summaryrefslogtreecommitdiffstats
path: root/kmymoney2/mymoney/storage/mymoneydatabasemgr.cpp
blob: e80feafd92e6d345999d656efd365e24bbefc568 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
/***************************************************************************
                          mymoneydatabasemgr.cpp
                             -------------------
    begin                : June 5 2007
    copyright            : (C) 2007 by Fernando Vilas
    email                : Fernando Vilas <fvilas@iname.com>
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
#include <typeinfo>
#include <algorithm>

#include "mymoneydatabasemgr.h"
#include "../mymoneytransactionfilter.h"
#include "../mymoneycategory.h"

#define TRY try {
#define CATCH } catch (MyMoneyException *e) {
#define PASS } catch (MyMoneyException *e) { throw; }

MyMoneyDatabaseMgr::MyMoneyDatabaseMgr() :
m_creationDate (TQDate::tqcurrentDate ()),
m_lastModificationDate (TQDate::tqcurrentDate ()),
m_sql (0)
{ }

MyMoneyDatabaseMgr::~MyMoneyDatabaseMgr()
{ }

  // general get functions
const MyMoneyPayee MyMoneyDatabaseMgr::user(void) const
{ return m_user; }

const TQDate MyMoneyDatabaseMgr::creationDate(void) const
{ return m_creationDate; }

const TQDate MyMoneyDatabaseMgr::lastModificationDate(void) const
{ return m_lastModificationDate; }

unsigned int MyMoneyDatabaseMgr::currentFixVersion(void) const
{ return CURRENT_FIX_VERSION; }

unsigned int MyMoneyDatabaseMgr::fileFixVersion(void) const
{ return m_fileFixVersion; }

  // general set functions
void MyMoneyDatabaseMgr::setUser(const MyMoneyPayee& user)
{
  m_user = user;
  if (m_sql != 0) m_sql->modifyUserInfo(user);
}

void MyMoneyDatabaseMgr::setFileFixVersion(const unsigned int v)
{ m_fileFixVersion = v; }

  // methods provided by MyMoneyKeyValueContainer
const TQString MyMoneyDatabaseMgr::value(const TQString& key) const
{
  return MyMoneyKeyValueContainer::value(key);
}

void MyMoneyDatabaseMgr::setValue(const TQString& key, const TQString& val)
{
  MyMoneyKeyValueContainer::setValue(key, val);
}

void MyMoneyDatabaseMgr::deletePair(const TQString& key)
{
  MyMoneyKeyValueContainer::deletePair(key);
}

const TQMap<TQString, TQString> MyMoneyDatabaseMgr::pairs(void) const
{
  return MyMoneyKeyValueContainer::pairs();
}

void MyMoneyDatabaseMgr::setPairs(const TQMap<TQString, TQString>& list)
{
  MyMoneyKeyValueContainer::setPairs(list);
}

MyMoneyDatabaseMgr const * MyMoneyDatabaseMgr::duplicate(void)
{
  MyMoneyDatabaseMgr* that = new MyMoneyDatabaseMgr();
  *that = *this;
  return that;
}

void MyMoneyDatabaseMgr::addAccount(MyMoneyAccount& account)
{
  if (m_sql) {
    // create the account.
    MyMoneyAccount newAccount(nextAccountID(), account);

    m_sql->addAccount(newAccount);
    account = newAccount;
  }
}

void MyMoneyDatabaseMgr::addAccount(MyMoneyAccount& tqparent, MyMoneyAccount& account)
{
  TQMap<TQString, MyMoneyAccount> accountList;
  TQStringList accountIdList;
  TQMap<TQString, MyMoneyAccount>::ConstIterator theParent;
  TQMap<TQString, MyMoneyAccount>::ConstIterator theChild;

  accountIdList << tqparent.id() << account.id();
  startTransaction();
  accountList = m_sql->fetchAccounts(accountIdList, true);

  theParent = accountList.tqfind(tqparent.id());
  if(theParent == accountList.end()) {
    TQString msg = "Unknown tqparent account '";
    msg += tqparent.id() + "'";
    throw new MYMONEYEXCEPTION(msg);
  }

  theChild = accountList.tqfind(account.id());
  if(theChild == accountList.end()) {
    TQString msg = "Unknown child account '";
    msg += account.id() + "'";
    throw new MYMONEYEXCEPTION(msg);
  }

  MyMoneyAccount acc = *theParent;
  acc.addAccountId(account.id());
  tqparent = acc;

  acc = *theChild;
  acc.setParentAccountId(tqparent.id());
  account = acc;

//FIXME:  MyMoneyBalanceCacheItem balance;
//FIXME:  m_balanceCache[account.id()] = balance;

  m_sql->modifyAccount(tqparent);
  m_sql->modifyAccount(account);
  commitTransaction();
}

void MyMoneyDatabaseMgr::addPayee(MyMoneyPayee& payee)
{
  if (m_sql) {
    // create the payee
    MyMoneyPayee newPayee(nextPayeeID(), payee);

    m_sql->addPayee(newPayee);
    payee = newPayee;
  }
}

const MyMoneyPayee MyMoneyDatabaseMgr::payee(const TQString& id) const
{
  TQMap<TQString, MyMoneyPayee>::ConstIterator it;
  TQMap<TQString, MyMoneyPayee> payeeList = m_sql->fetchPayees(TQString(id));
  it = payeeList.tqfind(id);
  if(it == payeeList.end())
    throw new MYMONEYEXCEPTION("Unknown payee '" + id + "'");

  return *it;
}

const MyMoneyPayee MyMoneyDatabaseMgr::payeeByName(const TQString& payee) const
{
  if(payee.isEmpty())
    return MyMoneyPayee::null;

  TQMap<TQString, MyMoneyPayee> payeeList;

  TRY
  payeeList = m_sql->fetchPayees();
  PASS

  TQMap<TQString, MyMoneyPayee>::ConstIterator it_p;

  for(it_p = payeeList.begin(); it_p != payeeList.end(); ++it_p) {
    if((*it_p).name() == payee) {
      return *it_p;
    }
  }

  throw new MYMONEYEXCEPTION("Unknown payee '" + payee + "'");
}

void MyMoneyDatabaseMgr::modifyPayee(const MyMoneyPayee& payee)
{
  TQMap<TQString, MyMoneyPayee> payeeList = m_sql->fetchPayees(TQString(payee.id()), true);
  TQMap<TQString, MyMoneyPayee>::ConstIterator it;

  it = payeeList.tqfind(payee.id());
  if(it == payeeList.end()) {
    TQString msg = "Unknown payee '" + payee.id() + "'";
    throw new MYMONEYEXCEPTION(msg);
  }

  m_sql->modifyPayee(payee);
}

void MyMoneyDatabaseMgr::removePayee(const MyMoneyPayee& payee)
{
  TQMap<TQString, MyMoneyTransaction>::ConstIterator it_t;
  TQMap<TQString, MyMoneySchedule>::ConstIterator it_s;
  TQMap<TQString, MyMoneyPayee> payeeList = m_sql->fetchPayees(TQString(payee.id()));
  TQMap<TQString, MyMoneyPayee>::ConstIterator it_p;

  it_p = payeeList.tqfind(payee.id());
  if(it_p == payeeList.end()) {
    TQString msg = "Unknown payee '" + payee.id() + "'";
    throw new MYMONEYEXCEPTION(msg);
  }

  // scan all transactions to check if the payee is still referenced
  TQMap<TQString, MyMoneyTransaction> transactionList = m_sql->fetchTransactions(); // make sure they're all here
  for(it_t = transactionList.begin(); it_t != transactionList.end(); ++it_t) {
    if((*it_t).hasReferenceTo(payee.id())) {
      throw new MYMONEYEXCEPTION(TQString("Cannot remove payee that is still referenced to a %1").tqarg("transaction"));
    }
  }
  
  // check referential integrity in schedules
  TQMap<TQString, MyMoneySchedule> scheduleList = m_sql->fetchSchedules(); // make sure they're all here
  for(it_s = scheduleList.begin(); it_s != scheduleList.end(); ++it_s) {
    if((*it_s).hasReferenceTo(payee.id())) {
      throw new MYMONEYEXCEPTION(TQString("Cannot remove payee that is still referenced to a %1").tqarg("schedule"));
    }
  }
  // remove any reference to report and/or budget
  removeReferences(payee.id());

  m_sql->removePayee(payee);
}

const TQValueList<MyMoneyPayee> MyMoneyDatabaseMgr::payeeList(void) const
{
  if (m_sql)
    return m_sql->fetchPayees().values();
  else
    return TQValueList<MyMoneyPayee> ();
}

const MyMoneyAccount MyMoneyDatabaseMgr::account(const TQString& id) const
{
  if (m_sql)
  {
    TQMap <TQString, MyMoneyAccount> accountList = m_sql->fetchAccounts(TQString(id));
    TQMap <TQString, MyMoneyAccount>::ConstIterator pos = accountList.tqfind(id);

    // locate the account and if present, return it's data
    if(pos != accountList.end())
      return *pos;
  }

  // throw an exception, if it does not exist
  TQString msg = "Unknown account id '" + id + "'";
  throw new MYMONEYEXCEPTION(msg);
}

bool MyMoneyDatabaseMgr::isStandardAccount(const TQString& id) const
{
  return id == STD_ACC_LIABILITY
      || id == STD_ACC_ASSET
      || id == STD_ACC_EXPENSE
      || id == STD_ACC_INCOME
      || id == STD_ACC_ETQUITY;
}

void MyMoneyDatabaseMgr::setAccountName(const TQString& id, const TQString& name)
{
  if(!isStandardAccount(id))
    throw new MYMONEYEXCEPTION("Only standard accounts can be modified using setAccountName()");

  if (m_sql) {
    startTransaction();
    MyMoneyAccount acc = m_sql->fetchAccounts(TQString(id), true) [id];
    acc.setName(name);
    m_sql->modifyAccount(acc);
    commitTransaction();
  }
}

void MyMoneyDatabaseMgr::addInstitution(MyMoneyInstitution& institution)
{
  if (m_sql) {
    MyMoneyInstitution newInstitution(nextInstitutionID(), institution);

    // mark file as changed
    m_sql->addInstitution (newInstitution);

    // return new data
    institution = newInstitution;
  }
}

const TQString MyMoneyDatabaseMgr::nextPayeeID(void)
{
  TQString id;
  if (m_sql) {
    id.setNum(ulong(m_sql->incrementPayeeId()));
    id = "P" + id.rightJustify(PAYEE_ID_SIZE, '0');
  }
  return id;
}

const TQString MyMoneyDatabaseMgr::nextInstitutionID(void)
{
  TQString id;
  if (m_sql) {
    id.setNum(ulong(m_sql->incrementInstitutionId()));
    id = "I" + id.rightJustify(INSTITUTION_ID_SIZE, '0');
  }
  return id;
}

const TQString MyMoneyDatabaseMgr::nextAccountID(void)
{
  TQString id;
  if (m_sql) {
    id.setNum(ulong(m_sql->incrementAccountId()));
    id = "A" + id.rightJustify(ACCOUNT_ID_SIZE, '0');
  }
  return id;
}

const TQString MyMoneyDatabaseMgr::nextBudgetID(void)
{
  TQString id;
  if (m_sql) {
    id.setNum(ulong(m_sql->incrementBudgetId()));
    id = "B" + id.rightJustify(BUDGET_ID_SIZE, '0');
  }
  return id;
}

const TQString MyMoneyDatabaseMgr::nextReportID(void)
{
  TQString id;
  if (m_sql) {
    id.setNum(ulong(m_sql->incrementReportId()));
    id = "R" + id.rightJustify(REPORT_ID_SIZE, '0');
  }
  return id;
}

const TQString MyMoneyDatabaseMgr::nextTransactionID(void)
{
  TQString id;
  if (m_sql) {
    id.setNum(ulong(m_sql->incrementTransactionId()));
    id = "T" + id.rightJustify(TRANSACTION_ID_SIZE, '0');
  }
  return id;
}

const TQString MyMoneyDatabaseMgr::nextScheduleID(void)
{
  TQString id;
  if (m_sql) {
    id.setNum(ulong(m_sql->incrementScheduleId()));
    id = "SCH" + id.rightJustify(SCHEDULE_ID_SIZE, '0');
  }
  return id;
}

const TQString MyMoneyDatabaseMgr::nextSecurityID(void)
{
  TQString id;
  if (m_sql) {
    id.setNum(ulong(m_sql->incrementSecurityId()));
    id = "E" + id.rightJustify(SECURITY_ID_SIZE, '0');
  }
  return id;
}

void MyMoneyDatabaseMgr::addTransaction(MyMoneyTransaction& transaction, const bool skipAccountUpdate)
{
  // perform some checks to see that the transaction stuff is OK. For
  // now we assume that
  // * no ids are assigned
  // * the date valid (must not be empty)
  // * the referenced accounts in the splits exist

  // first perform all the checks
  if(!transaction.id().isEmpty())
    throw new MYMONEYEXCEPTION("transaction already contains an id");
  if(!transaction.postDate().isValid())
    throw new MYMONEYEXCEPTION("invalid post date");

  // now check the splits
  TQValueList<MyMoneySplit>::ConstIterator it_s;
  for(it_s = transaction.splits().begin(); it_s != transaction.splits().end(); ++it_s) {
    // the following lines will throw an exception if the
    // account or payee do not exist
    account((*it_s).accountId());
    if(!(*it_s).payeeId().isEmpty())
      payee((*it_s).payeeId());
  }

  MyMoneyTransaction newTransaction(nextTransactionID(), transaction);
  TQString key = newTransaction.uniqueSortKey();

  m_sql->addTransaction(newTransaction);

  transaction = newTransaction;

  // adjust the balance of all affected accounts
  for(it_s = transaction.splits().begin(); it_s != transaction.splits().end(); ++it_s) {
    MyMoneyAccount acc = MyMoneyFile::instance()->account((*it_s).accountId());
    acc.adjustBalance((*it_s));
    if(!skipAccountUpdate) {
      acc.touch();
//FIXME:      tqinvalidateBalanceCache(acc.id());
    }
    m_sql->modifyAccount(acc);
  }
}

bool MyMoneyDatabaseMgr::hasActiveSplits(const TQString& id) const
{
  TQMap<TQString, MyMoneyTransaction>::ConstIterator it;

  MyMoneyTransactionFilter f(id);
  TQMap<TQString, MyMoneyTransaction> transactionList = m_sql->fetchTransactions(f);

  for(it = transactionList.begin(); it != transactionList.end(); ++it) {
    if((*it).accountReferenced(id)) {
      return true;
    }
  }
  return false;
}

  /**
    * This method is used to return the actual balance of an account
    * without it's sub-ordinate accounts. If a @p date is presented,
    * the balance at the beginning of this date (not including any
    * transaction on this date) is returned. Otherwise all recorded
    * transactions are included in the balance.
    *
    * @param id id of the account in question
    * @param date return balance for specific date
    * @return balance of the account as MyMoneyMoney object
    */
