summaryrefslogtreecommitdiffstats
path: root/krecipes/src/backends/qsqlrecipedb.cpp
blob: a7f8c8aff8d38291b9e1cfbcdf19f6a5f2bd1742 (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
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
/***************************************************************************
*   Copyright (C) 2003 by                                                 *
*   Unai Garro (ugarro@users.sourceforge.net)                             *
*   Cyril Bosselut (bosselut@b1project.com)                               *
*   Jason Kivlighn (jkivlighn@gmail.com)                                  *
*                                                                         *
*   Copyright (C) 2004-2006 Jason Kivlighn (jkivlighn@gmail.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 <stdlib.h>

#include "qsqlrecipedb.h"
#include "datablocks/categorytree.h"
#include "datablocks/rating.h"
#include "datablocks/weight.h"

#include "propertycalculator.h"

#include <ntqbuffer.h>
#include <ntqtextcodec.h>
#include <ntqvariant.h>

#include <tdeapplication.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <tdetempfile.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <kmdcodec.h>

int TQSqlRecipeDB::m_refCount = 0;

TQSqlRecipeDB::TQSqlRecipeDB( const TQString &host, const TQString &user, const TQString &pass, const TQString &name, int port ) : RecipeDB(),
	connectionName("connection" + TQString::number( m_refCount+1 ))
{
	DBuser = user;
	DBpass = pass;
	DBhost = host;
	DBname = name;
	DBport = port;

	dbOK = false; //it isn't ok until we've connect()'ed
	++m_refCount;

	TQTextCodec::setCodecForCStrings(TQTextCodec::codecForName("Latin1"));  //this is the default, but let's explicitly set this to be sure
}

TQSqlRecipeDB::~TQSqlRecipeDB()
{
	if ( dbOK ) {
		database->close();
	}

	TQSqlDatabase::removeDatabase( connectionName );
	--m_refCount;
}

void TQSqlRecipeDB::connect( bool create_db, bool create_tables )
{
	kdDebug() << i18n( "TQSqlRecipeDB: Opening Database..." ) << endl;
	kdDebug() << "Parameters: \n\thost: " << DBhost << "\n\tuser: " << DBuser << "\n\ttable: " << DBname << endl;

	bool driver_found = false;

	if ( qsqlDriver() ) //we're using a built-in driver
		driver_found = true;
	else {
		TQStringList drivers = TQSqlDatabase::drivers();
		for ( TQStringList::const_iterator it = drivers.begin(); it != drivers.end(); ++it ) {
			if ( ( *it ) == qsqlDriverPlugin() ) {
				driver_found = true;
				break;
			}
		}
	}

	if ( !driver_found ) {
		dbErr = TQString( i18n( "The TQt database plug-in (%1) is not installed.  This plug-in is required for using this database backend." ) ).arg( qsqlDriverPlugin() );
		return ;
	}

	//we need to have a unique connection name for each TQSqlRecipeDB class as multiple db's may be open at once (db to db transfer)
	if ( qsqlDriver() )
		database = TQSqlDatabase::addDatabase( qsqlDriver(), connectionName );
	else if ( !qsqlDriverPlugin().isEmpty() )
		database = TQSqlDatabase::addDatabase( qsqlDriverPlugin(), connectionName );
	else
		kdDebug()<<"Fatal internal error!  Backend incorrectly written!"<<endl;

	database->setDatabaseName( DBname );
	if ( !( DBuser.isNull() ) )
		database->setUserName( DBuser );
	if ( !( DBpass.isNull() ) )
		database->setPassword( DBpass );
	database->setHostName( DBhost );
	if ( DBport > 0 )
        	database->setPort(DBport);

	kdDebug() << i18n( "Parameters set. Calling db->open()" ) << endl;

	if ( !database->open() ) {
		//Try to create the database
		if ( create_db ) {
			kdDebug() << i18n( "Failing to open database. Trying to create it" ) << endl;
			createDB();
		}
		else {
			// Handle the error (passively)
			dbErr = TQString( i18n( "Krecipes could not open the database using the driver '%2' (with username: \"%1\"). You may not have the necessary permissions, or the server may be down." ) ).arg( DBuser ).arg( qsqlDriverPlugin() );
		}

		//Now Reopen the Database and signal & exit if it fails
		if ( !database->open() ) {
			TQString error = i18n( "Database message: %1" ).arg( database->lastError().databaseText() );
			kdDebug() << i18n( "Failing to open database. Exiting\n" ).latin1();

			// Handle the error (passively)
			dbErr = TQString( i18n( "Krecipes could not open the database using the driver '%2' (with username: \"%1\"). You may not have the necessary permissions, or the server may be down." ) ).arg( DBuser ).arg( qsqlDriverPlugin() );
			return ;
		}
	}

	if ( int( tqRound( databaseVersion() * 1e5 ) ) > int( tqRound( latestDBVersion() * 1e5 ) ) ) { //correct for float's imprecision
		dbErr = i18n( "This database was created with a newer version of Krecipes and cannot be opened." );
		return ;
	}

	// Check integrity of the database (tables). If not possible, exit
	// Because checkIntegrity() will create tables if they don't exist,
	// we don't want to run this when creating the database.  We would be
	// logged in as another user (usually the superuser and not have ownership of the tables
	if ( create_tables && !checkIntegrity() ) {
		dbErr = i18n( "Failed to fix database structure.\nIf you are using SQLite, this is often caused by using an SQLite 2 database with SQLite 3 installed.  If this is the case, make sure both SQLite 2 and 3 are installed, and then run 'krecipes --convert-sqlite3' to update your database to the new structure." );
		return;
	}

	// Database was opened correctly
	m_query = TQSqlQuery( TQString::null, database );
	m_query.setForwardOnly(true);
	dbOK = true;
}

void TQSqlRecipeDB::execSQL( const TQString &command )
{
	database->exec( command );
}

void TQSqlRecipeDB::loadRecipes( RecipeList *rlist, int items, TQValueList<int> ids )
{
	// Empty the recipe first
	rlist->empty();

	TQMap <int, RecipeList::Iterator> recipeIterators; // Stores the iterator of each recipe in the list;

	TQString command;

	TQString current_timestamp = TQDateTime::currentDateTime().toString(TQt::ISODate);

	TQStringList ids_str;
	for ( TQValueList<int>::const_iterator it = ids.begin(); it != ids.end(); ++it ) {
		TQString number_str = TQString::number(*it);
		ids_str << number_str;

		if ( !(items & RecipeDB::Noatime) )
 			database->exec( "UPDATE recipes SET ctime=ctime,mtime=mtime,atime='"+current_timestamp+"' WHERE id="+number_str );
	}

	// Read title, author, yield, and instructions as specified
	command = "SELECT id";
	if ( items & RecipeDB::Title ) command += ",title";
	if ( items & RecipeDB::Instructions ) command += ",instructions";
	if ( items & RecipeDB::PrepTime ) command += ",prep_time";
	if ( items & RecipeDB::Yield ) command += ",yield_amount,yield_amount_offset,yield_type_id";
	command += " FROM recipes"+(ids_str.count()!=0?" WHERE id IN ("+ids_str.join(",")+")":"");

	TQSqlQuery recipeQuery(command,database);
	if ( recipeQuery.isActive() ) {
		while ( recipeQuery.next() ) {
			int row_at = 0;

			Recipe recipe;
			recipe.recipeID = recipeQuery.value( row_at ).toInt(); ++row_at;

			if ( items & RecipeDB::Title ) {
				 recipe.title = unescapeAndDecode( recipeQuery.value( row_at ).toCString() ); ++row_at;
			}

			if ( items & RecipeDB::Instructions ) {
				recipe.instructions = unescapeAndDecode( recipeQuery.value( row_at ).toCString() ); ++row_at;
			}

			if ( items & RecipeDB::PrepTime ) {
				 recipe.prepTime = recipeQuery.value( row_at ).toTime(); ++row_at;
			}

			if ( items & RecipeDB::Yield ) {
				recipe.yield.amount = recipeQuery.value( row_at ).toDouble(); ++row_at;
				recipe.yield.amount_offset = recipeQuery.value( row_at ).toDouble(); ++row_at;
				recipe.yield.type_id = recipeQuery.value( row_at ).toInt(); ++row_at;
				if ( recipe.yield.type_id != -1 ) {
					TQString y_command = TQString("SELECT name FROM yield_types WHERE id=%1;").arg(recipe.yield.type_id);
					TQSqlQuery yield_query(y_command,database);
					if ( yield_query.isActive() && yield_query.first() )
						recipe.yield.type = unescapeAndDecode(yield_query.value( 0 ).toCString());
					else
						kdDebug()<<yield_query.lastError().databaseText()<<endl;
				}
			}

			if ( items & RecipeDB::Meta )
				loadRecipeMetadata(&recipe);

			recipeIterators[ recipe.recipeID ] = rlist->append( recipe );
		}
	}

	// Read the ingredients
	if ( items & RecipeDB::Ingredients ) {
		for ( RecipeList::iterator recipe_it = rlist->begin(); recipe_it != rlist->end(); ++recipe_it ) {
			if ( items & RecipeDB::NamesOnly ) {
				if ( items & IngredientAmounts )
					command = TQString( "SELECT il.ingredient_id,i.name,il.substitute_for,il.amount,il.amount_offset,u.id,u.type FROM ingredients i, ingredient_list il, units u WHERE il.recipe_id=%1 AND i.id=il.ingredient_id AND u.id=il.unit_id ORDER BY il.order_index" ).arg( (*recipe_it).recipeID );
				else
					command = TQString( "SELECT il.ingredient_id,i.name,il.substitute_for FROM ingredients i, ingredient_list il WHERE il.recipe_id=%1 AND i.id=il.ingredient_id" ).arg( (*recipe_it).recipeID );
			}
			else
				command = TQString( "SELECT il.ingredient_id,i.name,il.substitute_for,il.amount,il.amount_offset,u.id,u.name,u.plural,u.name_abbrev,u.plural_abbrev,u.type,il.group_id,il.id FROM ingredients i, ingredient_list il, units u WHERE il.recipe_id=%1 AND i.id=il.ingredient_id AND u.id=il.unit_id ORDER BY il.order_index" ).arg( (*recipe_it).recipeID );

			TQSqlQuery ingredientQuery( command, database );
			if ( ingredientQuery.isActive() ) {
				RecipeList::Iterator it = recipeIterators[ (*recipe_it).recipeID ];
				while ( ingredientQuery.next() ) {
					Ingredient ing;
					ing.ingredientID = ingredientQuery.value( 0 ).toInt();
					ing.name = unescapeAndDecode( ingredientQuery.value( 1 ).toCString() );

					if ( items & RecipeDB::NamesOnly ) {
						if ( items & IngredientAmounts ) {
							ing.amount = ingredientQuery.value( 3 ).toDouble();
							ing.amount_offset = ingredientQuery.value( 4 ).toDouble();
							ing.units.id = ingredientQuery.value( 5 ).toInt();
							ing.units.type = (Unit::Type)ingredientQuery.value( 6 ).toInt();
						}
					}
					else  {
						ing.amount = ingredientQuery.value( 3 ).toDouble();
						ing.amount_offset = ingredientQuery.value( 4 ).toDouble();
						ing.units.id = ingredientQuery.value( 5 ).toInt();
						ing.units.name = unescapeAndDecode( ingredientQuery.value( 6 ).toCString() );
						ing.units.plural = unescapeAndDecode( ingredientQuery.value( 7 ).toCString() );
						ing.units.name_abbrev = unescapeAndDecode( ingredientQuery.value( 8 ).toCString() );
						ing.units.plural_abbrev = unescapeAndDecode( ingredientQuery.value( 9 ).toCString() );
						ing.units.type = (Unit::Type)ingredientQuery.value( 10 ).toInt();
	
						//if we don't have both name and plural, use what we have as both
						if ( ing.units.name.isEmpty() )
							ing.units.name = ing.units.plural;
						else if ( ing.units.plural.isEmpty() )
							ing.units.plural = ing.units.name;
			
						ing.groupID = ingredientQuery.value( 11 ).toInt();
						if ( ing.groupID != -1 ) {
							TQSqlQuery toLoad( TQString( "SELECT name FROM ingredient_groups WHERE id=%1" ).arg( ing.groupID ), database );
							if ( toLoad.isActive() && toLoad.first() )
								ing.group = unescapeAndDecode( toLoad.value( 0 ).toCString() );
						}

						command = TQString("SELECT pl.prep_method_id,p.name FROM prep_methods p, prep_method_list pl WHERE pl.ingredient_list_id=%1 AND p.id=pl.prep_method_id ORDER BY pl.order_index;").arg(ingredientQuery.value( 12 ).toInt());
						TQSqlQuery ingPrepMethodsQuery( command, database );
						if ( ingPrepMethodsQuery.isActive() ) {
							while ( ingPrepMethodsQuery.next() ) {
								ing.prepMethodList.append( Element( unescapeAndDecode(ingPrepMethodsQuery.value(1).toCString()),ingPrepMethodsQuery.value(0).toInt()) );
							}
						}
					}

					if ( ingredientQuery.value( 2 ).toInt() > 0 ) {
						//given the ordering, we can assume substitute_for is the id of the last
						//ingredient in the list
						//int substitute_for = ingredientQuery.value( 2 ).toInt();
						(*it).ingList.last().substitutes.append( ing );
					}
					else
						(*it).ingList.append( ing );
				}
			}
		}
	}

	//Load the Image
	if ( items & RecipeDB::Photo ) {
		for ( RecipeList::iterator recipe_it = rlist->begin(); recipe_it != rlist->end(); ++recipe_it ) {
			RecipeList::iterator it = recipeIterators[ (*recipe_it).recipeID ];
			loadPhoto( (*it).recipeID, (*it).photo );
		}
	}

	//Load the category list
	if ( items & RecipeDB::Categories ) {
		for ( RecipeList::iterator recipe_it = rlist->begin(); recipe_it != rlist->end(); ++recipe_it ) {
			RecipeList::iterator it = recipeIterators[ (*recipe_it).recipeID ];
			
			command = TQString( "SELECT cl.category_id,c.name FROM category_list cl, categories c WHERE recipe_id=%1 AND cl.category_id=c.id;" ).arg( (*it).recipeID );
		
			m_query.exec( command );
			if ( m_query.isActive() ) {
				while ( m_query.next() ) {
					Element el;
					el.id = m_query.value( 0 ).toInt();
					el.name = unescapeAndDecode( m_query.value( 1 ).toCString() );
					(*it).categoryList.append( el );
				}
			}
		}
	}

	//Load the author list
	if ( items & RecipeDB::Authors ) {
		for ( RecipeList::iterator recipe_it = rlist->begin(); recipe_it != rlist->end(); ++recipe_it ) {
			RecipeList::iterator it = recipeIterators[ (*recipe_it).recipeID ];

			command = TQString( "SELECT al.author_id,a.name FROM author_list al, authors a WHERE recipe_id=%1 AND al.author_id=a.id;" ).arg( (*it).recipeID );
		
			m_query.exec( command );
			if ( m_query.isActive() ) {
				while ( m_query.next() ) {
					Element el;
					el.id = m_query.value( 0 ).toInt();
					el.name = unescapeAndDecode( m_query.value( 1 ).toCString() );
					(*it).authorList.append( el );
				}
			}
		}
	}

	//Load the ratings
	if ( items & RecipeDB::Ratings ) {
		for ( RecipeList::iterator recipe_it = rlist->begin(); recipe_it != rlist->end(); ++recipe_it ) {
			RecipeList::iterator it = recipeIterators[ (*recipe_it).recipeID ];
			
			command = TQString( "SELECT id,comment,rater FROM ratings WHERE recipe_id=%1 ORDER BY created DESC" ).arg( (*it).recipeID );
			TQSqlQuery query( command, database );
			if ( query.isActive() ) {
				while ( query.next() ) {
					Rating r;
					r.id = query.value( 0 ).toInt();
					r.comment = unescapeAndDecode( query.value( 1 ).toCString() );
					r.rater = unescapeAndDecode( query.value( 2 ).toCString() );

					command = TQString( "SELECT rc.id,rc.name,rl.stars FROM rating_criteria rc, rating_criterion_list rl WHERE rating_id=%1 AND rl.rating_criterion_id=rc.id" ).arg(r.id);
					TQSqlQuery criterionQuery( command, database );
					if ( criterionQuery.isActive() ) {
						while ( criterionQuery.next() ) {
							RatingCriteria rc;
							rc.id = criterionQuery.value( 0 ).toInt();
							rc.name = unescapeAndDecode( criterionQuery.value( 1 ).toCString() );
							rc.stars = criterionQuery.value( 2 ).toDouble();
							r.append( rc );
						}
					}

					(*it).ratingList.append( r );
				}
			}
		}
	}

	if ( items & RecipeDB::Properties ) {
		for ( RecipeList::iterator recipe_it = rlist->begin(); recipe_it != rlist->end(); ++recipe_it ) {
			RecipeList::iterator it = recipeIterators[ (*recipe_it).recipeID ];
			calculateProperties( *it, this );
		}
	}
}

void TQSqlRecipeDB::loadIngredientGroups( ElementList *list )
{
	list->clear();

	TQString command = "SELECT id,name FROM ingredient_groups ORDER BY name;";
	m_query.exec( command );

	if ( m_query.isActive() ) {
		while ( m_query.next() ) {
			Element group;
			group.id = m_query.value( 0 ).toInt();
			group.name = unescapeAndDecode( m_query.value( 1 ).toCString() );
			list->append( group );
		}
	}
}

void TQSqlRecipeDB::loadIngredients( ElementList *list, int limit, int offset )
{
	list->clear();

	TQString command = "SELECT id,name FROM ingredients ORDER BY name"
	  +((limit==-1)?"":" LIMIT "+TQString::number(limit)+" OFFSET "+TQString::number(offset));
	m_query.exec( command );

	if ( m_query.isActive() ) {
		while ( m_query.next() ) {
			Element ing;
			ing.id = m_query.value( 0 ).toInt();
			ing.name = unescapeAndDecode( m_query.value( 1 ).toCString() );
			list->append( ing );
		}
	}
}

void TQSqlRecipeDB::loadPrepMethods( ElementList *list, int limit, int offset )
{
	list->clear();

	TQString command = "SELECT id,name FROM prep_methods ORDER BY name"
	  +((limit==-1)?"":" LIMIT "+TQString::number(limit)+" OFFSET "+TQString::number(offset));
	m_query.exec( command );

	if ( m_query.isActive() ) {
		while ( m_query.next() ) {
			Element prep_method;
			prep_method.id = m_query.value( 0 ).toInt();
			prep_method.name = unescapeAndDecode( m_query.value( 1 ).toCString() );
			list->append( prep_method );
		}
	}
}

void TQSqlRecipeDB::loadYieldTypes( ElementList *list, int limit, int offset )
{
	list->clear();

	TQString command = "SELECT id,name FROM yield_types ORDER BY name"
	  +((limit==-1)?"":" LIMIT "+TQString::number(limit)+" OFFSET "+TQString::number(offset));
	m_query.exec( command );

	if ( m_query.isActive() ) {
		while ( m_query.next() ) {
			Element el;
			el.id = m_query.value( 0 ).toInt();
			el.name = unescapeAndDecode( m_query.value( 1 ).toCString() );
			list->append( el );
		}
	}
}

void TQSqlRecipeDB::createNewPrepMethod( const TQString &prepMethodName )
{
	TQString command;
	TQString real_name = prepMethodName.left( maxPrepMethodNameLength() );

	command = TQString( "INSERT INTO prep_methods VALUES(%2,'%1');" ).arg( escapeAndEncode( real_name ) ).arg( getNextInsertIDStr( "prep_methods", "id" ) );
	TQSqlQuery prepMethodToCreate( command, database );

	emit prepMethodCreated( Element( real_name, lastInsertID() ) );
}

void TQSqlRecipeDB::modPrepMethod( int prepMethodID, const TQString &newLabel )
{
	TQString command;

	command = TQString( "UPDATE prep_methods SET name='%1' WHERE id=%2;" ).arg( escapeAndEncode( newLabel ) ).arg( prepMethodID );
	TQSqlQuery prepMethodToCreate( command, database );

	emit prepMethodRemoved( prepMethodID );
	emit prepMethodCreated( Element( newLabel, prepMethodID ) );
}

void TQSqlRecipeDB::modProperty( int propertyID, const TQString &newLabel )
{
	TQString command;

	command = TQString( "UPDATE ingredient_properties SET name='%1' WHERE id=%2;" ).arg( escapeAndEncode( newLabel ) ).arg( propertyID );
	TQSqlQuery createQuery( command, database );

	emit propertyRemoved( propertyID );
	emit propertyCreated( propertyName( propertyID ) );
}

void TQSqlRecipeDB::loadPossibleUnits( int ingredientID, UnitList *list )
{
	list->clear();

	TQString command;

	command = TQString( "SELECT u.id,u.name,u.plural,u.name_abbrev,u.plural_abbrev,u.type FROM unit_list ul, units u WHERE ul.ingredient_id=%1 AND ul.unit_id=u.id;" ).arg( ingredientID );

	TQSqlQuery unitToLoad( command, database );

	if ( unitToLoad.isActive() ) {
		while ( unitToLoad.next() ) {
			Unit unit;
			unit.id = unitToLoad.value( 0 ).toInt();
			unit.name = unescapeAndDecode( unitToLoad.value( 1 ).toCString() );
			unit.plural = unescapeAndDecode( unitToLoad.value( 2 ).toCString() );
			unit.name_abbrev = unescapeAndDecode( unitToLoad.value( 3 ).toCString() );
			unit.plural_abbrev = unescapeAndDecode( unitToLoad.value( 4 ).toCString() );
			unit.type = (Unit::Type) unitToLoad.value( 5 ).toInt();

			list->append( unit );
		}
	}


}

void TQSqlRecipeDB::storePhoto( int recipeID, const TQByteArray &data )
{
	TQSqlQuery query( TQString::null, database );

	query.prepare( "UPDATE recipes SET photo=?,ctime=ctime,atime=atime,mtime=mtime WHERE id=" + TQString::number( recipeID ) );
	query.addBindValue( KCodecs::base64Encode( data ) );
	query.exec();
}

void TQSqlRecipeDB::loadPhoto( int recipeID, TQPixmap &photo )
{
	TQString command = TQString( "SELECT photo FROM recipes WHERE id=%1;" ).arg( recipeID );
	TQSqlQuery query( command, database );

	if ( query.isActive() && query.first() ) {
		TQCString decodedPic;
		TQPixmap pix;
		KCodecs::base64Decode( query.value( 0 ).toCString(), decodedPic );
		int len = decodedPic.size();

		if ( len > 0 ) {
			TQByteArray picData( len );
			memcpy( picData.data(), decodedPic.data(), len );
	
			bool ok = pix.loadFromData( picData, "JPEG" );
			if ( ok )
				photo = pix;
		}
	}
}

void TQSqlRecipeDB::loadRecipeMetadata( Recipe *recipe )
{
	TQString command = "SELECT ctime,mtime,atime FROM recipes WHERE id="+TQString::number(recipe->recipeID);

	TQSqlQuery query( command, database );
	if ( query.isActive() && query.first() ) {
		recipe->ctime = query.value(0).toDateTime();
		recipe->mtime = query.value(1).toDateTime();
		recipe->atime = query.value(2).toDateTime();
	}
}

void TQSqlRecipeDB::saveRecipe( Recipe *recipe )
{
	// Check if it's a new recipe or it exists (supossedly) already.

	bool newRecipe;
	newRecipe = ( recipe->recipeID == -1 );
	// First check if the recipe ID is set, if so, update (not create)
	// Be carefull, first check if the recipe hasn't been deleted while changing.

	TQSqlQuery recipeToSave( TQString::null, database );

	TQString command;

	TQDateTime current_datetime = TQDateTime::currentDateTime();
	TQString current_timestamp = current_datetime.toString(TQt::ISODate);
	if ( newRecipe ) {
		command = TQString( "INSERT INTO recipes VALUES ("+getNextInsertIDStr("recipes","id")+",'%1',%2,'%3','%4','%5',NULL,'%6','%7','%8','%9');" )  // Id is autoincremented
		          .arg( escapeAndEncode( recipe->title ) )
		          .arg( recipe->yield.amount )
		          .arg( recipe->yield.amount_offset )
		          .arg( recipe->yield.type_id )
		          .arg( escapeAndEncode( recipe->instructions ) )
		          .arg( recipe->prepTime.toString( "hh:mm:ss" ) )
		          .arg( current_timestamp )
		          .arg( current_timestamp )
		          .arg( current_timestamp );
		recipe->mtime = recipe->ctime = recipe->atime = current_datetime;
	}
	else {
		command = TQString( "UPDATE recipes SET title='%1',yield_amount='%2',yield_amount_offset='%3',yield_type_id='%4',instructions='%5',prep_time='%6',mtime='%8',ctime=ctime,atime=atime WHERE id=%7;" )
		          .arg( escapeAndEncode( recipe->title ) )
		          .arg( recipe->yield.amount )
		          .arg( recipe->yield.amount_offset )
		          .arg( recipe->yield.type_id )
		          .arg( escapeAndEncode( recipe->instructions ) )
		          .arg( recipe->prepTime.toString( "hh:mm:ss" ) )
		          .arg( recipe->recipeID )
		          .arg( current_timestamp );
		recipe->mtime = current_datetime;
	}
	recipeToSave.exec( command );

	if ( !newRecipe ) {
		// Clean up yield_types which have no recipe that they belong to
		TQStringList ids;
		command = TQString( "SELECT DISTINCT(yield_type_id) FROM recipes" );
		recipeToSave.exec( command );
		if ( recipeToSave.isActive() ) {
			while ( recipeToSave.next() ) {
				if ( recipeToSave.value( 0 ).toInt() != -1 )
					ids << TQString::number( recipeToSave.value( 0 ).toInt() );
			}
		}
		command = TQString( "DELETE FROM yield_types WHERE id NOT IN ( %1 )" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
		recipeToSave.exec( command );
	}

	// If it's a new recipe, identify the ID that was given to the recipe and store in the Recipe itself
	int recipeID;
	if ( newRecipe ) {
		recipeID = lastInsertID();
		recipe->recipeID = recipeID;
	}
	recipeID = recipe->recipeID;
	loadRecipeMetadata(recipe);

	// Let's begin storing the Image!
	if ( !recipe->photo.isNull() ) {
		TQByteArray ba;
		TQBuffer buffer( ba );
		buffer.open( IO_WriteOnly );
		TQImageIO iio( &buffer, "JPEG" );
		iio.setImage( recipe->photo.convertToImage() );
		iio.write();
		//recipe->photo.save( &buffer, "JPEG" ); don't need TQImageIO in QT 3.2

		storePhoto( recipeID, ba );
	}
	else {
		recipeToSave.exec( "UPDATE recipes SET photo=NULL, mtime=mtime, ctime=ctime, atime=atime WHERE id=" + TQString::number( recipeID ) );
	}

	// Save the ingredient list (first delete if we are updating)
	command = TQString( "SELECT id FROM ingredient_list WHERE recipe_id=%1" ).arg(recipeID);
	recipeToSave.exec( command );
	if ( recipeToSave.isActive() ) {
		while ( recipeToSave.next() ) {
			command = TQString("DELETE FROM prep_method_list WHERE ingredient_list_id=%1")
			  .arg(recipeToSave.value(0).toInt());
			database->exec(command);
		}
	}
	command = TQString( "DELETE FROM ingredient_list WHERE recipe_id=%1;" )
	          .arg( recipeID );
	recipeToSave.exec( command );

	int order_index = 0;
	for ( IngredientList::const_iterator ing_it = recipe->ingList.begin(); ing_it != recipe->ingList.end(); ++ing_it ) {
		order_index++;
		TQString ing_list_id_str = getNextInsertIDStr("ingredient_list","id");
		command = TQString( "INSERT INTO ingredient_list VALUES (%1,%2,%3,%4,%5,%6,%7,%8,NULL);" )
		          .arg( ing_list_id_str )
		          .arg( recipeID )
		          .arg( ( *ing_it ).ingredientID )
		          .arg( ( *ing_it ).amount )
		          .arg( ( *ing_it ).amount_offset )
		          .arg( ( *ing_it ).units.id )
		          .arg( order_index )
		          .arg( ( *ing_it ).groupID );
		recipeToSave.exec( command );

		int ing_list_id = lastInsertID();
		int prep_order_index = 0;
		for ( ElementList::const_iterator prep_it = (*ing_it).prepMethodList.begin(); prep_it != (*ing_it).prepMethodList.end(); ++prep_it ) {
			prep_order_index++;
			command = TQString( "INSERT INTO prep_method_list VALUES (%1,%2,%3);" )
				.arg( ing_list_id )
				.arg( ( *prep_it ).id )
				.arg( prep_order_index );
			recipeToSave.exec( command );
		}
		
		for ( TQValueList<IngredientData>::const_iterator sub_it = (*ing_it).substitutes.begin(); sub_it != (*ing_it).substitutes.end(); ++sub_it ) {
			order_index++;
			TQString ing_list_id_str = getNextInsertIDStr("ingredient_list","id");
			command = TQString( "INSERT INTO ingredient_list VALUES (%1,%2,%3,%4,%5,%6,%7,%8,%9);" )
				.arg( ing_list_id_str )
				.arg( recipeID )
				.arg( ( *sub_it ).ingredientID )
				.arg( ( *sub_it ).amount )
				.arg( ( *sub_it ).amount_offset )
				.arg( ( *sub_it ).units.id )
				.arg( order_index )
				.arg( ( *sub_it ).groupID )
				.arg( (*ing_it).ingredientID );
			recipeToSave.exec( command );
	
			int ing_list_id = lastInsertID();
			int prep_order_index = 0;
			for ( ElementList::const_iterator prep_it = (*sub_it).prepMethodList.begin(); prep_it != (*sub_it).prepMethodList.end(); ++prep_it ) {
				prep_order_index++;
				command = TQString( "INSERT INTO prep_method_list VALUES (%1,%2,%3);" )
					.arg( ing_list_id )
					.arg( ( *prep_it ).id )
					.arg( prep_order_index );
				recipeToSave.exec( command );
			}
		}
	}

	// Save the category list for the recipe (first delete, in case we are updating)
	command = TQString( "DELETE FROM category_list WHERE recipe_id=%1;" )
	          .arg( recipeID );
	recipeToSave.exec( command );

	ElementList::const_iterator cat_it = recipe->categoryList.end(); // Start from last, mysql seems to work in lifo format... so it's read first the latest inserted one (newest)
	--cat_it;
	for ( unsigned int i = 0; i < recipe->categoryList.count(); i++ ) {
		command = TQString( "INSERT INTO category_list VALUES (%1,%2);" )
		          .arg( recipeID )
		          .arg( ( *cat_it ).id );
		recipeToSave.exec( command );

		--cat_it;
	}

	//Add the default category -1 to ease and speed up searches

	command = TQString( "INSERT INTO category_list VALUES (%1,-1);" )
	          .arg( recipeID );
	recipeToSave.exec( command );


	// Save the author list for the recipe (first delete, in case we are updating)
	command = TQString( "DELETE FROM author_list WHERE recipe_id=%1;" )
	          .arg( recipeID );
	recipeToSave.exec( command );

	ElementList::const_iterator author_it = recipe->authorList.end(); // Start from last, mysql seems to work in lifo format... so it's read first the latest inserted one (newest)
	--author_it;
	for ( unsigned int i = 0; i < recipe->authorList.count(); i++ ) {
		command = TQString( "INSERT INTO author_list VALUES (%1,%2);" )
		          .arg( recipeID )
		          .arg( ( *author_it ).id );
		recipeToSave.exec( command );

		--author_it;
	}

	// Save the ratings (first delete criterion list if we are updating)
	command = TQString( "SELECT id FROM ratings WHERE recipe_id=%1" ).arg(recipeID);
	recipeToSave.exec( command );
	if ( recipeToSave.isActive() ) {
		while ( recipeToSave.next() ) {
			
			command = TQString("DELETE FROM rating_criterion_list WHERE rating_id=%1")
			  .arg(recipeToSave.value(0).toInt());
			database->exec(command);
		}
	}

	TQStringList ids;

	for ( RatingList::iterator rating_it = recipe->ratingList.begin(); rating_it != recipe->ratingList.end(); ++rating_it ) {
		//double average = (*rating_it).average();
		if ( (*rating_it).id == -1 ) //new rating
			command ="INSERT INTO ratings VALUES("+TQString(getNextInsertIDStr("ratings","id"))+","+TQString::number(recipeID)+",'"+TQString(escapeAndEncode((*rating_it).comment))+"','"+TQString(escapeAndEncode((*rating_it).rater))+/*"','"+TQString::number(average)+*/"','"+current_timestamp+"')";
		else //existing rating
			command = "UPDATE ratings SET "
			  "comment='"+TQString(escapeAndEncode((*rating_it).comment))+"',"
			  "rater='"+TQString(escapeAndEncode((*rating_it).rater))+"',"
			  "created=created "
			  "WHERE id="+TQString::number((*rating_it).id);

		recipeToSave.exec( command );
		
		if ( (*rating_it).id == -1 )
			(*rating_it).id = lastInsertID();
		
		for ( TQValueList<RatingCriteria>::const_iterator rc_it = (*rating_it).ratingCriteriaList.begin(); rc_it != (*rating_it).ratingCriteriaList.end(); ++rc_it ) {
			command = TQString( "INSERT INTO rating_criterion_list VALUES("+TQString::number((*rating_it).id)+","+TQString::number((*rc_it).id)+","+TQString::number((*rc_it).stars)+")" );
			recipeToSave.exec( command );
		}

		ids << TQString::number((*rating_it).id);
	}

	// only delete those ratings that don't exist anymore
	command = TQString( "DELETE FROM ratings WHERE recipe_id=%1 AND id NOT IN( %2 )" )
	          .arg( recipeID ).arg( ids.join(",") );
	recipeToSave.exec( command );

	if ( newRecipe )
		emit recipeCreated( Element( recipe->title.left( maxRecipeTitleLength() ), recipeID ), recipe->categoryList );
	else
		emit recipeModified( Element( recipe->title.left( maxRecipeTitleLength() ), recipeID ), recipe->categoryList );
}