//const MyMoneyMoney MyMoneyDatabaseMgr::balance(const TQString& id, const TQDate& date);

const MyMoneyMoney MyMoneyDatabaseMgr::totalBalance(const TQString& id, const TQDate& date) const
{
  TQStringList accounts;
  TQStringList::ConstIterator it_a;

  MyMoneyMoney result; //(balance(id, date));

  accounts = MyMoneyFile::instance()->account(id).accountList();
  for (it_a = accounts.begin(); it_a != accounts.end(); ++it_a) {
    accounts += MyMoneyFile::instance()->account(*it_a).accountList();
  }
  std::list <TQString> tempList (accounts.begin(), accounts.end());
  tempList.sort();;
  tempList.unique();

  accounts = TQStringList(tempList);

  TQMap<TQString, MyMoneyMoney> balanceMap = m_sql->fetchBalance(accounts, date);
  for (TQMap<TQString, MyMoneyMoney>::ConstIterator it_b = balanceMap.begin(); it_b != balanceMap.end(); ++it_b) {
    result += it_b.data();
  }

  return result;
}

const MyMoneyInstitution MyMoneyDatabaseMgr::institution(const TQString& id) const
{
  TQMap<TQString, MyMoneyInstitution>::ConstIterator pos;
  TQMap<TQString, MyMoneyInstitution> institutionList = m_sql->fetchInstitutions(TQString(id));

  pos = institutionList.tqfind(id);
  if(pos != institutionList.end())
    return *pos;
  throw new MYMONEYEXCEPTION("unknown institution");
}

bool MyMoneyDatabaseMgr::dirty(void) const
{ return false; }

void MyMoneyDatabaseMgr::setDirty(void)
{}

unsigned int MyMoneyDatabaseMgr::accountCount(void) const
{
  return m_sql->getRecCount("kmmAccounts");
}

const TQValueList<MyMoneyInstitution> MyMoneyDatabaseMgr::institutionList(void) const
{
  if (m_sql) {
    return m_sql->fetchInstitutions().values();
  } else {
    return TQValueList<MyMoneyInstitution> ();
  }
}