void TQSqlRecipeDB::loadRecipeList( ElementList *list, int categoryID, bool recursive )
{
	TQString command;

	if ( categoryID == -1 )  // load just the list
		command = "SELECT id,title FROM recipes;";
	else  // load the list of those in the specified category
		command = TQString( "SELECT r.id,r.title FROM recipes r,category_list cl WHERE r.id=cl.recipe_id AND cl.category_id=%1 ORDER BY r.title" ).arg( categoryID );

	if ( recursive ) {
		TQSqlQuery subcategories( TQString("SELECT id FROM categories WHERE parent_id='%1'").arg(categoryID), database );
		if ( subcategories.isActive() ) {
			while ( subcategories.next() ) {
				loadRecipeList(list,subcategories.value( 0 ).toInt(),true);
			}
		}
	}

	TQSqlQuery recipeToLoad( command, database );

	if ( recipeToLoad.isActive() ) {
		while ( recipeToLoad.next() ) {
			Element recipe;
			recipe.id = recipeToLoad.value( 0 ).toInt();
			recipe.name = unescapeAndDecode( recipeToLoad.value( 1 ).toCString() );
			list->append( recipe );
		}
	}
}


void TQSqlRecipeDB::loadUncategorizedRecipes( ElementList *list )
{
	list->clear();

	TQString command = "SELECT r.id,r.title FROM recipes r,category_list cl WHERE r.id=cl.recipe_id GROUP BY id HAVING COUNT(*)=1 ORDER BY r.title DESC";
	m_query.exec( command );
	if ( m_query.isActive() ) {
		while ( m_query.next() ) {
			Element recipe;
			recipe.id = m_query.value( 0 ).toInt();
			recipe.name = unescapeAndDecode( m_query.value( 1 ).toCString() );
			list->append( recipe );
		}
	}
}



void TQSqlRecipeDB::removeRecipe( int id )
{
	emit recipeRemoved( id );

	TQString command;

	command = TQString( "DELETE FROM recipes WHERE id=%1;" ).arg( id );
	TQSqlQuery recipeToRemove( command, database );
	command = TQString( "DELETE FROM ingredient_list WHERE recipe_id=%1;" ).arg( id );
	recipeToRemove.exec( command );
	command = TQString( "DELETE FROM category_list WHERE recipe_id=%1;" ).arg( id );
	recipeToRemove.exec( command );

	// Clean up ingredient_groups which have no recipe that they belong to
	// MySQL doesn't support subqueries until 4.1, so we'll do this the long way
	// (Easy way: DELETE FROM ingredient_groups WHERE id NOT IN ( SELECT DISTINCT(group_id) FROM ingredient_list );)
	TQStringList ids;
	command = TQString( "SELECT DISTINCT(group_id) FROM ingredient_list;" );
	recipeToRemove.exec( command );
	if ( recipeToRemove.isActive() ) {
		while ( recipeToRemove.next() ) {
			if ( recipeToRemove.value( 0 ).toInt() != -1 )
				ids << TQString::number( recipeToRemove.value( 0 ).toInt() );
		}
	}
	command = TQString( "DELETE FROM ingredient_groups WHERE id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	recipeToRemove.exec( command );

	// Clean up yield_types which have no recipe that they belong to
	ids.clear();
	command = TQString( "SELECT DISTINCT(yield_type_id) FROM recipes" );
	recipeToRemove.exec( command );
	if ( recipeToRemove.isActive() ) {
		while ( recipeToRemove.next() ) {
			if ( recipeToRemove.value( 0 ).toInt() != -1 )
				ids << TQString::number( recipeToRemove.value( 0 ).toInt() );
		}
	}
	command = TQString( "DELETE FROM yield_types WHERE id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	recipeToRemove.exec( command );
}

void TQSqlRecipeDB::removeRecipeFromCategory( int recipeID, int categoryID )
{
	TQString command;
	command = TQString( "DELETE FROM category_list WHERE recipe_id=%1 AND category_id=%2;" ).arg( recipeID ).arg( categoryID );
	TQSqlQuery recipeToRemove( command, database );

	emit recipeRemoved( recipeID, categoryID );
}

void TQSqlRecipeDB::categorizeRecipe( int recipeID, const ElementList &categoryList )
{
	TQString command;

	//emit recipeRemoved( recipeID, -1 );

	for ( ElementList::const_iterator it = categoryList.begin(); it != categoryList.end(); ++it ) {
		command = TQString( "INSERT INTO category_list VALUES(%1,%2)" ).arg( recipeID ).arg( (*it).id );
		database->exec( command );
	}

	emit recipeModified( Element(recipeTitle(recipeID),recipeID), categoryList );
}

void TQSqlRecipeDB::createNewIngGroup( const TQString &name )
{
	TQString command;
	TQString real_name = name.left( maxIngGroupNameLength() );

	command = TQString( "INSERT INTO ingredient_groups VALUES(%2,'%1');" ).arg( escapeAndEncode( real_name ) ).arg( getNextInsertIDStr( "ingredient_groups", "id" ) );
	TQSqlQuery query( command, database );

	emit ingGroupCreated( Element( real_name, lastInsertID() ) );
}

void TQSqlRecipeDB::createNewIngredient( const TQString &ingredientName )
{
	TQString command;
	TQString real_name = ingredientName.left( maxIngredientNameLength() );

	command = TQString( "INSERT INTO ingredients VALUES(%2,'%1');" ).arg( escapeAndEncode( real_name ) ).arg( getNextInsertIDStr( "ingredients", "id" ) );
	TQSqlQuery ingredientToCreate( command, database );

	emit ingredientCreated( Element( real_name, lastInsertID() ) );
}

void TQSqlRecipeDB::createNewRating( const TQString &rating )
{
	TQString command;
	TQString real_name = rating/*.left( maxIngredientNameLength() )*/;

	command = TQString( "INSERT INTO rating_criteria VALUES(%2,'%1');" ).arg( escapeAndEncode( real_name ) ).arg( getNextInsertIDStr( "rating_criteria", "id" ) );
	TQSqlQuery toCreate( command, database );

	emit ratingCriteriaCreated( Element( real_name, lastInsertID() ) );
}

void TQSqlRecipeDB::createNewYieldType( const TQString &name )
{
	TQString command;
	TQString real_name = name.left( maxYieldTypeLength() );

	command = TQString( "INSERT INTO yield_types VALUES(%2,'%1');" ).arg( escapeAndEncode( real_name ) ).arg( getNextInsertIDStr( "yield_types", "id" ) );
	database->exec(command);

	//emit yieldTypeCreated( Element( real_name, lastInsertID() ) );
}

void TQSqlRecipeDB::modIngredientGroup( int groupID, const TQString &newLabel )
{
	TQString command;

	command = TQString( "UPDATE ingredient_groups SET name='%1' WHERE id=%2;" ).arg( escapeAndEncode( newLabel ) ).arg( groupID );
	TQSqlQuery ingredientToCreate( command, database );

	emit ingGroupRemoved( groupID );
	emit ingGroupCreated( Element( newLabel, groupID ) );
}

void TQSqlRecipeDB::modIngredient( int ingredientID, const TQString &newLabel )
{
	TQString command;

	command = TQString( "UPDATE ingredients SET name='%1' WHERE id=%2;" ).arg( escapeAndEncode( newLabel ) ).arg( ingredientID );
	TQSqlQuery ingredientToCreate( command, database );

	emit ingredientRemoved( ingredientID );
	emit ingredientCreated( Element( newLabel, ingredientID ) );
}

void TQSqlRecipeDB::addUnitToIngredient( int ingredientID, int unitID )
{
	TQString command;

	command = TQString( "INSERT INTO unit_list VALUES(%1,%2);" ).arg( ingredientID ).arg( unitID );
	TQSqlQuery ingredientToCreate( command, database );
}

void TQSqlRecipeDB::loadUnits( UnitList *list, Unit::Type type, int limit, int offset )
{
	list->clear();

	TQString command;

	command = "SELECT id,name,name_abbrev,plural,plural_abbrev,type FROM units "
	  +((type==Unit::All)?"":"WHERE type="+TQString::number(type))
	  +" ORDER BY name"
	  +((limit==-1)?"":" LIMIT "+TQString::number(limit)+" OFFSET "+TQString::number(offset));

	TQSqlQuery unitToLoad( command, database );

	if ( unitToLoad.isActive() ) {
		while ( unitToLoad.next() ) {
			Unit unit;
			unit.id = unitToLoad.value( 0 ).toInt();
			unit.name = unescapeAndDecode( unitToLoad.value( 1 ).toCString() );
			unit.name_abbrev = unescapeAndDecode( unitToLoad.value( 2 ).toCString() );
			unit.plural = unescapeAndDecode( unitToLoad.value( 3 ).toCString() );
			unit.plural_abbrev = unescapeAndDecode( unitToLoad.value( 4 ).toCString() );
			unit.type = (Unit::Type)unitToLoad.value( 5 ).toInt();
			list->append( unit );
		}
	}
}

void TQSqlRecipeDB::removeUnitFromIngredient( int ingredientID, int unitID )
{
	TQString command;

	command = TQString( "DELETE FROM unit_list WHERE ingredient_id=%1 AND unit_id=%2;" ).arg( ingredientID ).arg( unitID );
	TQSqlQuery unitToRemove( command, database );

	// Remove any recipe using that combination of ingredients also (user must have been warned before calling this function!)

	command = TQString( "SELECT r.id FROM recipes r,ingredient_list il WHERE r.id=il.recipe_id AND il.ingredient_id=%1 AND il.unit_id=%2;" ).arg( ingredientID ).arg( unitID );
	unitToRemove.exec( command );
	if ( unitToRemove.isActive() ) {
		while ( unitToRemove.next() ) {
			emit recipeRemoved( unitToRemove.value( 0 ).toInt() );
			database->exec( TQString( "DELETE FROM recipes WHERE id=%1;" ).arg( unitToRemove.value( 0 ).toInt() ) );
		}
	}

	// Remove any ingredient in ingredient_list which has references to this unit and ingredient
	command = TQString( "DELETE FROM ingredient_list WHERE ingredient_id=%1 AND unit_id=%2;" ).arg( ingredientID ).arg( unitID );
	unitToRemove.exec( command );

	// Remove any ingredient properties from ingredient_info where the this ingredient+unit is being used (user must have been warned before calling this function!)
	command = TQString( "DELETE FROM ingredient_info ii WHERE ii.ingredient_id=%1 AND ii.per_units=%2;" ).arg( ingredientID ).arg( unitID );
	unitToRemove.exec( command );

	// Clean up ingredient_list which have no recipe that they belong to
	// MySQL doesn't support subqueries until 4.1, so we'll do this the long way
	// (Easy way: DELETE FROM ingredient_list WHERE recipe_id NOT IN ( SELECT id FROM recipes );)
	TQStringList ids;
	command = TQString( "SELECT id FROM recipes;" );
	unitToRemove.exec( command );
	if ( unitToRemove.isActive() ) {
		while ( unitToRemove.next() ) {
			ids << TQString::number( unitToRemove.value( 0 ).toInt() );
		}
	}
	command = TQString( "DELETE FROM ingredient_list WHERE recipe_id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	unitToRemove.exec( command );

	// Clean up category_list which have no recipe that they belong to
	command = TQString( "DELETE FROM category_list WHERE recipe_id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	unitToRemove.exec( command );

	// Clean up ingredient_groups which have no recipe that they belong to
	// MySQL doesn't support subqueries until 4.1, so we'll do this the long way
	// (Easy way: DELETE FROM ingredient_groups WHERE id NOT IN ( SELECT DISTINCT(group_id) FROM ingredient_list );)
	ids.clear();
	command = TQString( "SELECT DISTINCT(group_id) FROM ingredient_list;" );
	unitToRemove.exec( command );
	if ( unitToRemove.isActive() ) {
		while ( unitToRemove.next() ) {
			if ( unitToRemove.value( 0 ).toInt() != -1 )
				ids << TQString::number( unitToRemove.value( 0 ).toInt() );
		}
	}
	command = TQString( "DELETE FROM ingredient_groups WHERE id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	unitToRemove.exec( command );
}

void TQSqlRecipeDB::removeIngredientGroup( int groupID )
{
	TQString command;

	// First remove the ingredient

	command = TQString( "DELETE FROM ingredient_groups WHERE id=%1" ).arg( groupID );
	TQSqlQuery toDelete( command, database );

	// Remove all the unit entries for this ingredient

	command = TQString( "UPDATE ingredient_list SET group_id='-1' WHERE group_id=%1" ).arg( groupID );
	toDelete.exec( command );

	emit ingGroupRemoved( groupID );
}

void TQSqlRecipeDB::removeIngredient( int ingredientID )
{
	TQString command;

	// First remove the ingredient

	command = TQString( "DELETE FROM ingredients WHERE id=%1;" ).arg( ingredientID );
	TQSqlQuery ingredientToDelete( command, database );

	// Remove all the unit entries for this ingredient

	command = TQString( "DELETE FROM unit_list WHERE ingredient_id=%1;" ).arg( ingredientID );
	ingredientToDelete.exec( command );

	// Remove any recipe using that ingredient

	command = TQString( "SELECT r.id FROM recipes r,ingredient_list il WHERE r.id=il.recipe_id AND il.ingredient_id=%1;" ).arg( ingredientID );
	ingredientToDelete.exec( command );
	if ( ingredientToDelete.isActive() ) {
		while ( ingredientToDelete.next() ) {
			emit recipeRemoved( ingredientToDelete.value( 0 ).toInt() );
			database->exec( TQString( "DELETE FROM recipes WHERE id=%1;" ).arg( ingredientToDelete.value( 0 ).toInt() ) );
		}
	}

	// Remove any ingredient in ingredient_list which has references to this ingredient
	command = TQString( "DELETE FROM ingredient_list WHERE ingredient_id=%1;" ).arg( ingredientID );
	ingredientToDelete.exec( command );

	// Clean up ingredient_list which have no recipe that they belong to
	// MySQL doesn't support subqueries until 4.1, so we'll do this the long way
	// (Easy way: DELETE FROM ingredient_list WHERE recipe_id NOT IN ( SELECT id FROM recipes );)
	TQStringList ids;
	command = TQString( "SELECT id FROM recipes;" );
	ingredientToDelete.exec( command );
	if ( ingredientToDelete.isActive() ) {
		while ( ingredientToDelete.next() ) {
			ids << TQString::number( ingredientToDelete.value( 0 ).toInt() );
		}
	}
	command = TQString( "DELETE FROM ingredient_list WHERE recipe_id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	ingredientToDelete.exec( command );

	// Clean up category_list which have no recipe that they belong to. Same method as above
	command = TQString( "DELETE FROM category_list WHERE recipe_id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	ingredientToDelete.exec( command );

	// Clean up ingredient_groups which have no recipe that they belong to
	// MySQL doesn't support subqueries until 4.1, so we'll do this the long way
	// (Easy way: DELETE FROM ingredient_groups WHERE id NOT IN ( SELECT DISTINCT(group_id) FROM ingredient_list );)
	ids.clear();
	command = TQString( "SELECT DISTINCT(group_id) FROM ingredient_list;" );
	ingredientToDelete.exec( command );
	if ( ingredientToDelete.isActive() ) {
		while ( ingredientToDelete.next() ) {
			if ( ingredientToDelete.value( 0 ).toInt() != -1 )
				ids << TQString::number( ingredientToDelete.value( 0 ).toInt() );
		}
	}
	command = TQString( "DELETE FROM ingredient_groups WHERE id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	ingredientToDelete.exec( command );

	// Remove property list of this ingredient
	command = TQString( "DELETE FROM ingredient_info WHERE ingredient_id=%1;" ).arg( ingredientID );
	ingredientToDelete.exec( command );

	emit ingredientRemoved( ingredientID );
}

void TQSqlRecipeDB::removeIngredientWeight( int id )
{
	TQString command;

	// First remove the ingredient

	command = TQString( "DELETE FROM ingredient_weights WHERE id=%1" ).arg( id );
	TQSqlQuery toDelete( command, database );
}

void TQSqlRecipeDB::addIngredientWeight( const Weight &w )
{
	TQString command;
	if ( w.id != -1 ) {
		command = TQString( "UPDATE ingredient_weights SET ingredient_id=%1,amount=%2,unit_id=%3,weight=%4,weight_unit_id=%5,prep_method_id=%7 WHERE id=%6" )
		  .arg(w.ingredientID)
		  .arg(w.perAmount)
		  .arg(w.perAmountUnitID)
		  .arg(w.weight)
		  .arg(w.weightUnitID)
		  .arg(w.id)
		  .arg(w.prepMethodID);
	}
	else {
		command = TQString( "INSERT INTO ingredient_weights VALUES(%6,%1,%2,%3,%4,%5,%7)" )
		  .arg(w.ingredientID)
		  .arg(w.perAmount)
		  .arg(w.perAmountUnitID)
		  .arg(w.weight)
		  .arg(w.weightUnitID)
		  .arg(getNextInsertIDStr( "ingredient_weights", "id" ))
		  .arg(w.prepMethodID);
	}
	TQSqlQuery query( command, database );
}

void TQSqlRecipeDB::addProperty( const TQString &name, const TQString &units )
{
	TQString command;
	TQString real_name = name.left( maxPropertyNameLength() );

	command = TQString( "INSERT INTO ingredient_properties VALUES(%3,'%1','%2');" )
	          .arg( escapeAndEncode( real_name ) )
	          .arg( escapeAndEncode( units ) )
	          .arg( getNextInsertIDStr( "ingredient_properties", "id" ) );
	TQSqlQuery propertyToAdd( command, database );

	emit propertyCreated( IngredientProperty( real_name, units, lastInsertID() ) );
}

void TQSqlRecipeDB::loadProperties( IngredientPropertyList *list, int ingredientID )
{
	list->clear();
	TQString command;
	bool usePerUnit;
	if ( ingredientID >= 0 )  // Load properties of this ingredient
	{
		usePerUnit = true;
		command = TQString( "SELECT ip.id,ip.name,ip.units,ii.per_units,u.name,u.type,ii.amount,ii.ingredient_id  FROM ingredient_properties ip, ingredient_info ii, units u WHERE ii.ingredient_id=%1 AND ii.property_id=ip.id AND ii.per_units=u.id;" ).arg( ingredientID );
	}
	else if ( ingredientID == -1 )  // Load the properties of all the ingredients
	{
		usePerUnit = true;
		command = TQString( "SELECT ip.id,ip.name,ip.units,ii.per_units,u.name,u.type,ii.amount,ii.ingredient_id FROM ingredient_properties ip, ingredient_info ii, units u WHERE ii.property_id=ip.id AND ii.per_units=u.id;" );
	}
	else // Load the whole property list (just the list of possible properties, not the ingredient properties)
	{
		usePerUnit = false;
		command = TQString( "SELECT  id,name,units FROM ingredient_properties;" );
	}

	TQSqlQuery propertiesToLoad ( command, database );
	// Load the results into the list
	if ( propertiesToLoad.isActive() ) {
		while ( propertiesToLoad.next() ) {
			IngredientProperty prop;
			prop.id = propertiesToLoad.value( 0 ).toInt();
			prop.name = unescapeAndDecode( propertiesToLoad.value( 1 ).toCString() );
			prop.units = unescapeAndDecode( propertiesToLoad.value( 2 ).toCString() );
			if ( usePerUnit ) {
				prop.perUnit.id = propertiesToLoad.value( 3 ).toInt();
				prop.perUnit.name = unescapeAndDecode( propertiesToLoad.value( 4 ).toCString() );
				prop.perUnit.type = (Unit::Type)propertiesToLoad.value( 5 ).toInt();
			}

			if ( ingredientID >= -1 )
				prop.amount = propertiesToLoad.value( 6 ).toDouble();
			else
				prop.amount = -1; // Property is generic, not attached to an ingredient

			if ( ingredientID >= -1 )
				prop.ingredientID = propertiesToLoad.value( 7 ).toInt();

			list->append( prop );
		}
	}
}

void TQSqlRecipeDB::changePropertyAmountToIngredient( int ingredientID, int propertyID, double amount, int per_units )
{
	TQString command;
	command = TQString( "UPDATE ingredient_info SET amount=%1 WHERE ingredient_id=%2 AND property_id=%3 AND per_units=%4;" ).arg( amount ).arg( ingredientID ).arg( propertyID ).arg( per_units );
	TQSqlQuery infoToChange( command, database );
}

void TQSqlRecipeDB::addPropertyToIngredient( int ingredientID, int propertyID, double amount, int perUnitsID )
{
	TQString command;

	command = TQString( "INSERT INTO ingredient_info VALUES(%1,%2,%3,%4);" ).arg( ingredientID ).arg( propertyID ).arg( amount ).arg( perUnitsID );
	TQSqlQuery propertyToAdd( command, database );
}


void TQSqlRecipeDB::removePropertyFromIngredient( int ingredientID, int propertyID, int perUnitID )
{
	TQString command;
	// remove property from ingredient info. Note that there could be duplicates with different units (per_units). Remove just the one especified.
	command = TQString( "DELETE FROM ingredient_info WHERE ingredient_id=%1 AND property_id=%2 AND per_units=%3;" ).arg( ingredientID ).arg( propertyID ).arg( perUnitID );
	TQSqlQuery propertyToRemove( command, database );
}

void TQSqlRecipeDB::removeProperty( int propertyID )
{
	TQString command;

	// Remove property from the ingredient_properties
	command = TQString( "DELETE FROM ingredient_properties WHERE id=%1;" ).arg( propertyID );
	TQSqlQuery propertyToRemove( command, database );

	// Remove any ingredient info that uses this property
	command = TQString( "DELETE FROM ingredient_info WHERE property_id=%1;" ).arg( propertyID );
	propertyToRemove.exec( command );

	emit propertyRemoved( propertyID );
}

void TQSqlRecipeDB::removeUnit( int unitID )
{
	TQString command;
	// Remove the unit first
	command = TQString( "DELETE FROM units WHERE id=%1;" ).arg( unitID );
	TQSqlQuery unitToRemove( command, database );

	//Remove the unit from ingredients using it

	command = TQString( "DELETE FROM unit_list WHERE unit_id=%1;" ).arg( unitID );
	unitToRemove.exec( command );


	// Remove any recipe using that unit in the ingredient list (user must have been warned before calling this function!)

	command = TQString( "SELECT r.id FROM recipes r,ingredient_list il WHERE r.id=il.recipe_id AND il.unit_id=%1;" ).arg( unitID );
	unitToRemove.exec( command );
	if ( unitToRemove.isActive() ) {
		while ( unitToRemove.next() ) {
			emit recipeRemoved( unitToRemove.value( 0 ).toInt() );
			database->exec( TQString( "DELETE FROM recipes WHERE id=%1;" ).arg( unitToRemove.value( 0 ).toInt() ) );
		}
	}

	// Remove any ingredient in ingredient_list which has references to this unit
	command = TQString( "DELETE FROM ingredient_list WHERE unit_id=%1;" ).arg( unitID );
	unitToRemove.exec( command );

	// Clean up ingredient_list which have no recipe that they belong to
	// MySQL doesn't support subqueries until 4.1, so we'll do this the long way
	// (Easy way: DELETE FROM ingredient_list WHERE recipe_id NOT IN ( SELECT id FROM recipes );)
	TQStringList ids;
	command = TQString( "SELECT id FROM recipes;" );
	unitToRemove.exec( command );
	if ( unitToRemove.isActive() ) {
		while ( unitToRemove.next() ) {
			ids << TQString::number( unitToRemove.value( 0 ).toInt() );
		}
	}
	command = TQString( "DELETE FROM ingredient_list WHERE recipe_id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	unitToRemove.exec( command );

	// Clean up category_list which have no recipe that they belong to. Same method as above
	command = TQString( "DELETE FROM category_list WHERE recipe_id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	unitToRemove.exec( command );

	// Clean up ingredient_groups which have no recipe that they belong to
	// MySQL doesn't support subqueries until 4.1, so we'll do this the long way
	// (Easy way: DELETE FROM ingredient_groups WHERE id NOT IN ( SELECT DISTINCT(group_id) FROM ingredient_list );)
	ids.clear();
	command = TQString( "SELECT DISTINCT(group_id) FROM ingredient_list;" );
	unitToRemove.exec( command );
	if ( unitToRemove.isActive() ) {
		while ( unitToRemove.next() ) {
			if ( unitToRemove.value( 0 ).toInt() != -1 )
				ids << TQString::number( unitToRemove.value( 0 ).toInt() );
		}
	}
	command = TQString( "DELETE FROM ingredient_groups WHERE id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	unitToRemove.exec( command );

	// Remove the ingredient properties using this unit (user must be warned before calling this function)
	command = TQString( "DELETE FROM ingredient_info WHERE per_units=%1;" ).arg( unitID );
	unitToRemove.exec( command );

	// Remove the unit conversion ratios with this unit
	command = TQString( "DELETE FROM units_conversion WHERE unit1_id=%1 OR unit2_id=%2;" ).arg( unitID ).arg( unitID );
	unitToRemove.exec( command );

	// Remove associated ingredient weights
	command = TQString( "DELETE FROM ingredient_weights WHERE unit_id=%1" ).arg( unitID );
	unitToRemove.exec( command );

	emit unitRemoved( unitID );
}

void TQSqlRecipeDB::removePrepMethod( int prepMethodID )
{
	TQString command;
	// Remove the prep method first
	command = TQString( "DELETE FROM prep_methods WHERE id=%1;" ).arg( prepMethodID );
	TQSqlQuery prepMethodToRemove( command, database );

	// Remove any recipe using that prep method in the ingredient list (user must have been warned before calling this function!)

	command = TQString( "SELECT DISTINCT r.id FROM recipes r,ingredient_list il, prep_method_list pl WHERE r.id=il.recipe_id AND pl.ingredient_list_id=il.id AND pl.prep_method_id=%1;" ).arg( prepMethodID );
	prepMethodToRemove.exec( command );
	if ( prepMethodToRemove.isActive() ) {
		while ( prepMethodToRemove.next() ) {
			emit recipeRemoved( prepMethodToRemove.value( 0 ).toInt() );
			database->exec( TQString( "DELETE FROM recipes WHERE id=%1;" ).arg( prepMethodToRemove.value( 0 ).toInt() ) );
		}
	}

	// Clean up ingredient_list which have no recipe that they belong to
	// MySQL doesn't support subqueries until 4.1, so we'll do this the long way
	// (Easy way: DELETE FROM ingredient_list WHERE recipe_id NOT IN ( SELECT id FROM recipes );)
	TQStringList ids;
	command = TQString( "SELECT id FROM recipes;" );
	prepMethodToRemove.exec( command );
	if ( prepMethodToRemove.isActive() ) {
		while ( prepMethodToRemove.next() ) {
			ids << TQString::number( prepMethodToRemove.value( 0 ).toInt() );
		}
	}

	command = TQString( "DELETE FROM ingredient_list WHERE recipe_id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	prepMethodToRemove.exec( command );

	// Clean up category_list which have no recipe that they belong to. Same method as above
	command = TQString( "DELETE FROM category_list WHERE recipe_id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	prepMethodToRemove.exec( command );

	// Clean up ingredient_groups which have no recipe that they belong to
	// MySQL doesn't support subqueries until 4.1, so we'll do this the long way
	// (Easy way: DELETE FROM ingredient_groups WHERE id NOT IN ( SELECT DISTINCT(group_id) FROM ingredient_list );)
	ids.clear();
	command = TQString( "SELECT DISTINCT(group_id) FROM ingredient_list;" );
	prepMethodToRemove.exec( command );
	if ( prepMethodToRemove.isActive() ) {
		while ( prepMethodToRemove.next() ) {
			if ( prepMethodToRemove.value( 0 ).toInt() != -1 )
				ids << TQString::number( prepMethodToRemove.value( 0 ).toInt() );
		}
	}
	command = TQString( "DELETE FROM ingredient_groups WHERE id NOT IN ( %1 );" ).arg( ( ids.count() == 0 ) ? "-1" : ids.join( "," ) );
	prepMethodToRemove.exec( command );

	emit prepMethodRemoved( prepMethodID );
}


void TQSqlRecipeDB::createNewUnit( const Unit &unit )
{
	TQString real_name = unit.name.left( maxUnitNameLength() ).stripWhiteSpace();
	TQString real_plural = unit.plural.left( maxUnitNameLength() ).stripWhiteSpace();
	TQString real_name_abbrev = unit.name_abbrev.left( maxUnitNameLength() ).stripWhiteSpace();
	TQString real_plural_abbrev = unit.plural_abbrev.left( maxUnitNameLength() ).stripWhiteSpace();

	Unit new_unit( real_name, real_plural );
	new_unit.name_abbrev = real_name_abbrev;
	new_unit.plural_abbrev = real_plural_abbrev;
	new_unit.type = unit.type;

	if ( real_name.isEmpty() )
		real_name = real_plural;
	else if ( real_plural.isEmpty() )
		real_plural = real_name;

	if ( real_name_abbrev.isEmpty() )
		real_name_abbrev = "NULL";
	else
		real_name_abbrev = "'"+escapeAndEncode(real_name_abbrev)+"'";
	if ( real_plural_abbrev.isEmpty() )
		real_plural_abbrev = "NULL";
	else
		real_plural_abbrev = "'"+escapeAndEncode(real_plural_abbrev)+"'";
	

	TQString command = "INSERT INTO units VALUES(" + getNextInsertIDStr( "units", "id" ) 
	   + ",'" + escapeAndEncode( real_name )
	   + "'," + real_name_abbrev
	   + ",'" + escapeAndEncode( real_plural )
	   + "'," + real_plural_abbrev
	   + "," + TQString::number(unit.type)
	   + ");";

	TQSqlQuery unitToCreate( command, database );

	new_unit.id = lastInsertID();
	emit unitCreated( new_unit );
}


void TQSqlRecipeDB::modUnit( const Unit &unit )
{
	TQSqlQuery unitQuery( TQString::null, database );

	TQString real_name = unit.name.left( maxUnitNameLength() ).stripWhiteSpace();
	TQString real_plural = unit.plural.left( maxUnitNameLength() ).stripWhiteSpace();
	TQString real_name_abbrev = unit.name_abbrev.left( maxUnitNameLength() ).stripWhiteSpace();
	TQString real_plural_abbrev = unit.plural_abbrev.left( maxUnitNameLength() ).stripWhiteSpace();

	Unit newUnit( real_name, real_plural, unit.id );
	newUnit.type = unit.type;
	newUnit.name_abbrev = real_name_abbrev;
	newUnit.plural_abbrev = real_plural_abbrev;

	if ( real_name_abbrev.isEmpty() )
		real_name_abbrev = "NULL";
	else
		real_name_abbrev = "'"+escapeAndEncode(real_name_abbrev)+"'";
	if ( real_plural_abbrev.isEmpty() )
		real_plural_abbrev = "NULL";
	else
		real_plural_abbrev = "'"+escapeAndEncode(real_plural_abbrev)+"'";

	TQString command = TQString("UPDATE units SET name='%1',name_abbrev=%2,plural='%3',plural_abbrev=%4,type=%6 WHERE id='%5'")
	  .arg(escapeAndEncode(real_name))
	  .arg(real_name_abbrev)
	  .arg(escapeAndEncode(real_plural))
	  .arg(real_plural_abbrev)
	  .arg(unit.id)
	  .arg(unit.type);
	unitQuery.exec( command );

	emit unitRemoved( unit.id );
	emit unitCreated( newUnit );
}

void TQSqlRecipeDB::findUseOfIngGroupInRecipes( ElementList *results, int groupID )
{
	TQString command = TQString( "SELECT DISTINCT r.id,r.title FROM recipes r,ingredient_list il WHERE r.id=il.recipe_id AND il.group_id=%1" ).arg( groupID );
	TQSqlQuery query( command, database );

	// Populate data
	if ( query.isActive() ) {
		while ( query.next() ) {
			Element recipe;
			recipe.id = query.value( 0 ).toInt();
			recipe.name = unescapeAndDecode( query.value( 1 ).toCString() );
			results->append( recipe );
		}
	}
}

void TQSqlRecipeDB::findUseOfCategoryInRecipes( ElementList *results, int catID )
{
	TQString command = TQString( "SELECT r.id,r.title FROM recipes r,category_list cl WHERE r.id=cl.recipe_id AND cl.category_id=%1" ).arg( catID );
	TQSqlQuery query( command, database );

	// Populate data
	if ( query.isActive() ) {
		while ( query.next() ) {
			Element recipe;
			recipe.id = query.value( 0 ).toInt();
			recipe.name = unescapeAndDecode( query.value( 1 ).toCString() );
			results->append( recipe );
		}
	}

	//recursively find dependenacies in subcategories
	command = TQString( "SELECT id FROM categories WHERE parent_id=%1" ).arg( catID );
	TQSqlQuery findDeps = database->exec( command );
	if ( findDeps.isActive() ) {
		while ( findDeps.next() ) {
			findUseOfCategoryInRecipes(results,findDeps.value( 0 ).toInt() );
		}
	}
}

void TQSqlRecipeDB::findUseOfAuthorInRecipes( ElementList *results, int authorID )
{
	TQString command = TQString( "SELECT r.id,r.title FROM recipes r,author_list al WHERE r.id=al.recipe_id AND al.author_id=%1" ).arg( authorID );
	TQSqlQuery query( command, database );

	// Populate data
	if ( query.isActive() ) {
		while ( query.next() ) {
			Element recipe;
			recipe.id = query.value( 0 ).toInt();
			recipe.name = unescapeAndDecode( query.value( 1 ).toCString() );
			results->append( recipe );
		}
	}
}

void TQSqlRecipeDB::loadUnitRatios( UnitRatioList *ratioList, Unit::Type type )
{
	ratioList->clear();

	TQString command;
	if ( type == Unit::All )
		command = "SELECT unit1_id,unit2_id,ratio FROM units_conversion";
	else
		command = "SELECT unit1_id,unit2_id,ratio FROM units_conversion,units unit1,units unit2 WHERE unit1_id=unit1.id AND unit1.type="+TQString::number(type)+" AND unit2_id=unit2.id AND unit2.type="+TQString::number(type);
	TQSqlQuery ratiosToLoad( command, database );

	if ( ratiosToLoad.isActive() ) {
		while ( ratiosToLoad.next() ) {
			UnitRatio ratio;
			ratio.uID1 = ratiosToLoad.value( 0 ).toInt();
			ratio.uID2 = ratiosToLoad.value( 1 ).toInt();
			ratio.ratio = ratiosToLoad.value( 2 ).toDouble();
			ratioList->add( ratio );
		}
	}
}

void TQSqlRecipeDB::saveUnitRatio( const UnitRatio *ratio )
{
	TQString command;

	// Check if it's a new ratio or it exists already.
	command = TQString( "SELECT * FROM units_conversion WHERE unit1_id=%1 AND unit2_id=%2" ).arg( ratio->uID1 ).arg( ratio->uID2 ); // Find ratio between units

	TQSqlQuery ratioFound( command, database ); // Find the entries
	bool newRatio = ( ratioFound.size() == 0 );

	if ( newRatio )
		command = TQString( "INSERT INTO units_conversion VALUES(%1,%2,%3);" ).arg( ratio->uID1 ).arg( ratio->uID2 ).arg( ratio->ratio );
	else
		command = TQString( "UPDATE units_conversion SET ratio=%3 WHERE unit1_id=%1 AND unit2_id=%2" ).arg( ratio->uID1 ).arg( ratio->uID2 ).arg( ratio->ratio );

	ratioFound.exec( command ); // Enter the new ratio
}

void TQSqlRecipeDB::removeUnitRatio( int unitID1, int unitID2 )
{
	database->exec(TQString( "DELETE FROM units_conversion WHERE unit1_id=%1 AND unit2_id=%2" ).arg( unitID1 ).arg( unitID2 ));
}

double TQSqlRecipeDB::unitRatio( int unitID1, int unitID2 )
{

	if ( unitID1 == unitID2 )
		return ( 1.0 );
	TQString command;

	command = TQString( "SELECT ratio FROM units_conversion WHERE unit1_id=%1 AND unit2_id=%2;" ).arg( unitID1 ).arg( unitID2 );
	TQSqlQuery ratioToLoad( command, database );

	if ( ratioToLoad.isActive() && ratioToLoad.next() )
		return ( ratioToLoad.value( 0 ).toDouble() );
	else
		return ( -1 );
}

double TQSqlRecipeDB::ingredientWeight( const Ingredient &ing, bool *wasApproximated )
{
	TQString command = TQString( "SELECT amount,weight,prep_method_id,unit_id FROM ingredient_weights WHERE ingredient_id=%1 AND (unit_id=%2 OR weight_unit_id=%3)" )
	   .arg( ing.ingredientID )
	   .arg( ing.units.id ).arg( ing.units.id );

	TQSqlQuery query( command, database );

	if ( query.isActive() ) {
		//store the amount for the entry with no prep method.  If no other suitable entry is found, we'll guesstimate
		//the weight using this entry
		double convertedAmount = -1;
		while ( query.next() ) {
			int prepMethodID = query.value( 2 ).toInt();

			if ( ing.prepMethodList.containsId( prepMethodID ) ) {
				if ( wasApproximated ) *wasApproximated = false;
				double amount = query.value( 0 ).toDouble();

				//'per_amount' -> 'weight' conversion
				if ( query.value( 3 ).toInt() == ing.units.id )
					convertedAmount = query.value( 1 ).toDouble() * ing.amount / amount;
				//'weight' -> 'per_amount' conversion
				else
					convertedAmount = amount * ing.amount / query.value( 1 ).toDouble();

				return convertedAmount;
			}
			if ( prepMethodID == -1 ) {
				//'per_amount' -> 'weight' conversion
				if ( query.value( 3 ).toInt() == ing.units.id )
					convertedAmount = query.value( 1 ).toDouble() * ing.amount / query.value( 0 ).toDouble();
				//'weight' -> 'per_amount' conversion
				else
					convertedAmount = query.value( 0 ).toDouble() * ing.amount / query.value( 1 ).toDouble();
			}
		}
		//no matching prep method found, use entry without a prep method if there was one
		if ( convertedAmount > 0 ) {
			if ( wasApproximated ) *wasApproximated = true;
			kdDebug()<<"Prep method given, but no weight entry found that uses that prep method.  I'm fudging the weight with an entry without a prep method."<<endl;

			return convertedAmount;
		}
	}
	return -1;
}

WeightList TQSqlRecipeDB::ingredientWeightUnits( int ingID )
{
	WeightList list;

	TQString command = TQString( "SELECT id,amount,unit_id,weight,weight_unit_id,prep_method_id FROM ingredient_weights WHERE ingredient_id=%1" ).arg( ingID );
	TQSqlQuery query( command, database );
	if ( query.isActive() ) {
		while ( query.next() ) {
			Weight w;
			w.id = query.value(0).toInt();
			w.perAmount = query.value(1).toDouble();
			w.perAmountUnitID = query.value(2).toInt();
			w.weight = query.value(3).toDouble();
			w.weightUnitID = query.value(4).toInt();
			w.prepMethodID = query.value(5).toInt();
			w.ingredientID = ingID;
			list.append(w);
		}
	}

	return list;
}

//Finds data dependant on this Ingredient/Unit combination
void TQSqlRecipeDB::findIngredientUnitDependancies( int ingredientID, int unitID, ElementList *recipes, ElementList *ingredientInfo )
{

	// Recipes using that combination

	TQString command = TQString( "SELECT DISTINCT r.id,r.title  FROM recipes r,ingredient_list il WHERE r.id=il.recipe_id AND il.ingredient_id=%1 AND il.unit_id=%2;" ).arg( ingredientID ).arg( unitID );
	TQSqlQuery unitToRemove( command, database );
	loadElementList( recipes, &unitToRemove );
	// Ingredient info using that combination
	command = TQString( "SELECT i.name,ip.name,ip.units,u.name FROM ingredients i, ingredient_info ii, ingredient_properties ip, units u WHERE i.id=ii.ingredient_id AND ii.ingredient_id=%1 AND ii.per_units=%2 AND ii.property_id=ip.id AND ii.per_units=u.id;" ).arg( ingredientID ).arg( unitID );

	unitToRemove.exec( command );
	loadPropertyElementList( ingredientInfo, &unitToRemove );
}

void TQSqlRecipeDB::findIngredientDependancies( int ingredientID, ElementList *recipes )
{
	TQString command = TQString( "SELECT DISTINCT r.id,r.title FROM recipes r,ingredient_list il WHERE r.id=il.recipe_id AND il.ingredient_id=%1" ).arg( ingredientID );

	TQSqlQuery ingredientToRemove( command, database );
	loadElementList( recipes, &ingredientToRemove );
}



//Finds data dependant on the removal of this Unit
void TQSqlRecipeDB::findUnitDependancies( int unitID, ElementList *properties, ElementList *recipes, ElementList *weights )
{

	// Ingredient-Info (ingredient->property) using this Unit

	TQString command = TQString( "SELECT i.name,ip.name,ip.units,u.name  FROM ingredients i, ingredient_info ii, ingredient_properties ip, units u WHERE i.id=ii.ingredient_id AND ii.per_units=%1 AND ii.property_id=ip.id  AND ii.per_units=u.id;" ).arg( unitID );
	TQSqlQuery unitToRemove( command, database );
	loadPropertyElementList( properties, &unitToRemove );

	// Recipes using this Unit
	command = TQString( "SELECT DISTINCT r.id,r.title  FROM recipes r,ingredient_list il WHERE r.id=il.recipe_id AND il.unit_id=%1;" ).arg( unitID ); // Without "DISTINCT" we get duplicates since ingredient_list has no unique recipe_id's
	unitToRemove.exec( command );
	loadElementList( recipes, &unitToRemove );

	// Weights using this unit
	command = TQString( "SELECT i.name,weight_u.name,per_u.name,w.prep_method_id FROM ingredients i,ingredient_weights w,units weight_u,units per_u WHERE i.id=w.ingredient_id AND w.unit_id=per_u.id AND w.weight_unit_id=weight_u.id AND (weight_u.id=%1 OR per_u.id=%2)" )
	  .arg( unitID )
	  .arg( unitID );
	unitToRemove.exec( command );
	if ( unitToRemove.isActive() ) {
		while ( unitToRemove.next() ) {
			Element el;

			TQString ingName = unescapeAndDecode( unitToRemove.value( 0 ).toCString() );
			TQString weightUnit = unescapeAndDecode( unitToRemove.value( 1 ).toCString() );
			TQString perUnit = unescapeAndDecode( unitToRemove.value( 2 ).toCString() );

			int prepID = unitToRemove.value( 3 ).toInt();
			TQString prep;
			if ( prepID != -1 ) {
				command = TQString( "SELECT p.name FROM prep_methods p, ingredient_weights w WHERE p.id = w.prep_method_id AND w.prep_method_id=%1" )
					.arg( prepID );
				TQSqlQuery query( command, database );
				if ( query.isActive() && query.first() )
					prep = unescapeAndDecode( query.value( 0 ).toCString() );
			}

			el.name = TQString( i18n("In ingredient '%1': weight [%2/%3%4]") ).arg( ingName ).arg( weightUnit ).arg( perUnit ).arg( (prepID == -1)?TQString::null:"; "+prep );
			weights->append( el );
		}
	}

}

void TQSqlRecipeDB::findPrepMethodDependancies( int prepMethodID, ElementList *recipes )
{
	//get just the ids first so that we can use DISTINCT
	TQString command = TQString( "SELECT DISTINCT r.id FROM recipes r,ingredient_list il, prep_method_list pl WHERE r.id=il.recipe_id AND pl.ingredient_list_id=il.id AND pl.prep_method_id=%1;" ).arg( prepMethodID );

	TQStringList ids;
	TQSqlQuery query( command, database );
	if ( query.isActive() ) {
		while ( query.next() ) {
			ids << TQString::number(query.value( 0 ).toInt());
		}
	}

	//now get the titles of the ids
	command = TQString( "SELECT r.id, r.title FROM recipes r WHERE r.id IN ("+ids.join(",")+")" );
	TQSqlQuery prepMethodToRemove( command, database );
	loadElementList( recipes, &prepMethodToRemove );
}


void TQSqlRecipeDB::loadElementList( ElementList *elList, TQSqlQuery *query )
{
	if ( query->isActive() ) {
		while ( query->next() ) {
			Element el;
			el.id = query->value( 0 ).toInt();
			el.name = unescapeAndDecode( query->value( 1 ).toCString() );
			elList->append( el );
		}
	}
}
// See function "findUnitDependancies" for use
void TQSqlRecipeDB::loadPropertyElementList( ElementList *elList, TQSqlQuery *query )
{
	if ( query->isActive() ) {
		while ( query->next() ) {
			Element el;
			el.id = -1; // There's no ID for the ingredient-property combination
			TQString ingName = unescapeAndDecode( query->value( 0 ).toCString() );
			TQString propName = unescapeAndDecode( query->value( 1 ).toCString() );
			TQString propUnits = unescapeAndDecode( query->value( 2 ).toCString() );
			TQString propPerUnits = unescapeAndDecode( query->value( 3 ).toCString() );

			el.name = TQString( i18n("In ingredient '%1': property \"%2\" [%3/%4]") ).arg( ingName ).arg( propName ).arg( propUnits ).arg( propPerUnits );
			elList->append( el );
		}
	}
}


//The string going into the database is utf8 text interpreted as latin1
TQString TQSqlRecipeDB::escapeAndEncode( const TQString &s ) const
{
	TQString s_escaped = s;

	s_escaped.replace ( "'", "\\'" );
	s_escaped.replace ( ";", "\";@" ); // Small trick for only for parsing later on

	return TQString::fromLatin1( s_escaped.utf8() );
}

//The string coming out of the database is utf8 text, interpreted as though latin1.  Calling fromUtf8() on this gives us back the original utf8.
TQString TQSqlRecipeDB::unescapeAndDecode( const TQCString &s ) const
{
	return TQString::fromUtf8( s ).replace( "\";@", ";" ); // Use unicode encoding
}

bool TQSqlRecipeDB::ingredientContainsUnit( int ingredientID, int unitID )
{
	TQString command = TQString( "SELECT *  FROM unit_list WHERE ingredient_id= %1 AND unit_id=%2;" ).arg( ingredientID ).arg( unitID );
	TQSqlQuery recipeToLoad( command, database );
	if ( recipeToLoad.isActive() ) {
		return ( recipeToLoad.size() > 0 );
	}
	return false;
}

bool TQSqlRecipeDB::ingredientContainsProperty( int ingredientID, int propertyID, int perUnitsID )
{
	TQString command = TQString( "SELECT *  FROM ingredient_info WHERE ingredient_id=%1 AND property_id=%2 AND per_units=%3;" ).arg( ingredientID ).arg( propertyID ).arg( perUnitsID );
	TQSqlQuery recipeToLoad( command, database );
	if ( recipeToLoad.isActive() ) {
		return ( recipeToLoad.size() > 0 );
	}
	return false;
}

TQString TQSqlRecipeDB::categoryName( int ID )
{
	TQString command = TQString( "SELECT name FROM categories WHERE id=%1;" ).arg( ID );
	TQSqlQuery toLoad( command, database );
	if ( toLoad.isActive() && toLoad.next() )  // Go to the first record (there should be only one anyway.
		return ( unescapeAndDecode( toLoad.value( 0 ).toCString() ) );

	return ( TQString::null );
}

TQString TQSqlRecipeDB::ingredientName( int ID )
{
	TQString command = TQString( "SELECT name FROM ingredients WHERE id=%1" ).arg( ID );
	TQSqlQuery toLoad( command, database );
	if ( toLoad.isActive() && toLoad.next() )  // Go to the first record (there should be only one anyway.
		return ( unescapeAndDecode( toLoad.value( 0 ).toCString() ) );

	return ( TQString::null );
}

TQString TQSqlRecipeDB::prepMethodName( int ID )
{
	TQString command = TQString( "SELECT name FROM prep_methods WHERE id=%1" ).arg( ID );
	TQSqlQuery toLoad( command, database );
	if ( toLoad.isActive() && toLoad.next() )  // Go to the first record (there should be only one anyway.
		return ( unescapeAndDecode( toLoad.value( 0 ).toCString() ) );

	return ( TQString::null );
}

IngredientProperty TQSqlRecipeDB::propertyName( int ID )
{
	TQString command = TQString( "SELECT name,units FROM ingredient_properties WHERE id=%1;" ).arg( ID );
	TQSqlQuery toLoad( command, database );
	if ( toLoad.isActive() && toLoad.next() ) { // Go to the first record (there should be only one anyway.
		return ( IngredientProperty( unescapeAndDecode( toLoad.value( 0 ).toCString() ), unescapeAndDecode( toLoad.value( 1 ).toCString() ), ID ) );
	}

	return ( IngredientProperty( TQString::null, TQString::null ) );
}

Unit TQSqlRecipeDB::unitName( int ID )
{
	TQString command = TQString( "SELECT name,plural,name_abbrev,plural_abbrev,type FROM units WHERE id=%1" ).arg( ID );
	TQSqlQuery toLoad( command, database );
	if ( toLoad.isActive() && toLoad.next() ) { // Go to the first record (there should be only one anyway.
		Unit unit( unescapeAndDecode( toLoad.value( 0 ).toCString() ), unescapeAndDecode( toLoad.value( 1 ).toCString() ) );

		//if we don't have both name and plural, use what we have as both
		if ( unit.name.isEmpty() )
			unit.name = unit.plural;
		else if ( unit.plural.isEmpty() )
			unit.plural = unit.name;

		unit.name_abbrev = unescapeAndDecode( toLoad.value( 2 ).toCString() );
		unit.plural_abbrev = unescapeAndDecode( toLoad.value( 3 ).toCString() );
		unit.type = (Unit::Type) toLoad.value( 4 ).toInt();
		unit.id = ID;

		return unit;
	}

	return Unit();
}

int TQSqlRecipeDB::getCount( const TQString &table_name )
{
	m_command = "SELECT COUNT(1) FROM "+table_name;
	TQSqlQuery count( m_command, database );
	if ( count.isActive() && count.next() ) { // Go to the first record (there should be only one anyway.
		return count.value( 0 ).toInt();
	}

	return -1;
}

int TQSqlRecipeDB::categoryTopLevelCount()
{
	m_command = "SELECT COUNT(1) FROM categories WHERE parent_id='-1'";
	TQSqlQuery count( m_command, database );
	if ( count.isActive() && count.next() ) { // Go to the first record (there should be only one anyway.
		return count.value( 0 ).toInt();
	}

	return -1;
}

bool TQSqlRecipeDB::checkIntegrity( void )
{


	// Check existence of the necessary tables (the database may be created, but empty)
	TQStringList tables;
	tables << "ingredient_info" << "ingredient_list" << "ingredient_properties" << "ingredient_weights" << "ingredients" << "recipes" << "unit_list" << "units" << "units_conversion" << "categories" << "category_list" << "authors" << "author_list" << "db_info" << "prep_methods" << "ingredient_groups" << "yield_types" << "prep_method_list" << "ratings" << "rating_criteria" << "rating_criterion_list";

	TQStringList existingTableList = database->tables();
	for ( TQStringList::Iterator it = tables.begin(); it != tables.end(); ++it ) {
		bool found = false;

		for ( TQStringList::Iterator ex_it = existingTableList.begin(); ( ( ex_it != existingTableList.end() ) && ( !found ) ); ++ex_it ) {
			found = ( *ex_it == *it );
		}

		if ( !found ) {
			kdDebug() << "Recreating missing table: " << *it << "\n";
			createTable( *it );
		}
	}

	TQStringList newTableList = database->tables();
	if ( newTableList.isEmpty() )
		return false;


	// Check for older versions, and port

	kdDebug() << "Checking database version...\n";
	float version = databaseVersion();
	kdDebug() << "version found... " << version << " \n";
	kdDebug() << "latest version... " << latestDBVersion() << endl;
	if ( int( tqRound( databaseVersion() * 1e5 ) ) < int( tqRound( latestDBVersion() * 1e5 ) ) ) { //correct for float's imprecision
		switch ( KMessageBox::questionYesNo( 0, i18n( "<!doc>The database was created with a previous version of Krecipes.  Would you like Krecipes to update this database to work with this version of Krecipes?  Depending on the number of recipes and amount of data, this could take some time.<br><br><b>Warning: After updating, this database will no longer be compatible with previous versions of Krecipes.<br><br>Cancelling this operation may result in corrupting the database.</b>" ) ) ) {
		case KMessageBox::Yes:
			emit progressBegin(0,TQString::null,i18n("Porting database structure..."),50);
			portOldDatabases( version );
			emit progressDone();
			break;
		case KMessageBox::No:
			return false;
		}
	}

	return true;
}

void TQSqlRecipeDB::splitCommands( TQString& s, TQStringList& sl )
{
	sl = TQStringList::split( TQRegExp( ";{1}(?!@)" ), s );
}

void TQSqlRecipeDB::portOldDatabases( float /* version */ )
{}

float TQSqlRecipeDB::databaseVersion( void )
{

	TQString command = "SELECT ver FROM db_info";
	TQSqlQuery dbVersion( command, database );

	if ( dbVersion.isActive() && dbVersion.next() )
		return ( dbVersion.value( 0 ).toDouble() ); // There should be only one (or none for old DB) element, so go to first
	else
		return ( 0.2 ); // if table is empty, assume oldest (0.2), and port
}

void TQSqlRecipeDB::loadRatingCriterion( ElementList *list, int limit, int offset )
{
	list->clear();

	TQString command = "SELECT id,name FROM rating_criteria ORDER BY name"
	  +((limit==-1)?"":" LIMIT "+TQString::number(limit)+" OFFSET "+TQString::number(offset));
	TQSqlQuery toLoad( command, database );
	if ( toLoad.isActive() ) {
		while ( toLoad.next() ) {
			Element el;
			el.id = toLoad.value( 0 ).toInt();
			el.name = unescapeAndDecode( toLoad.value( 1 ).toCString() );
			list->append( el );
		}
	}
}

void TQSqlRecipeDB::loadCategories( ElementList *list, int limit, int offset )
{
	list->clear();

	m_command = "SELECT id,name FROM categories ORDER BY name"
	  +((limit==-1)?"":" LIMIT "+TQString::number(limit)+" OFFSET "+TQString::number(offset));
	TQSqlQuery categoryToLoad( m_command, database );
	if ( categoryToLoad.isActive() ) {
		while ( categoryToLoad.next() ) {
			Element el;
			el.id = categoryToLoad.value( 0 ).toInt();
			el.name = unescapeAndDecode( categoryToLoad.value( 1 ).toCString() );
			list->append( el );
		}
	}
}

void TQSqlRecipeDB::loadCategories( CategoryTree *list, int limit, int offset, int parent_id, bool recurse )
{
	TQString limit_str;
	if ( parent_id == -1 ) {
		emit progressBegin(0,TQString::null,i18n("Loading category list"));
		list->clear();

		//only limit the number of top-level categories
		limit_str = (limit==-1)?"":" LIMIT "+TQString::number(limit)+" OFFSET "+TQString::number(offset);
	}

	m_command = "SELECT id,name,parent_id FROM categories WHERE parent_id='"+TQString::number(parent_id)+"' ORDER BY name "+limit_str;

	TQSqlQuery categoryToLoad( TQString::null, database );
	//categoryToLoad.setForwardOnly(true); //FIXME? Subcategories aren't loaded if this is enabled, even though we only go forward

	categoryToLoad.exec(m_command);

	if ( categoryToLoad.isActive() ) {
		while ( categoryToLoad.next() ) {
			emit progress();

			int id = categoryToLoad.value( 0 ).toInt();
			Element el;
			el.id = id;
			el.name = unescapeAndDecode( categoryToLoad.value( 1 ).toCString() );
			CategoryTree *list_child = list->add( el );

			if ( recurse ) {
				//TQTime dbg_timer; dbg_timer.start(); kdDebug()<<"   calling TQSqlRecipeDB::loadCategories"<<endl;
				loadCategories( list_child, -1, -1, id ); //limit and offset won't be used
				// kdDebug()<<"   done in "<<dbg_timer.elapsed()<<" ms"<<endl;
			}
		}
	}

	if ( parent_id == -1 )
		emit progressDone();
}

void TQSqlRecipeDB::createNewCategory( const TQString &categoryName, int parent_id )
{
	TQString command;
	TQString real_name = categoryName.left( maxCategoryNameLength() );

	command = TQString( "INSERT INTO categories VALUES(%3,'%1',%2);" )
	          .arg( escapeAndEncode( real_name ) )
	          .arg( parent_id )
	          .arg( getNextInsertIDStr( "categories", "id" ) );
	TQSqlQuery categoryToCreate( command, database );

	emit categoryCreated( Element( real_name, lastInsertID() ), parent_id );
}

void TQSqlRecipeDB::modCategory( int categoryID, const TQString &newLabel )
{
	TQString command = TQString( "UPDATE categories SET name='%1' WHERE id=%2;" ).arg( escapeAndEncode( newLabel ) ).arg( categoryID );
	TQSqlQuery categoryToUpdate( command, database );

	emit categoryModified( Element( newLabel, categoryID ) );
}

void TQSqlRecipeDB::modCategory( int categoryID, int new_parent_id )
{
	TQString command = TQString( "UPDATE categories SET parent_id=%1 WHERE id=%2;" ).arg( new_parent_id ).arg( categoryID );
	TQSqlQuery categoryToUpdate( command, database );

	emit categoryModified( categoryID, new_parent_id );
}

void TQSqlRecipeDB::removeCategory( int categoryID )
{
	TQString command;

	command = TQString( "DELETE FROM categories WHERE id=%1;" ).arg( categoryID );
	TQSqlQuery categoryToRemove( command, database );

	command = TQString( "DELETE FROM category_list WHERE category_id=%1;" ).arg( categoryID );
	categoryToRemove.exec( command );

	//recursively delete subcategories
	command = TQString( "SELECT id FROM categories WHERE parent_id=%1;" ).arg( categoryID );
	categoryToRemove.exec( command );
	if ( categoryToRemove.isActive() ) {
		while ( categoryToRemove.next() ) {
			removeCategory( categoryToRemove.value( 0 ).toInt() );
		}
	}

	emit categoryRemoved( categoryID );
}


void TQSqlRecipeDB::loadAuthors( ElementList *list, int limit, int offset )
{
	list->clear();
	TQString command = "SELECT id,name FROM authors ORDER BY name"
	  +((limit==-1)?"":" LIMIT "+TQString::number(limit)+" OFFSET "+TQString::number(offset));
	TQSqlQuery authorToLoad( command, database );
	if ( authorToLoad.isActive() ) {
		while ( authorToLoad.next() ) {
			Element el;
			el.id = authorToLoad.value( 0 ).toInt();
			el.name = unescapeAndDecode( authorToLoad.value( 1 ).toCString() );
			list->append( el );
		}
	}
}

void TQSqlRecipeDB::createNewAuthor( const TQString &authorName )
{
	TQString command;
	TQString real_name = authorName.left( maxAuthorNameLength() );

	command = TQString( "INSERT INTO authors VALUES(%2,'%1');" ).arg( escapeAndEncode( real_name ) ).arg( getNextInsertIDStr( "authors", "id" ) );
	TQSqlQuery authorToCreate( command, database );

	emit authorCreated( Element( real_name, lastInsertID() ) );
}

void TQSqlRecipeDB::modAuthor( int authorID, const TQString &newLabel )
{
	TQString command;

	command = TQString( "UPDATE authors SET name='%1' WHERE id=%2;" ).arg( escapeAndEncode( newLabel ) ).arg( authorID );
	TQSqlQuery authorToCreate( command, database );

	emit authorRemoved( authorID );
	emit authorCreated( Element( newLabel, authorID ) );
}

void TQSqlRecipeDB::removeAuthor( int authorID )
{
	TQString command;

	command = TQString( "DELETE FROM authors WHERE id=%1;" ).arg( authorID );
	TQSqlQuery authorToRemove( command, database );

	emit authorRemoved( authorID );
}

int TQSqlRecipeDB::findExistingAuthorByName( const TQString& name )
{
	TQString search_str = escapeAndEncode( name.left( maxAuthorNameLength() ) ); //truncate to the maximum size db holds

	TQString command = TQString( "SELECT id FROM authors WHERE name LIKE '%1';" ).arg( search_str );
	TQSqlQuery elementToLoad( command, database ); // Run the query
	int id = -1;

	if ( elementToLoad.isActive() && elementToLoad.first() )
		id = elementToLoad.value( 0 ).toInt();

	return id;
}

int TQSqlRecipeDB::findExistingCategoryByName( const TQString& name )
{
	TQString search_str = escapeAndEncode( name.left( maxCategoryNameLength() ) ); //truncate to the maximum size db holds

	TQString command = TQString( "SELECT id FROM categories WHERE name LIKE '%1';" ).arg( search_str );
	TQSqlQuery elementToLoad( command, database ); // Run the query
	int id = -1;

	if ( elementToLoad.isActive() && elementToLoad.first() )
		id = elementToLoad.value( 0 ).toInt();

	return id;
}

int TQSqlRecipeDB::findExistingIngredientGroupByName( const TQString& name )
{
	TQString search_str = escapeAndEncode( name.left( maxIngGroupNameLength() ) ); //truncate to the maximum size db holds

	TQString command = TQString( "SELECT id FROM ingredient_groups WHERE name LIKE '%1';" ).arg( search_str );
	TQSqlQuery elementToLoad( command, database ); // Run the query
	int id = -1;

	if ( elementToLoad.isActive() && elementToLoad.first() )
		id = elementToLoad.value( 0 ).toInt();

	return id;
}

int TQSqlRecipeDB::findExistingIngredientByName( const TQString& name )
{
	TQString search_str = escapeAndEncode( name.left( maxIngredientNameLength() ) ); //truncate to the maximum size db holds

	TQString command = TQString( "SELECT id FROM ingredients WHERE name LIKE '%1';" ).arg( search_str );
	TQSqlQuery elementToLoad( command, database ); // Run the query
	int id = -1;

	if ( elementToLoad.isActive() && elementToLoad.first() )
		id = elementToLoad.value( 0 ).toInt();

	return id;
}

int TQSqlRecipeDB::findExistingPrepByName( const TQString& name )
{
	TQString search_str = escapeAndEncode( name.left( maxPrepMethodNameLength() ) ); //truncate to the maximum size db holds

	TQString command = TQString( "SELECT id FROM prep_methods WHERE name LIKE '%1';" ).arg( search_str );
	TQSqlQuery elementToLoad( command, database ); // Run the query
	int id = -1;

	if ( elementToLoad.isActive() && elementToLoad.first() )
		id = elementToLoad.value( 0 ).toInt();

	return id;
}

int TQSqlRecipeDB::findExistingPropertyByName( const TQString& name )
{
	TQString search_str = escapeAndEncode( name.left( maxPropertyNameLength() ) ); //truncate to the maximum size db holds

	TQString command = TQString( "SELECT id FROM ingredient_properties WHERE name LIKE '%1';" ).arg( search_str );
	TQSqlQuery elementToLoad( command, database ); // Run the query
	int id = -1;

	if ( elementToLoad.isActive() && elementToLoad.first() )
		id = elementToLoad.value( 0 ).toInt();

	return id;
}

int TQSqlRecipeDB::findExistingUnitByName( const TQString& name )
{
	TQString search_str = escapeAndEncode( name.left( maxUnitNameLength() ) ); //truncate to the maximum size db holds

	TQString command = "SELECT id FROM units WHERE name LIKE '" + search_str 
		  + "' OR plural LIKE '" + search_str 
		  + "' OR name_abbrev LIKE '" + search_str 
		  + "' OR plural_abbrev LIKE '" + search_str 
		  + "'";

	TQSqlQuery elementToLoad( command, database ); // Run the query
	int id = -1;

	if ( elementToLoad.isActive() && elementToLoad.first() )
		id = elementToLoad.value( 0 ).toInt();

	return id;
}

int TQSqlRecipeDB::findExistingRatingByName( const TQString& name )
{
	TQString search_str = escapeAndEncode( name ); //truncate to the maximum size db holds

	TQString command = TQString( "SELECT id FROM rating_criteria WHERE name LIKE '%1'" ).arg( search_str );
	TQSqlQuery elementToLoad( command, database ); // Run the query

	int id = -1;
	if ( elementToLoad.isActive() && elementToLoad.first() )
		id = elementToLoad.value( 0 ).toInt();

	return id;
}

int TQSqlRecipeDB::findExistingRecipeByName( const TQString& name )
{
	TQString search_str = escapeAndEncode( name.left( maxRecipeTitleLength() ) ); //truncate to the maximum size db holds

	TQString command = TQString( "SELECT id FROM recipes WHERE title LIKE '%1';" ).arg( search_str );
	TQSqlQuery elementToLoad( command, database ); // Run the query

	int id = -1;
	if ( elementToLoad.isActive() && elementToLoad.first() )
		id = elementToLoad.value( 0 ).toInt();

	return id;
}

int TQSqlRecipeDB::findExistingYieldTypeByName( const TQString& name )
{
	TQString search_str = escapeAndEncode( name.left( maxYieldTypeLength() ) ); //truncate to the maximum size db holds

	TQString command = TQString( "SELECT id FROM yield_types WHERE name LIKE '%1';" ).arg( search_str );
	TQSqlQuery elementToLoad( command, database ); // Run the query

	int id = -1;
	if ( elementToLoad.isActive() && elementToLoad.first() )
		id = elementToLoad.value( 0 ).toInt();

	return id;
}

void TQSqlRecipeDB::mergeAuthors( int id1, int id2 )
{
	TQSqlQuery update( TQString::null, database );

	//change all instances of 'id2' to 'id1'
	TQString command = TQString( "UPDATE author_list SET author_id=%1 WHERE author_id=%2" )
	                  .arg( id1 )
	                  .arg( id2 );
	update.exec( command );

	//and ensure no duplicates were created in this process
	command = TQString( "SELECT recipe_id FROM author_list WHERE author_id=%1 ORDER BY recipe_id" )
	          .arg( id1 );
	update.exec( command );
	int last_id = -1;
	if ( update.isActive() ) {
		while ( update.next() ) {
			int current_id = update.value( 0 ).toInt();
			if ( last_id == current_id ) {
				int count = -1;
				command = TQString( "SELECT COUNT(1) FROM author_list WHERE author_id=%1 AND recipe_id=%2" )
				          .arg( id1 )
				          .arg( last_id );
				TQSqlQuery remove( command, database);
				if ( remove.isActive() && remove.first() )
					count = remove.value(0).toInt();
				if ( count > 1 ) {
					command = TQString( "DELETE FROM author_list WHERE author_id=%1 AND recipe_id=%2" )
						.arg( id1 )
						.arg( last_id );
					database->exec( command );
	
					command = TQString( "INSERT INTO author_list VALUES(%1,%2)" )
						.arg( id1 )
						.arg( last_id );
					database->exec( command );
				}
			}
			last_id = current_id;
		}
	}

	//remove author with id 'id2'
	command = TQString( "DELETE FROM authors WHERE id=%1" ).arg( id2 );
	update.exec( command );
	emit authorRemoved( id2 );
}

void TQSqlRecipeDB::mergeCategories( int id1, int id2 )
{
	TQSqlQuery update( TQString::null, database );

	//change all instances of 'id2' to 'id1'
	TQString command = TQString( "UPDATE category_list SET category_id=%1 WHERE category_id=%2" )
	                  .arg( id1 )
	                  .arg( id2 );
	update.exec( command );

	//and ensure no duplicates were created in this process
	command = TQString( "SELECT recipe_id FROM category_list WHERE category_id=%1 ORDER BY recipe_id" )
	          .arg( id1 );
	update.exec( command );
	int last_id = -1;
	if ( update.isActive() ) {
		while ( update.next() ) {
			int current_id = update.value( 0 ).toInt();
			if ( last_id == current_id ) {
				int count = -1;
				command = TQString( "SELECT COUNT(1) FROM category_list WHERE category_id=%1 AND recipe_id=%2" )
				          .arg( id1 )
				          .arg( last_id );
				TQSqlQuery remove( command, database);
				if ( remove.isActive() && remove.first() )
					count = remove.value(0).toInt();
				if ( count > 1 ) {
					command = TQString( "DELETE FROM category_list WHERE category_id=%1 AND recipe_id=%2" )
						.arg( id1 )
						.arg( last_id );
					database->exec( command );
	
					command = TQString( "INSERT INTO category_list VALUES(%1,%2)" )
						.arg( id1 )
						.arg( last_id );
					database->exec( command );
				}
			}
			last_id = current_id;
		}
	}

	command = TQString( "UPDATE categories SET parent_id=%1 WHERE parent_id=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );

	//we don't want to have a category be its own parent...
	command = TQString( "UPDATE categories SET parent_id=-1 WHERE parent_id=id" );
	update.exec( command );

	//remove category with id 'id2'
	command = TQString( "DELETE FROM categories WHERE id=%1" ).arg( id2 );
	update.exec( command );

	emit categoriesMerged( id1, id2 );
}

void TQSqlRecipeDB::mergeIngredientGroups( int id1, int id2 )
{
	TQSqlQuery update( TQString::null, database );

	//change all instances of 'id2' to 'id1'
	TQString command = TQString( "UPDATE ingredient_list SET group_id=%1 WHERE group_id=%2" )
	                  .arg( id1 )
	                  .arg( id2 );
	update.exec( command );

	//remove ingredient with id 'id2'
	command = TQString( "DELETE FROM ingredient_groups WHERE id=%1" ).arg( id2 );
	update.exec( command );
	emit ingGroupRemoved( id2 );
}

void TQSqlRecipeDB::mergeIngredients( int id1, int id2 )
{
	TQSqlQuery update( TQString::null, database );

	//change all instances of 'id2' to 'id1'
	TQString command = TQString( "UPDATE ingredient_list SET ingredient_id=%1 WHERE ingredient_id=%2" )
	                  .arg( id1 )
	                  .arg( id2 );
	update.exec( command );

	//delete nutrient info associated with ingredient with id 'id2'
	command = TQString( "DELETE FROM ingredient_info WHERE ingredient_id=%1" )
	          .arg( id2 );
	update.exec( command );

	//update the unit_list
	command = TQString( "UPDATE unit_list SET ingredient_id=%1 WHERE ingredient_id=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );

	//and ensure no duplicates were created in this process
	command = TQString( "SELECT unit_id FROM unit_list WHERE ingredient_id=%1 ORDER BY unit_id" )
	          .arg( id1 );
	update.exec( command );
	int last_id = -1;
	if ( update.isActive() ) {
		while ( update.next() ) {
			int current_id = update.value( 0 ).toInt();
			if ( last_id == current_id ) {
				int count = -1;
				command = TQString( "SELECT COUNT(1) FROM unit_list WHERE ingredient_id=%1 AND unit_id=%2" )
				          .arg( id1 )
				          .arg( last_id );
				TQSqlQuery remove( command, database);
				if ( remove.isActive() && remove.first() )
					count = remove.value(0).toInt();
				if ( count > 1 ) {
					command = TQString( "DELETE FROM unit_list WHERE ingredient_id=%1 AND unit_id=%2" )
						.arg( id1 )
						.arg( last_id );
					database->exec( command );
	
					command = TQString( "INSERT INTO unit_list VALUES(%1,%2)" )
						.arg( id1 )
						.arg( last_id );
					database->exec( command );
				}
			}
			last_id = current_id;
		}
	}

	//update ingredient info
	command = TQString( "UPDATE ingredient_info SET ingredient_id=%1 WHERE ingredient_id=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );

	//and ensure no duplicates were created in this process
	//info associated with one ingredient will be lost... they should be the same ingredient and thus info anyways
	command = TQString( "SELECT property_id FROM ingredient_info WHERE ingredient_id=%1 ORDER BY property_id" )
	          .arg( id1 );
	update.exec( command );
	last_id = -1;
	if ( update.isActive() ) {
		while ( update.next() ) {
			int current_id = update.value( 0 ).toInt();
			if ( last_id == current_id ) {
				int count = -1;
				command = TQString( "SELECT COUNT(1) FROM ingredient_info WHERE ingredient_id=%1 AND property_id=%2" )
				          .arg( id1 )
				          .arg( last_id );
				TQSqlQuery remove( command, database);
				if ( remove.isActive() && remove.first() )
					count = remove.value(0).toInt();
				if ( count > 1 ) {
					command = TQString( "DELETE FROM ingredient_info WHERE ingredient_id=%1 AND property_id=%2" )
						.arg( id1 )
						.arg( last_id );
					database->exec( command );
	
					command = TQString( "INSERT INTO ingredient_info VALUES(%1,%2)" )
						.arg( id1 )
						.arg( last_id );
					database->exec( command );
				}

			}
			last_id = current_id;
		}
	}

	//remove ingredient with id 'id2'
	command = TQString( "DELETE FROM ingredients WHERE id=%1" ).arg( id2 );
	update.exec( command );
	emit ingredientRemoved( id2 );
}

void TQSqlRecipeDB::mergePrepMethods( int id1, int id2 )
{
	TQSqlQuery update( TQString::null, database );

	//change all instances of 'id2' to 'id1' in ingredient list
	TQString command = TQString( "UPDATE prep_method_list SET prep_method_id=%1 WHERE prep_method_id=%2" )
	                  .arg( id1 )
	                  .arg( id2 );
	update.exec( command );

	//change all instances of 'id2' to 'id1' in ingredient weights
	command = TQString( "UPDATE ingredient_weights SET prep_method_id=%1 WHERE prep_method_id=%2" )
	                  .arg( id1 )
	                  .arg( id2 );
	update.exec( command );

	//remove prep method with id 'id2'
	command = TQString( "DELETE FROM prep_methods WHERE id=%1" ).arg( id2 );
	update.exec( command );
	emit prepMethodRemoved( id2 );
}

void TQSqlRecipeDB::mergeProperties( int id1, int id2 )
{
	TQSqlQuery update( TQString::null, database );

	//change all instances of 'id2' to 'id1'
	TQString command = TQString( "UPDATE ingredient_properties SET id=%1 WHERE id=%2" )
	                  .arg( id1 )
	                  .arg( id2 );
	update.exec( command );

	command = TQString( "UPDATE ingredient_info SET property_id=%1 WHERE property_id=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );

	//remove prep method with id 'id2'
	command = TQString( "DELETE FROM ingredient_properties WHERE id=%1" ).arg( id2 );
	update.exec( command );
	emit propertyRemoved( id2 );
}

void TQSqlRecipeDB::mergeUnits( int id1, int id2 )
{
	TQSqlQuery update( TQString::null, database );

	//change all instances of 'id2' to 'id1' in unit list
	TQString command = TQString( "UPDATE unit_list SET unit_id=%1 WHERE unit_id=%2" )
	                  .arg( id1 )
	                  .arg( id2 );
	update.exec( command );

	//change all instances of 'id2' to 'id1' in ingredient list
	command = TQString( "UPDATE ingredient_list SET unit_id=%1 WHERE unit_id=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );

	//and ensure no duplicates were created in this process
	command = TQString( "SELECT ingredient_id FROM unit_list WHERE unit_id=%1 ORDER BY ingredient_id" )
	          .arg( id1 );
	update.exec( command );
	int last_id = -1;
	if ( update.isActive() ) {
		while ( update.next() ) {
			int current_id = update.value( 0 ).toInt();
			if ( last_id == current_id ) {
				int count = -1;
				command = TQString( "SELECT COUNT(1) FROM unit_list WHERE ingredient_id=%1 AND unit_id=%2" )
				          .arg( id1 )
				          .arg( last_id );
				TQSqlQuery remove( command, database);
				if ( remove.isActive() && remove.first() )
					count = remove.value(0).toInt();
				if ( count > 1 ) {
					command = TQString( "DELETE FROM unit_list WHERE ingredient_id=%1 AND unit_id=%2" )
						.arg( id1 )
						.arg( last_id );
					database->exec( command );
	
					command = TQString( "INSERT INTO unit_list VALUES(%1,%2)" )
						.arg( id1 )
						.arg( last_id );
					database->exec( command );
				}
			}
			last_id = current_id;
		}
	}

	//update ingredient info
	command = TQString( "UPDATE ingredient_info SET per_units=%1 WHERE per_units=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );

	//change all instances of 'id2' to 'id1' in unit_conversion
	command = TQString( "UPDATE units_conversion SET unit1_id=%1 WHERE unit1_id=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );
	command = TQString( "UPDATE units_conversion SET unit2_id=%1 WHERE unit2_id=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );

	//and ensure that the one to one ratio wasn't created
	command = TQString( "DELETE FROM units_conversion WHERE unit1_id=unit2_id" );
	update.exec( command );

	//update ingredient weights
	command = TQString( "UPDATE ingredient_weights SET unit_id=%1 WHERE unit_id=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );
	command = TQString( "UPDATE ingredient_weights SET weight_unit_id=%1 WHERE weight_unit_id=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );

	//change all instances of 'id2' to 'id1' in ingredient weights
	command = TQString( "UPDATE ingredient_weights SET unit_id=%1 WHERE unit_id=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );

	command = TQString( "UPDATE ingredient_weights SET weight_unit_id=%1 WHERE weight_unit_id=%2" )
	          .arg( id1 )
	          .arg( id2 );
	update.exec( command );

	//remove units with id 'id2'
	command = TQString( "DELETE FROM units WHERE id=%1" ).arg( id2 );
	update.exec( command );
	emit unitRemoved( id2 );
}

TQString TQSqlRecipeDB::getUniqueRecipeTitle( const TQString &recipe_title )
{
	//already is unique
	if ( findExistingRecipeByName( recipe_title ) == -1 )
		return recipe_title;

	TQString return_title = recipe_title; //If any error is produced, just go for default value (always return something)

	TQString command = TQString( "SELECT COUNT(1) FROM recipes WHERE title LIKE '%1 (%)';" ).arg( escapeAndEncode( recipe_title ) );

	TQSqlQuery alikeRecipes( command, database );
	if ( alikeRecipes.isActive() && alikeRecipes.first() )
	{
		int count = alikeRecipes.value( 0 ).toInt();
		return_title = TQString( "%1 (%2)" ).arg( recipe_title ).arg( count + 2 );

		//make sure this newly created title is unique (just in case)
		while ( findExistingRecipeByName( return_title ) != -1 ) {
			count--; //go down to find the skipped recipe(s)
			return_title = TQString( "%1 (%2)" ).arg( recipe_title ).arg( count + 2 );
		}
	}

	return return_title;
}

TQString TQSqlRecipeDB::recipeTitle( int recipeID )
{
	TQString command = TQString( "SELECT title FROM recipes WHERE id=%1;" ).arg( recipeID );
	TQSqlQuery recipeToLoad( command, database );
	if ( recipeToLoad.isActive() && recipeToLoad.next() )  // Go to the first record (there should be only one anyway.
		return ( unescapeAndDecode(recipeToLoad.value( 0 ).toCString()) );

	return ( TQString::null );
}

void TQSqlRecipeDB::emptyData( void )
{
	TQStringList tables;
	tables << "ingredient_info" << "ingredient_list" << "ingredient_properties" << "ingredients" << "recipes" << "unit_list" << "units" << "units_conversion" << "categories" << "category_list" << "authors" << "author_list" << "prep_methods" << "ingredient_groups" << "yield_types" << "ratings" << "rating_criteria" << "rating_criterion_list";
	TQSqlQuery tablesToEmpty( TQString::null, database );
	for ( TQStringList::Iterator it = tables.begin(); it != tables.end(); ++it ) {
		TQString command = TQString( "DELETE FROM %1;" ).arg( *it );
		tablesToEmpty.exec( command );
	}
}

void TQSqlRecipeDB::empty( void )
{
	TQSqlQuery tablesToEmpty( TQString::null, database );

	TQStringList list = database->tables();
	TQStringList::const_iterator it = list.begin();
	while( it != list.end() ) {
		TQString command = TQString( "DROP TABLE %1;" ).arg( *it );
		tablesToEmpty.exec( command );

		if ( !tablesToEmpty.isActive() )
			kdDebug()<<tablesToEmpty.lastError().databaseText()<<endl;

		++it;
	}
}

TQString TQSqlRecipeDB::getNextInsertIDStr( const TQString &table, const TQString &column )
{
	int next_id = getNextInsertID( table, column );

	TQString id_str;
	if ( next_id == -1 )
		id_str = "NULL";
	else
		id_str = TQString::number( next_id );

	return id_str;
}

void TQSqlRecipeDB::search( RecipeList *list, int items, const RecipeSearchParameters &parameters )
{
	TQString query = buildSearchQuery(parameters);

	TQValueList<int> ids;
	TQSqlQuery recipeToLoad( query, database );
	if ( recipeToLoad.isActive() ) {
		while ( recipeToLoad.next() ) {
			ids << recipeToLoad.value( 0 ).toInt();
		}
	}

	if ( ids.count() > 0 )
		loadRecipes( list, items, ids );
}

#include "qsqlrecipedb.moc"