void MyMoneyDatabaseMgr::modifyAccount(const MyMoneyAccount& account, const bool skipCheck)
{
  TQMap<TQString, MyMoneyAccount>::ConstIterator pos;

  // locate the account in the file global pool
  startTransaction();
  TQMap<TQString, MyMoneyAccount> accountList = m_sql->fetchAccounts (TQString(account.id()), true);
  pos = accountList.tqfind(account.id());
  if(pos != accountList.end()) {
    // check if the new info is based on the old one.
    // this is the case, when the file and the id
    // as well as the type are equal.
    if(((*pos).tqparentAccountId() == account.tqparentAccountId()
    && (*pos).accountType() == account.accountType())
    || skipCheck == true) {
      // make sure that all the referenced objects exist
      if(!account.institutionId().isEmpty())
        institution(account.institutionId());

      TQValueList<TQString>::ConstIterator it_a;
      for(it_a = account.accountList().begin(); it_a != account.accountList().end(); ++it_a) {
        this->account(*it_a);
      }

      // update information in account list
      //m_accountList.modify(account.id(), account);

      // tqinvalidate cached balance
//FIXME:      tqinvalidateBalanceCache(account.id());

      // mark file as changed
      m_sql->modifyAccount(account);
      commitTransaction();
    } else {
      rollbackTransaction();
      throw new MYMONEYEXCEPTION("Invalid information for update");
    }

  } else {
    rollbackTransaction();
    throw new MYMONEYEXCEPTION("Unknown account id");
  }
}

void MyMoneyDatabaseMgr::modifyInstitution(const MyMoneyInstitution& institution)
{
  TQMap<TQString, MyMoneyInstitution> institutionList = m_sql->fetchInstitutions(TQString(institution.id()));
  TQMap<TQString, MyMoneyInstitution>::ConstIterator pos;

  // locate the institution in the file global pool
  pos = institutionList.tqfind(institution.id());
  if(pos != institutionList.end()) {
    m_sql->modifyInstitution(institution);
  } else
    throw new MYMONEYEXCEPTION("unknown institution");
}

  /**
    * This method is used to update a specific transaction in the
    * transaction pool of the MyMoneyFile object
    *
    * An exception will be thrown upon error conditions.
    *
    * @param transaction reference to transaction to be changed
    */
void MyMoneyDatabaseMgr::modifyTransaction(const MyMoneyTransaction& transaction)
{
  TQMap<TQString, bool> modifiedAccounts;

  // perform some checks to see that the transaction stuff is OK. For
  // now we assume that
  // * ids are assigned
  // * the pointer to the MyMoneyFile object is not 0
  // * the date valid (must not be empty)
  // * the splits must have valid account ids

  // first perform all the checks
  if(transaction.id().isEmpty()
//  || transaction.file() != this
  || !transaction.postDate().isValid())
    throw new MYMONEYEXCEPTION("invalid transaction to be modified");

  // now check the splits
  TQValueList<MyMoneySplit>::ConstIterator it_s;
  for(it_s = transaction.splits().begin(); it_s != transaction.splits().end(); ++it_s) {
    // the following lines will throw an exception if the
    // account or payee do not exist
    MyMoneyFile::instance()->account((*it_s).accountId());
    if(!(*it_s).payeeId().isEmpty())
      MyMoneyFile::instance()->payee((*it_s).payeeId());
  }

  // new data seems to be ok. find old version of transaction
  // in our pool. Throw exception if unknown.
//  if(!m_transactionKeys.tqcontains(transaction.id()))
//    throw new MYMONEYEXCEPTION("invalid transaction id");

//  TQString oldKey = m_transactionKeys[transaction.id()];
  TQMap <TQString, MyMoneyTransaction> transactionList = m_sql->fetchTransactions("('" + TQString(transaction.id()) + "')");
//  if(transactionList.size() != 1)
//    throw new MYMONEYEXCEPTION("invalid transaction key");

  TQMap<TQString, MyMoneyTransaction>::ConstIterator it_t;

//  it_t = transactionList.tqfind(oldKey);
  it_t = transactionList.begin();
  if(it_t == transactionList.end())
    throw new MYMONEYEXCEPTION("invalid transaction key");

  // mark all accounts referenced in old and new transaction data
  // as modified
  TQMap<TQString, MyMoneyAccount> accountList = m_sql->fetchAccounts();
  for(it_s = (*it_t).splits().begin(); it_s != (*it_t).splits().end(); ++it_s) {
    MyMoneyAccount acc = accountList[(*it_s).accountId()];
    acc.adjustBalance((*it_s), true);
    acc.touch();
//FIXME:    tqinvalidateBalanceCache(acc.id());
    //m_accountList.modify(acc.id(), acc);
    m_sql->modifyAccount(acc);
    //modifiedAccounts[(*it_s).accountId()] = true;
  }
  for(it_s = transaction.splits().begin(); it_s != transaction.splits().end(); ++it_s) {
    MyMoneyAccount acc = accountList[(*it_s).accountId()];
    acc.adjustBalance((*it_s));
    acc.touch();
//FIXME:    tqinvalidateBalanceCache(acc.id());
    //m_accountList.modify(acc.id(), acc);
    m_sql->modifyAccount(acc);
    //modifiedAccounts[(*it_s).accountId()] = true;
  }

  // remove old transaction from lists
//  m_sql->removeTransaction(oldKey);

  // add new transaction to lists
 // TQString newKey = transaction.uniqueSortKey();
//  m_sql->insertTransaction(newKey, transaction);
  //m_transactionKeys.modify(transaction.id(), newKey);

  // mark file as changed
  m_sql->modifyTransaction(transaction);
}

void MyMoneyDatabaseMgr::reparentAccount(MyMoneyAccount &account, MyMoneyAccount& tqparent)
{
  if(account.accountType() == MyMoneyAccount::Stock && tqparent.accountType() != MyMoneyAccount::Investment)
    throw new MYMONEYEXCEPTION("Cannot move a stock acocunt into a non-investment account");

  TQStringList accountIdList;
  TQMap<TQString, MyMoneyAccount>::ConstIterator oldParent;
  TQMap<TQString, MyMoneyAccount>::ConstIterator newParent;
  TQMap<TQString, MyMoneyAccount>::ConstIterator childAccount;

  // verify that accounts exist. If one does not,
  // an exception is thrown
  accountIdList << account.id() << tqparent.id();
  MyMoneyDatabaseMgr::account(account.id());
  MyMoneyDatabaseMgr::account(tqparent.id());

  if(!account.tqparentAccountId().isEmpty()) {
    accountIdList << account.tqparentAccountId();
  }

  startTransaction();
  TQMap<TQString, MyMoneyAccount> accountList = m_sql->fetchAccounts(accountIdList, true);

  if(!account.tqparentAccountId().isEmpty()) {
    MyMoneyDatabaseMgr::account(account.tqparentAccountId());
    oldParent = accountList.tqfind(account.tqparentAccountId());
  }

  newParent = accountList.tqfind(tqparent.id());
  childAccount = accountList.tqfind(account.id());

  MyMoneyAccount acc;
  if(!account.tqparentAccountId().isEmpty()) {
    acc = (*oldParent);
    acc.removeAccountId(account.id());
    m_sql->modifyAccount(acc);
  }

  tqparent = (*newParent);
  tqparent.addAccountId(account.id());

  account = (*childAccount);
  account.setParentAccountId(tqparent.id());

  m_sql->modifyAccount(tqparent);
  m_sql->modifyAccount(account);
  commitTransaction();
}

void MyMoneyDatabaseMgr::removeTransaction(const MyMoneyTransaction& transaction)
{
  TQMap<TQString, bool> modifiedAccounts;

  // first perform all the checks
  if(transaction.id().isEmpty())
    throw new MYMONEYEXCEPTION("invalid transaction to be deleted");

  TQMap<TQString, TQString>::ConstIterator it_k;
  TQMap<TQString, MyMoneyTransaction>::ConstIterator it_t;

//  it_k = m_transactionKeys.tqfind(transaction.id());
//  if(it_k == m_transactionKeys.end())
//    throw new MYMONEYEXCEPTION("invalid transaction to be deleted");

  TQMap <TQString, MyMoneyTransaction> transactionList = m_sql->fetchTransactions("('" + TQString(transaction.id()) + "')");
//  it_t = transactionList.tqfind(*it_k);
  it_t = transactionList.begin();
  if(it_t == transactionList.end())
    throw new MYMONEYEXCEPTION("invalid transaction key");

  TQValueList<MyMoneySplit>::ConstIterator it_s;

  // scan the splits and collect all accounts that need
  // to be updated after the removal of this transaction
  TQMap<TQString, MyMoneyAccount> accountList = m_sql->fetchAccounts();
  for(it_s = (*it_t).splits().begin(); it_s != (*it_t).splits().end(); ++it_s) {
    MyMoneyAccount acc = accountList[(*it_s).accountId()];
//    modifiedAccounts[(*it_s).accountId()] = true;
    acc.adjustBalance((*it_s), true);
    acc.touch();
    m_sql->modifyAccount(acc);
//FIXME:    tqinvalidateBalanceCache(acc.id());
  }

  // FIXME: check if any split is frozen and throw exception

  // remove the transaction from the two lists
  //m_transactionList.remove(*it_k);
//  m_transactionKeys.remove(transaction.id());

  // mark file as changed
  m_sql->removeTransaction(transaction);
}

unsigned int MyMoneyDatabaseMgr::transactionCount(const TQString& account) const
{ return (m_sql->transactionCount(account)); }

const TQMap<TQString, unsigned long> MyMoneyDatabaseMgr::transactionCountMap(void) const
{ return (m_sql->transactionCountMap()); }

const TQValueList<MyMoneyTransaction> MyMoneyDatabaseMgr::transactionList(MyMoneyTransactionFilter& filter) const
{
  TQValueList<MyMoneyTransaction> list;
  transactionList(list, filter);
  return list;
}

void MyMoneyDatabaseMgr::transactionList(TQValueList<MyMoneyTransaction>& list, MyMoneyTransactionFilter& filter) const
{
  list.clear();

  TRY
  if (m_sql) list = m_sql->fetchTransactions(filter).values();
  PASS
}

void MyMoneyDatabaseMgr::transactionList(TQValueList<TQPair<MyMoneyTransaction, MyMoneySplit> >& list, MyMoneyTransactionFilter& filter) const
{
  list.clear();
  MyMoneyMap<TQString, MyMoneyTransaction> transactionList;
  TRY
  if (m_sql) transactionList = m_sql->fetchTransactions(filter);
  PASS

  TQMap<TQString, MyMoneyTransaction>::ConstIterator it_t;
  TQMap<TQString, MyMoneyTransaction>::ConstIterator txEnd = transactionList.end();

  for(it_t = transactionList.begin(); it_t != txEnd; ++it_t) {
    if(filter.match(*it_t)) {
      TQValueList<MyMoneySplit>::const_iterator it_s;
      for(it_s = filter.matchingSplits().begin(); it_s != filter.matchingSplits().end(); ++it_s) {
        list.append(tqMakePair(*it_t, *it_s));
      }
    }
  }
}

void MyMoneyDatabaseMgr::removeAccount(const MyMoneyAccount& account)
{
  MyMoneyAccount tqparent;

  // check that the account and it's tqparent exist
  // this will throw an exception if the id is unknown
  MyMoneyDatabaseMgr::account(account.id());
  tqparent = MyMoneyDatabaseMgr::account(account.tqparentAccountId());

  // check that it's not one of the standard account groups
  if(isStandardAccount(account.id()))
    throw new MYMONEYEXCEPTION("Unable to remove the standard account groups");

  if(hasActiveSplits(account.id())) {
    throw new MYMONEYEXCEPTION("Unable to remove account with active splits");
  }

  // re-tqparent all sub-ordinate accounts to the tqparent of the account
  // to be deleted. First round check that all accounts exist, second
  // round do the re-tqparenting.
  TQStringList::ConstIterator it;
  for(it = account.accountList().begin(); it != account.accountList().end(); ++it) {
    MyMoneyDatabaseMgr::account(*it);
  }

  // if one of the accounts did not exist, an exception had been
  // thrown and we would not make it until here.

  TQStringList accountIdList;
  accountIdList << tqparent.id() << account.id();
  startTransaction();
  TQMap<TQString, MyMoneyAccount> accountList = m_sql->fetchAccounts(accountIdList, true);

  TQMap<TQString, MyMoneyAccount>::ConstIterator it_a;
  TQMap<TQString, MyMoneyAccount>::ConstIterator it_p;

  // locate the account in the file global pool

  it_a = accountList.tqfind(account.id());
  if(it_a == accountList.end())
    throw new MYMONEYEXCEPTION("Internal error: account not found in list");

  it_p = accountList.tqfind(tqparent.id());
  if(it_p == accountList.end())
    throw new MYMONEYEXCEPTION("Internal error: tqparent account not found in list");

  if(!account.institutionId().isEmpty())
    throw new MYMONEYEXCEPTION("Cannot remove account still attached to an institution");

  // FIXME: check referential integrity for the account to be removed

  // check if the new info is based on the old one.
  // this is the case, when the file and the id
  // as well as the type are equal.
  if((*it_a).id() == account.id()
  && (*it_a).accountType() == account.accountType()) {

    // second round over sub-ordinate accounts: do re-tqparenting
    // but only if the list contains at least one entry
    // FIXME: move this logic to MyMoneyFile
    if((*it_a).accountList().count() > 0) {
      for(it = (*it_a).accountList().begin(); it != (*it_a).accountList().end(); ++it) {
        MyMoneyAccount acc(MyMoneyDatabaseMgr::account(*it));
        reparentAccount(acc, tqparent);//, false);
      }
    }
    // remove account from tqparent's list
    tqparent.removeAccountId(account.id());
    m_sql->modifyAccount(tqparent);

    // remove account from the global account pool
    //m_accountList.remove(account.id());

    // remove from balance list
//FIXME:    m_balanceCache.remove(account.id());
//FIXME:    tqinvalidateBalanceCache(tqparent.id());

    m_sql->removeAccount(account);
  }
  commitTransaction();
}

void MyMoneyDatabaseMgr::removeInstitution(const MyMoneyInstitution& institution)
{
  TQMap<TQString, MyMoneyInstitution> institutionList = m_sql->fetchInstitutions(TQString(institution.id()));
  TQMap<TQString, MyMoneyInstitution>::ConstIterator it_i;

  it_i = institutionList.tqfind(institution.id());
  if(it_i != institutionList.end()) {
    // mark file as changed
    m_sql->removeInstitution(institution);
  } else
    throw new MYMONEYEXCEPTION("invalid institution");
}

const MyMoneyTransaction MyMoneyDatabaseMgr::transaction(const TQString& id) const
{
  // get the full key of this transaction, throw exception
  // if it's invalid (unknown)
  //if(!m_transactionKeys.tqcontains(id))
  //  throw new MYMONEYEXCEPTION("invalid transaction id");

  // check if this key is in the list, throw exception if not
  //TQString key = m_transactionKeys[id];
  TQMap <TQString, MyMoneyTransaction> transactionList = m_sql->fetchTransactions("('" + TQString(id) + "')");

  //there should only be one transaction in the map, if it was found, so check the size of the map
  //return the first element.
  //if(!transactionList.tqcontains(key))
  if(!transactionList.size())
    throw new MYMONEYEXCEPTION("invalid transaction key");

  return transactionList.begin().data();
}

const MyMoneyMoney MyMoneyDatabaseMgr::balance(const TQString& id, const TQDate& date) const
{
  TQStringList idList;
  idList.append(id);
  TQMap<TQString,MyMoneyMoney> tempMap = m_sql->fetchBalance(idList, date);

  MyMoneyMoney returnValue = tempMap[id];
  if (returnValue != MyMoneyMoney()) {
    return returnValue;
  }

//DEBUG
  TQDate date_ (date);
  //if (date_ == TQDate()) date_ = TQDate::tqcurrentDate();
// END DEBUG

  MyMoneyMoney result(0);
  MyMoneyAccount acc;
  TQMap<TQString, MyMoneyAccount> accountList = m_sql->fetchAccounts(/*TQString(id)*/);
  //TQMap<TQString, MyMoneyAccount>::const_iterator accpos = accountList.tqfind(id);
  if (date_ != TQDate()) qDebug ("request balance for %s at %s", id.data(), TQString(date_.toString(Qt::ISODate)).latin1());
//  if(!date_.isValid() && MyMoneyFile::instance()->account(id).accountType() != MyMoneyAccount::Stock) {
//    if(accountList.tqfind(id) != accountList.end())
//      return accountList[id].balance();
//    return MyMoneyMoney(0);
//  }
  if(/*m_balanceCache[id].valid == false || date != m_balanceCacheDate) || */ m_sql != 0) {
    TQMap<TQString, MyMoneyMoney> balances;
    TQMap<TQString, MyMoneyMoney>::ConstIterator it_b;
//FIXME:    if (date != m_balanceCacheDate) {
//FIXME:      m_balanceCache.clear();
//FIXME:      m_balanceCacheDate = date;
//FIXME:    }

    TQValueList<MyMoneyTransaction>::ConstIterator it_t;
    TQValueList<MyMoneyTransaction>::ConstIterator txEnd;
    TQValueList<MyMoneySplit>::ConstIterator it_s;

    MyMoneyTransactionFilter filter;
    filter.addAccount(id);
    filter.setDateFilter(TQDate(), date_);
    filter.setReportAllSplits(false);
    TQValueList<MyMoneyTransaction> list = transactionList(filter);

    txEnd = list.end();
    for(it_t = list.begin(); it_t != txEnd; ++it_t) {
      for(it_s = (*it_t).splits().begin(); it_s != (*it_t).splits().end(); ++it_s){
        const TQString aid = (*it_s).accountId();
        if((*it_s).action() == MyMoneySplit::ActionSplitShares) {
          balances[aid] = balances[aid] * (*it_s).shares();
        } else {
          balances[aid] += (*it_s).value((*it_t).commodity(), accountList[aid].currencyId());
        }
      }
    }

    // fill the found balances into the cache
//FIXME:    for(it_b = balances.begin(); it_b != balances.end(); ++it_b) {
//FIXME:      MyMoneyBalanceCacheItem balance(*it_b);
//FIXME:      m_balanceCache[it_b.key()] = balance;
//FIXME:    }

    // fill all accounts w/o transactions to zero
//    if (m_sql != 0) {
//      TQMap<TQString, MyMoneyAccount>::ConstIterator it_a;
//      for(it_a = m_accountList.begin(); it_a != m_accountList.end(); ++it_a) {
//FIXME:        if(m_balanceCache[(*it_a).id()].valid == false) {
//FIXME:          MyMoneyBalanceCacheItem balance(MyMoneyMoney(0,1));
//FIXME:          m_balanceCache[(*it_a).id()] = balance;
//FIXME:        }
//      }
//    }

  result = balances[id];

  }

//FIXME:  if(m_balanceCache[id].valid == true)
//FIXME:    result = m_balanceCache[id].balance;
//FIXME:  else
//FIXME:    qDebug("Cache mishit should never happen at this point");

  return result;
}

const MyMoneyTransaction MyMoneyDatabaseMgr::transaction(const TQString& account, const int idx) const
{
/* removed with MyMoneyAccount::Transaction
  TQMap<TQString, MyMoneyAccount>::ConstIterator acc;

  // find account object in list, throw exception if unknown
  acc = m_accountList.tqfind(account);
  if(acc == m_accountList.end())
    throw new MYMONEYEXCEPTION("unknown account id");

  // get the transaction info from the account
  MyMoneyAccount::Transaction t = (*acc).transaction(idx);

  // return the transaction, throw exception if not found
  return transaction(t.transactionID());
*/

  // new implementation if the above code does not work anymore
  TQValueList<MyMoneyTransaction> list;
  //MyMoneyAccount acc = m_accountList[account];
  MyMoneyAccount acc = m_sql->fetchAccounts(TQString(account)) [account];
  MyMoneyTransactionFilter filter;

  if(acc.accountGroup() == MyMoneyAccount::Income
  || acc.accountGroup() == MyMoneyAccount::Expense)
    filter.addCategory(account);
  else
    filter.addAccount(account);

  transactionList(list, filter);
  if(idx < 0 || idx >= static_cast<int> (list.count()))
    throw new MYMONEYEXCEPTION("Unknown idx for transaction");

  return transaction(list[idx].id());
}

unsigned int MyMoneyDatabaseMgr::institutionCount(void) const
{
  return m_sql->getRecCount("kmmInstitutions");
}

void MyMoneyDatabaseMgr::accountList(TQValueList<MyMoneyAccount>& list) const
{
  TQMap <TQString, MyMoneyAccount> accountList;
  if (m_sql) accountList  = m_sql->fetchAccounts();
  TQMap<TQString, MyMoneyAccount>::ConstIterator it;
  TQMap<TQString, MyMoneyAccount>::ConstIterator accEnd = accountList.end();
  for(it = accountList.begin(); it != accEnd; ++it) {
    if(!isStandardAccount((*it).id())) {
      list.append(*it);
    }
  }
}

const MyMoneyAccount MyMoneyDatabaseMgr::liability(void) const
{ return MyMoneyFile::instance()->account(STD_ACC_LIABILITY); }

const MyMoneyAccount MyMoneyDatabaseMgr::asset(void) const
{ return MyMoneyFile::instance()->account(STD_ACC_ASSET); }

const MyMoneyAccount MyMoneyDatabaseMgr::expense(void) const
{ return MyMoneyFile::instance()->account(STD_ACC_EXPENSE); }

const MyMoneyAccount MyMoneyDatabaseMgr::income(void) const
{ return MyMoneyFile::instance()->account(STD_ACC_INCOME); }

const MyMoneyAccount MyMoneyDatabaseMgr::equity(void) const
{ return MyMoneyFile::instance()->account(STD_ACC_ETQUITY); }

void MyMoneyDatabaseMgr::addSecurity(MyMoneySecurity& security)
{
  // create the account
  MyMoneySecurity newSecurity(nextSecurityID(), security);

  m_sql->addSecurity(newSecurity);
  security = newSecurity;
}

void MyMoneyDatabaseMgr::modifySecurity(const MyMoneySecurity& security)
{
  TQMap<TQString, MyMoneySecurity> securitiesList = m_sql->fetchSecurities(TQString(security.id()), true);
  TQMap<TQString, MyMoneySecurity>::ConstIterator it;

  it = securitiesList.tqfind(security.id());
  if(it == securitiesList.end())
  {
    TQString msg = "Unknown security  '";
    msg += security.id() + "' during modifySecurity()";
    throw new MYMONEYEXCEPTION(msg);
  }

  m_sql->modifySecurity(security);
}

void MyMoneyDatabaseMgr::removeSecurity(const MyMoneySecurity& security)
{
  TQMap<TQString, MyMoneySecurity> securitiesList = m_sql->fetchSecurities(TQString(security.id()));
  TQMap<TQString, MyMoneySecurity>::ConstIterator it;

  // FIXME: check referential integrity

  it = securitiesList.tqfind(security.id());
  if(it == securitiesList.end())
  {
    TQString msg = "Unknown security  '";
    msg += security.id() + "' during removeSecurity()";
    throw new MYMONEYEXCEPTION(msg);
  }

  m_sql->removeSecurity(security);
}

const MyMoneySecurity MyMoneyDatabaseMgr::security(const TQString& id) const
{
  TQMap<TQString, MyMoneySecurity> securitiesList = m_sql->fetchSecurities(TQString(id));
  TQMap<TQString, MyMoneySecurity>::ConstIterator it = securitiesList.tqfind(id);
  if(it != securitiesList.end())
  {
    return it.data();
  }

  return MyMoneySecurity();
}

const TQValueList<MyMoneySecurity> MyMoneyDatabaseMgr::securityList(void) const
{ return m_sql->fetchSecurities().values(); }

void MyMoneyDatabaseMgr::addPrice(const MyMoneyPrice& price)
{
  MyMoneyPriceEntries::ConstIterator it;
  MyMoneyPriceList priceList = m_sql->fetchPrices();
  it = priceList[MyMoneySecurityPair(price.from(), price.to())].tqfind(price.date());
  // do not tqreplace, if the information did not change.
  if(it != priceList[MyMoneySecurityPair(price.from(), price.to())].end()) {
    if((*it).rate((*it).to()) == price.rate(price.to())
    && (*it).source() == price.source())
      return;
  }

  m_sql->addPrice(price);
}

void MyMoneyDatabaseMgr::removePrice(const MyMoneyPrice& price)
{
  m_sql->removePrice(price);
}

const MyMoneyPrice MyMoneyDatabaseMgr::price(const TQString& fromId, const TQString& toId, const TQDate& _date, const bool exactDate) const
{
  return m_sql->fetchSinglePrice(fromId, toId, _date, exactDate);
}

const MyMoneyPriceList MyMoneyDatabaseMgr::priceList(void) const
{ return m_sql->fetchPrices(); }

void MyMoneyDatabaseMgr::addSchedule(MyMoneySchedule& sched)
{
  // first perform all the checks
  if(!sched.id().isEmpty())
    throw new MYMONEYEXCEPTION("schedule already contains an id");

  // The following will throw an exception when it fails
  sched.validate(false);

  if (m_sql) {
    startTransaction();
    sched = MyMoneySchedule (nextScheduleID(), sched);

    m_sql->addSchedule(sched);
    commitTransaction();
  }
}

void MyMoneyDatabaseMgr::modifySchedule(const MyMoneySchedule& sched)
{
  TQMap<TQString, MyMoneySchedule> scheduleList = m_sql->fetchSchedules(TQString(sched.id()));
  TQMap<TQString, MyMoneySchedule>::ConstIterator it;

  it = scheduleList.tqfind(sched.id());
  if(it == scheduleList.end()) {
    TQString msg = "Unknown schedule '" + sched.id() + "'";
    throw new MYMONEYEXCEPTION(msg);
  }

  m_sql->modifySchedule(sched);
}

void MyMoneyDatabaseMgr::removeSchedule(const MyMoneySchedule& sched)
{
  TQMap<TQString, MyMoneySchedule> scheduleList = m_sql->fetchSchedules(TQString(sched.id()));
  TQMap<TQString, MyMoneySchedule>::ConstIterator it;

  it = scheduleList.tqfind(sched.id());
  if(it == scheduleList.end()) {
    TQString msg = "Unknown schedule '" + sched.id() + "'";
    throw new MYMONEYEXCEPTION(msg);
  }

  // FIXME: check referential integrity for loan accounts

  m_sql->removeSchedule(sched);
}

const MyMoneySchedule MyMoneyDatabaseMgr::schedule(const TQString& id) const
{
  TQMap<TQString, MyMoneySchedule> scheduleList = m_sql->fetchSchedules(TQString(id));
  TQMap<TQString, MyMoneySchedule>::ConstIterator pos;

  // locate the schedule and if present, return it's data
  pos = scheduleList.tqfind(id);
  if(pos != scheduleList.end())
    return (*pos);

  // throw an exception, if it does not exist
  TQString msg = "Unknown schedule id '" + id + "'";
  throw new MYMONEYEXCEPTION(msg);
}

const TQValueList<MyMoneySchedule> MyMoneyDatabaseMgr::scheduleList(const TQString& accountId,
                                     const MyMoneySchedule::typeE type,
                                     const MyMoneySchedule::occurenceE occurence,
                                     const MyMoneySchedule::paymentTypeE paymentType,
                                     const TQDate& startDate,
                                     const TQDate& endDate,
                                     const bool overdue) const
{
  TQMap<TQString, MyMoneySchedule> scheduleList;
  if (m_sql) scheduleList = m_sql->fetchSchedules();
  TQMap<TQString, MyMoneySchedule>::ConstIterator pos;
  TQValueList<MyMoneySchedule> list;

  // qDebug("scheduleList()");

  for(pos = scheduleList.begin(); pos != scheduleList.end(); ++pos) {
    // qDebug("  '%s'", (*pos).id().data());

    if(type != MyMoneySchedule::TYPE_ANY) {
      if(type != (*pos).type()) {
        continue;
      }
    }

    if(occurence != MyMoneySchedule::OCCUR_ANY) {
      if(occurence != (*pos).occurence()) {
        continue;
      }
    }

    if(paymentType != MyMoneySchedule::STYPE_ANY) {
      if(paymentType != (*pos).paymentType()) {
        continue;
      }
    }

    if(!accountId.isEmpty()) {
      MyMoneyTransaction t = (*pos).transaction();
      TQValueList<MyMoneySplit>::ConstIterator it;
      TQValueList<MyMoneySplit> splits;
      splits = t.splits();
      for(it = splits.begin(); it != splits.end(); ++it) {
        if((*it).accountId() == accountId)
          break;
      }
      if(it == splits.end()) {
        continue;
      }
    }

    if(startDate.isValid() && endDate.isValid()) {
      if((*pos).paymentDates(startDate, endDate).count() == 0) {
        continue;
      }
    }

    if(startDate.isValid() && !endDate.isValid()) {
      if(!(*pos).nextPayment(startDate.addDays(-1)).isValid()) {
        continue;
      }
    }

    if(!startDate.isValid() && endDate.isValid()) {
      if((*pos).startDate() > endDate) {
        continue;
      }
    }

    if(overdue) {
      if (!(*pos).isOverdue())
        continue;
/*
      TQDate nextPayment = (*pos).nextPayment((*pos).lastPayment());
      if(!nextPayment.isValid())
        continue;
      if(nextPayment >= TQDate::tqcurrentDate())
        continue;
*/
    }

    // qDebug("Adding '%s'", (*pos).name().latin1());
    list << *pos;
  }
  return list;
}

const TQValueList<MyMoneySchedule> MyMoneyDatabaseMgr::scheduleListEx( int scheduleTypes,
                                              int scheduleOcurrences,
                                              int schedulePaymentTypes,
                                              TQDate startDate,
                                              const TQStringList& accounts) const
{
//  qDebug("scheduleListEx");
  TQMap<TQString, MyMoneySchedule> scheduleList = m_sql->fetchSchedules();
  TQMap<TQString, MyMoneySchedule>::ConstIterator pos;
  TQValueList<MyMoneySchedule> list;

  if (!startDate.isValid())
    return list;

  for(pos = scheduleList.begin(); pos != scheduleList.end(); ++pos)
  {
    if (scheduleTypes && !(scheduleTypes & (*pos).type()))
      continue;

    if (scheduleOcurrences && !(scheduleOcurrences & (*pos).occurence()))
      continue;

    if (schedulePaymentTypes && !(schedulePaymentTypes & (*pos).paymentType()))
      continue;

    if((*pos).paymentDates(startDate, startDate).count() == 0)
      continue;

    if ((*pos).isFinished())
      continue;

    if ((*pos).hasRecordedPayment(startDate))
      continue;

    if (accounts.count() > 0)
    {
      if (accounts.tqcontains((*pos).account().id()))
        continue;
    }

//    qDebug("\tAdding '%s'", (*pos).name().latin1());
    list << *pos;
  }

  return list;
}

void MyMoneyDatabaseMgr::addCurrency(const MyMoneySecurity& currency)
{
  if (m_sql) {
    TQMap<TQString, MyMoneySecurity> currencyList = m_sql->fetchCurrencies(TQString(currency.id()));
    TQMap<TQString, MyMoneySecurity>::ConstIterator it;

    it = currencyList.tqfind(currency.id());
    if(it != currencyList.end()) {
      throw new MYMONEYEXCEPTION(TQString("Cannot add currency with existing id %1").tqarg(currency.id()));
    }

    m_sql->addCurrency(currency);
  }
}

void MyMoneyDatabaseMgr::modifyCurrency(const MyMoneySecurity& currency)
{
  TQMap<TQString, MyMoneySecurity> currencyList = m_sql->fetchCurrencies(TQString(currency.id()));
  TQMap<TQString, MyMoneySecurity>::ConstIterator it;

  it = currencyList.tqfind(currency.id());
  if(it == currencyList.end()) {
    throw new MYMONEYEXCEPTION(TQString("Cannot modify currency with unknown id %1").tqarg(currency.id()));
  }

  m_sql->modifyCurrency(currency);
}

void MyMoneyDatabaseMgr::removeCurrency(const MyMoneySecurity& currency)
{
  TQMap<TQString, MyMoneySecurity> currencyList = m_sql->fetchCurrencies(TQString(currency.id()));
  TQMap<TQString, MyMoneySecurity>::ConstIterator it;

  // FIXME: check referential integrity

  it = currencyList.tqfind(currency.id());
  if(it == currencyList.end()) {
    throw new MYMONEYEXCEPTION(TQString("Cannot remove currency with unknown id %1").tqarg(currency.id()));
  }

  m_sql->removeCurrency(currency);
}

const MyMoneySecurity MyMoneyDatabaseMgr::currency(const TQString& id) const
{
  if(id.isEmpty()) {

  }
  TQMap<TQString, MyMoneySecurity> currencyList = m_sql->fetchCurrencies(TQString(id));
  TQMap<TQString, MyMoneySecurity>::ConstIterator it;

  it = currencyList.tqfind(id);
  if(it == currencyList.end()) {
    throw new MYMONEYEXCEPTION(TQString("Cannot retrieve currency with unknown id '%1'").tqarg(id));
  }

  return *it;
}

const TQValueList<MyMoneySecurity> MyMoneyDatabaseMgr::currencyList(void) const
{
  if (m_sql) {
    return m_sql->fetchCurrencies().values();
  } else {
    return TQValueList<MyMoneySecurity> ();
  }
}

const TQValueList<MyMoneyReport> MyMoneyDatabaseMgr::reportList( void ) const
{
  if (m_sql) {
    return m_sql->fetchReports().values();
  } else {
    return TQValueList<MyMoneyReport> ();
  }
}

void MyMoneyDatabaseMgr::addReport( MyMoneyReport& report )
{
  if(!report.id().isEmpty())
    throw new MYMONEYEXCEPTION("transaction already contains an id");

  MyMoneyReport newReport(nextReportID(), report);
  report = newReport;
  m_sql->addReport(newReport);
  //m_sql->addReport(MyMoneyReport (nextReportID(), report));
}

void MyMoneyDatabaseMgr::modifyReport( const MyMoneyReport& report )
{
  TQMap<TQString, MyMoneyReport> reportList = m_sql->fetchReports(TQString(report.id()));
  TQMap<TQString, MyMoneyReport>::ConstIterator it;

  it = reportList.tqfind(report.id());
  if(it == reportList.end()) {
    TQString msg = "Unknown report '" + report.id() + "'";
    throw new MYMONEYEXCEPTION(msg);
  }

  m_sql->modifyReport(report);
}

unsigned MyMoneyDatabaseMgr::countReports( void ) const
{
  return m_sql->getRecCount("kmmReports");
}

const MyMoneyReport MyMoneyDatabaseMgr::report( const TQString& id ) const
{
  return m_sql->fetchReports(TQString(id))[id];
}

void MyMoneyDatabaseMgr::removeReport(const MyMoneyReport& report)
{
  TQMap<TQString, MyMoneyReport> reportList = m_sql->fetchReports(TQString(report.id()));
  TQMap<TQString, MyMoneyReport>::ConstIterator it;

  it = reportList.tqfind(report.id());
  if(it == reportList.end()) {
    TQString msg = "Unknown report '" + report.id() + "'";
    throw new MYMONEYEXCEPTION(msg);
  }

  m_sql->removeReport(report);
}

const TQValueList<MyMoneyBudget> MyMoneyDatabaseMgr::budgetList( void ) const
{
  return m_sql->fetchBudgets().values();
}

void MyMoneyDatabaseMgr::addBudget( MyMoneyBudget& budget )
{
  MyMoneyBudget newBudget(nextBudgetID(), budget);
  m_sql->addBudget(newBudget);
}

const MyMoneyBudget MyMoneyDatabaseMgr::budgetByName(const TQString& budget) const
{
  TQMap<TQString, MyMoneyBudget> budgets = m_sql->fetchBudgets();
  TQMap<TQString, MyMoneyBudget>::ConstIterator it_p;

  for(it_p = budgets.begin(); it_p != budgets.end(); ++it_p) {
    if((*it_p).name() == budget) {
      return *it_p;
    }
  }

  throw new MYMONEYEXCEPTION("Unknown budget '" + budget + "'");
}

void MyMoneyDatabaseMgr::modifyBudget( const MyMoneyBudget& budget )
{
  //TQMap<TQString, MyMoneyBudget>::ConstIterator it;

  //it = m_budgetList.tqfind(budget.id());
  //if(it == m_budgetList.end()) {
  //  TQString msg = "Unknown budget '" + budget.id() + "'";
  //  throw new MYMONEYEXCEPTION(msg);
  //}
  //m_budgetList.modify(budget.id(), budget);

  startTransaction();
  if (m_sql->fetchBudgets(TQString(budget.id()), true).empty()) {
    TQString msg = "Unknown budget '" + budget.id() + "'";
    throw new MYMONEYEXCEPTION(msg);
  }
  m_sql->modifyBudget(budget);
  commitTransaction();
}

unsigned MyMoneyDatabaseMgr::countBudgets( void ) const
{
  return m_sql->getRecCount("kmmBudgetConfig");
}

MyMoneyBudget MyMoneyDatabaseMgr::budget( const TQString& id ) const
{
  return m_sql->fetchBudgets(TQString(id)) [id];
}

void MyMoneyDatabaseMgr::removeBudget(const MyMoneyBudget& budget)
{
//  TQMap<TQString, MyMoneyBudget>::ConstIterator it;
//
//  it = m_budgetList.tqfind(budget.id());
//  if(it == m_budgetList.end()) {
//    TQString msg = "Unknown budget '" + budget.id() + "'";
//    throw new MYMONEYEXCEPTION(msg);
//  }
//
  m_sql->removeBudget(budget);
}

void MyMoneyDatabaseMgr::clearCache(void)
{
  //m_balanceCache.clear();
}

class isReferencedHelper {
  public:
    isReferencedHelper(const TQString& id)
      : m_id (id)
    {}

    inline bool operator() (const MyMoneyObject& obj) const
    { return obj.hasReferenceTo(m_id); }

  private:
    TQString m_id;
};

bool MyMoneyDatabaseMgr::isReferenced(const MyMoneyObject& obj, const MyMoneyFileBitArray& skipCheck) const
{
  bool rc = false;
  const TQString& id = obj.id();

  MyMoneyPriceList::const_iterator it_pr;

  MyMoneyPriceList::const_iterator priceEnd;

  // FIXME optimize the list of objects we have to checks
  //       with a bit of knowledge of the internal structure, we
  //       could optimize the number of objects we check for references

  // Scan all engine objects for a reference
  if(!skipCheck[RefCheckTransaction]) {
    bool skipTransactions = false;
    MyMoneyTransactionFilter f;
    if (typeid(obj) == typeid(MyMoneyAccount)) {
      f.addAccount(obj.id());
    } else if (typeid(obj) == typeid(MyMoneyCategory)) {
      f.addCategory(obj.id());
    } else if (typeid(obj) == typeid(MyMoneyPayee)) {
      f.addPayee(obj.id());
    } // if it's anything else, I guess we just read everything
    //FIXME: correction, transactions can only have a reference to an account or payee,
    //             so, read nothing.
    else {
      skipTransactions = true;
    }
    if (! skipTransactions) {
      //TQMap <TQString, MyMoneyTransaction> transactionList = m_sql->fetchTransactions(f);
      //rc = (transactionList.end() != std::find_if(transactionList.begin(), transactionList.end(),  isReferencedHelper(id)));
      //if (rc != m_sql->isReferencedByTransaction(obj.id()))
      //  qDebug ("Transaction match inconsistency.");
      rc = m_sql->isReferencedByTransaction(obj.id());
    }
  }

  if(!skipCheck[RefCheckAccount] && !rc) {
    TQValueList<MyMoneyAccount> accountList;
    MyMoneyFile::instance()->accountList(accountList);
    rc = (accountList.end() != std::find_if(accountList.begin(), accountList.end(),  isReferencedHelper(id)));
  }
  if(!skipCheck[RefCheckInstitution] && !rc) {
    TQValueList<MyMoneyInstitution> institutionList;
    MyMoneyFile::instance()->institutionList(institutionList);
    rc = (institutionList.end() != std::find_if(institutionList.begin(), institutionList.end(),  isReferencedHelper(id)));
  }
  if(!skipCheck[RefCheckPayee] && !rc) {
    TQValueList<MyMoneyPayee> payeeList = MyMoneyFile::instance()->payeeList();
    rc = (payeeList.end() != std::find_if(payeeList.begin(), payeeList.end(),  isReferencedHelper(id)));
  }
  if(!skipCheck[RefCheckReport] && !rc) {
    TQMap<TQString, MyMoneyReport> reportList = m_sql->fetchReports();
    rc = (reportList.end() != std::find_if(reportList.begin(), reportList.end(),  isReferencedHelper(id)));
  }
  if(!skipCheck[RefCheckBudget] && !rc) {
    TQMap<TQString, MyMoneyBudget> budgets = m_sql->fetchBudgets();
    rc = (budgets.end() != std::find_if(budgets.begin(), budgets.end(),  isReferencedHelper(id)));
  }
  if(!skipCheck[RefCheckSchedule] && !rc) {
    TQMap<TQString, MyMoneySchedule> scheduleList = m_sql->fetchSchedules();
    rc = (scheduleList.end() != std::find_if(scheduleList.begin(), scheduleList.end(),  isReferencedHelper(id)));
  }
  if(!skipCheck[RefCheckSecurity] && !rc) {
    TQValueList<MyMoneySecurity> securitiesList = MyMoneyFile::instance()->securityList();
    rc = (securitiesList.end() != std::find_if(securitiesList.begin(), securitiesList.end(),  isReferencedHelper(id)));
  }
  if(!skipCheck[RefCheckCurrency] && !rc) {
    TQValueList<MyMoneySecurity> currencyList = m_sql->fetchCurrencies().values();
    rc = (currencyList.end() != std::find_if(currencyList.begin(), currencyList.end(),  isReferencedHelper(id)));
  }
  // within the pricelist we don't have to scan each entry. Checking the TQPair
  // members of the MyMoneySecurityPair is enough as they are identical to the
  // two security ids
  if(!skipCheck[RefCheckPrice] && !rc) {
    MyMoneyPriceList priceList = m_sql->fetchPrices();
    priceEnd = priceList.end();
    for(it_pr = priceList.begin(); !rc && it_pr != priceEnd; ++it_pr) {
      rc = (it_pr.key().first == id) || (it_pr.key().second == id);
    }
  }
  return rc;
}

void MyMoneyDatabaseMgr::close(void) {
  if (m_sql != 0) {
    m_sql->close(true);
    m_sql = 0;
  }
}

void MyMoneyDatabaseMgr::startTransaction(void)
{ if (m_sql) m_sql->startCommitUnit ("databasetransaction"); }

bool MyMoneyDatabaseMgr::commitTransaction(void)
{
  if (m_sql)
    return m_sql->endCommitUnit ("databasetransaction");
  return false;
}

void MyMoneyDatabaseMgr::rollbackTransaction(void)
{ if (m_sql) m_sql->cancelCommitUnit ("databasetransaction"); }

void MyMoneyDatabaseMgr::setCreationDate(const TQDate& val)
{ m_creationDate = val; }

KSharedPtr <MyMoneyStorageSql> MyMoneyDatabaseMgr::connectToDatabase(const KURL& url) {
  m_sql = new MyMoneyStorageSql (this, url);
  return m_sql;
}

 void MyMoneyDatabaseMgr::fillStorage()
{ m_sql->fillStorage(); }

void MyMoneyDatabaseMgr::setLastModificationDate(const TQDate& val)
{ m_lastModificationDate = val; }

bool MyMoneyDatabaseMgr::isDuplicateTransaction(const TQString& /*id*/) const
{
  //FIXME: figure out the real id from the key and check the DB.
//return m_transactionKeys.tqcontains(id);
  return false;
}

void MyMoneyDatabaseMgr::loadAccounts(const TQMap<TQString, MyMoneyAccount>& /*map*/)
{
//  m_accountList = map;
//FIXME: update the database.
// startTransaction
// DELETE FROM kmmAccounts
// for each account in the map
//    m_sql->addAccount(...)
// commitTransaction
// on error, rollbackTransaction
}

void MyMoneyDatabaseMgr::loadTransactions(const TQMap<TQString, MyMoneyTransaction>& /*map*/)
{
//  m_transactionList = map;
//FIXME: update the database.

//  // now fill the key map
//  TQMap<TQString, TQString> keys;
//  TQMap<TQString, MyMoneyTransaction>::ConstIterator it_t;
//  for(it_t = map.begin(); it_t != map.end(); ++it_t) {
//    keys[(*it_t).id()] = it_t.key();
//  }
//  m_transactionKeys = keys;
}

void MyMoneyDatabaseMgr::loadInstitutions(const TQMap<TQString, MyMoneyInstitution>& /*map*/)
{
//  m_institutionList = map;
//FIXME: update the database.

//  // now fill the key map
//  TQMap<TQString, TQString> keys;
//  TQMap<TQString, MyMoneyTransaction>::ConstIterator it_t;
//  for(it_t = map.begin(); it_t != map.end(); ++it_t) {
//    keys[(*it_t).id()] = it_t.key();
//  }
//  m_transactionKeys = keys;
}

void MyMoneyDatabaseMgr::loadPayees(const TQMap<TQString, MyMoneyPayee>& /*map*/)
{
//  m_payeeList = map;
}

void MyMoneyDatabaseMgr::loadSchedules(const TQMap<TQString, MyMoneySchedule>& /*map*/)
{
//  m_scheduleList = map;
}

void MyMoneyDatabaseMgr::loadSecurities(const TQMap<TQString, MyMoneySecurity>& /*map*/)
{
//  m_securitiesList = map;
}

void MyMoneyDatabaseMgr::loadCurrencies(const TQMap<TQString, MyMoneySecurity>& /*map*/)
{
//  m_currencyList = map;
//FIXME: update the database.
// startTransaction
// DELETE FROM kmmBudgetConfig
// for each budget in the map
//    m_sql->addBudget(...)
// commitTransaction
// on error, rollbackTransaction
}

void MyMoneyDatabaseMgr::loadReports( const TQMap<TQString, MyMoneyReport>& /*reports*/ )
{
//  m_reportList = reports;
//FIXME: update the database.
// startTransaction
// DELETE FROM kmmBudgetConfig
// for each budget in the map
//    m_sql->addBudget(...)
// commitTransaction
// on error, rollbackTransaction
}

void MyMoneyDatabaseMgr::loadBudgets( const TQMap<TQString, MyMoneyBudget>& /*budgets*/ )
{
//  m_budgetList = budgets;
//FIXME: update the database.
// startTransaction
// DELETE FROM kmmBudgetConfig
// for each budget in the map
//    m_sql->addBudget(...)
// commitTransaction
// on error, rollbackTransaction
}

void MyMoneyDatabaseMgr::loadPrices(const MyMoneyPriceList& list)
{
  Q_UNUSED(list);
}

unsigned long MyMoneyDatabaseMgr::accountId(void) const
{ return m_sql->getNextAccountId(); }

unsigned long MyMoneyDatabaseMgr::transactionId(void) const
{ return m_sql->getNextTransactionId(); }

unsigned long MyMoneyDatabaseMgr::payeeId(void) const
{ return m_sql->getNextPayeeId(); }

unsigned long MyMoneyDatabaseMgr::institutionId(void) const
{ return m_sql->getNextInstitutionId(); }

unsigned long MyMoneyDatabaseMgr::scheduleId(void) const
{ return m_sql->getNextScheduleId(); }

unsigned long MyMoneyDatabaseMgr::securityId(void) const
{ return m_sql->getNextSecurityId(); }

unsigned long MyMoneyDatabaseMgr::reportId(void) const
{ return m_sql->getNextReportId(); }

unsigned long MyMoneyDatabaseMgr::budgetId(void) const
{ return m_sql->getNextBudgetId(); }

void MyMoneyDatabaseMgr::loadAccountId(const unsigned long id)
{
  m_sql->loadAccountId(id);
}

void MyMoneyDatabaseMgr::loadTransactionId(const unsigned long id)
{
  m_sql->loadTransactionId(id);
}

void MyMoneyDatabaseMgr::loadPayeeId(const unsigned long id)
{
  m_sql->loadPayeeId(id);
}

void MyMoneyDatabaseMgr::loadInstitutionId(const unsigned long id)
{
  m_sql->loadInstitutionId(id);
}

void MyMoneyDatabaseMgr::loadScheduleId(const unsigned long id)
{
  m_sql->loadScheduleId(id);
}

void MyMoneyDatabaseMgr::loadSecurityId(const unsigned long id)
{
  m_sql->loadSecurityId(id);
}

void MyMoneyDatabaseMgr::loadReportId(const unsigned long id)
{
  m_sql->loadReportId(id);
}

void MyMoneyDatabaseMgr::loadBudgetId(const unsigned long id)
{
  m_sql->loadBudgetId(id);
}

void MyMoneyDatabaseMgr::rebuildAccountBalances(void)
{
  startTransaction();
  TQMap<TQString, MyMoneyAccount> accountMap = m_sql->fetchAccounts(TQStringList(), true);

  TQMap<TQString, MyMoneyMoney> balanceMap = m_sql->fetchBalance(accountMap.keys(), TQDate());

  for (TQMap<TQString, MyMoneyMoney>::const_iterator it_b = balanceMap.begin();
         it_b != balanceMap.end(); ++it_b) {
    accountMap[it_b.key()].setBalance(it_b.data());
  }

  for (TQMap<TQString, MyMoneyAccount>::const_iterator it_a = accountMap.begin();
         it_a != accountMap.end(); ++it_a) {
    m_sql->modifyAccount(it_a.data());
  }
  commitTransaction();
}

void MyMoneyDatabaseMgr::removeReferences(const TQString& id)
{
  TQMap<TQString, MyMoneyReport>::const_iterator it_r;
  TQMap<TQString, MyMoneyBudget>::const_iterator it_b;

  // remove from reports
  TQMap<TQString, MyMoneyReport> reportList = m_sql->fetchReports();
  for(it_r = reportList.begin(); it_r != reportList.end(); ++it_r) {
    MyMoneyReport r = *it_r;
    r.removeReference(id);
//    reportList.modify(r.id(), r);
  }

  // remove from budgets
  TQMap<TQString, MyMoneyBudget> budgetList = m_sql->fetchBudgets();
  for(it_b = budgetList.begin(); it_b != budgetList.end(); ++it_b) {
    MyMoneyBudget b = *it_b;
    b.removeReference(id);
//    budgetList.modify(b.id(), b);
  }
}

#undef TRY
#undef CATCH
#undef PASS