File: EDASQLite.ec

package info (click to toggle)
ecere-sdk 0.44.15-1
  • links: PTS
  • area: main
  • in suites: sid, stretch
  • size: 97,712 kB
  • ctags: 54,695
  • sloc: ansic: 593,042; makefile: 12,250; yacc: 4,955; lex: 707; objc: 259; python: 252; xml: 102
file content (2049 lines) | stat: -rw-r--r-- 73,869 bytes parent folder | download
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
#ifdef ECERE_STATIC
public import static "ecere"
public import static "EDA"
#else
public import "ecere"
public import "EDA"
#endif

#ifdef __linux__
#include <sqlite3.h>
#else
#include "sqlite3.h"
#endif

#define uint _uint
#include "ffi.h"
#undef uint

__attribute__((unused)) static void UnusedFunction()
{
   int a;
   a.OnGetString(0,0,0);
   a.OnFree();
   a.OnCopy(null);
   a.OnCompare(null);
   a.OnSaveEdit(null,0);
   a.OnEdit(null,null,0,0,0,0,0);
   a.OnDisplay(null,0,0,0,0,0,0);
   a.OnGetDataFromString(null);
   a.OnUnserialize(null);
   a.OnSerialize(null);
}

default:
extern int __ecereVMethodID_class_OnGetString;
extern int __ecereVMethodID_class_OnGetDataFromString;
extern int __ecereVMethodID_class_OnCompare;
extern int __ecereVMethodID_class_OnSerialize;
extern int __ecereVMethodID_class_OnUnserialize;
extern int __ecereVMethodID_class_OnFree;
private:

int CollationCompare(Class type, int count1, const void * data1, int count2, const void * data2)
{
   if(type.type == normalClass || type.type ==  noHeadClass)
   {
      Instance inst1, inst2;
      int result;
      SerialBuffer buffer1 { size = count1, count = count1, buffer = (byte *)data1 };
      SerialBuffer buffer2 { size = count2, count = count2, buffer = (byte *)data2 };

      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnUnserialize])(type, &inst1, buffer1);
      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnUnserialize])(type, &inst2, buffer2);

      result = ((int (*)(void *, const void *, const void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, inst1, inst2);

      buffer1.buffer = null;
      buffer2.buffer = null;
      delete buffer1;
      delete buffer2;
      inst1.OnFree();
      inst2.OnFree();
      return result;
   }
   else if(type.type == structClass)
   {
      void * inst1, * inst2;
      int result;
      SerialBuffer buffer1 { size = count1, count = count1, buffer = (byte *)data1 };
      SerialBuffer buffer2 { size = count2, count = count2, buffer = (byte *)data2 };

      inst1 = new0 byte[type.structSize];
      inst2 = new0 byte[type.structSize];
      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnUnserialize])(type, inst1, buffer1);
      ((void (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnUnserialize])(type, inst2, buffer2);

      result = ((int (*)(void *, void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, inst1, inst2);

      buffer1.buffer = null;
      buffer2.buffer = null;
      delete buffer1;
      delete buffer2;
      delete inst1;
      delete inst2;
      return result;
   }
   else
      return ((int (*)(void *, const void *, const void *))(void *)type._vTbl[__ecereVMethodID_class_OnCompare])(type, data1, data2);
}

public class SQLiteStaticLink { }   // Until .imp generation is fixed

class SQLiteDataSource : DirFilesDataSourceDriver
{
   class_property(name) = "SQLite";
   class_property(databaseFileExtension) = "sqlite";

   Database OpenDatabase(const String name, CreateOptions createOptions, DataSource ds)
   {
      Database result = null;
      if(name && name[0])
      {
         String path = MakeDatabasePath(name);
         sqlite3 * db;

         // sqlite3_open(path, &db);
         // sqlite3_open_v2(path, &db, SQLITE_OPEN_READONLY /*SQLITE_OPEN_READWRITE*/ /*SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE*/, null );

         if(sqlite3_open_v2(path, &db, (createOptions == readOnly) ? SQLITE_OPEN_READONLY :
            (SQLITE_OPEN_READWRITE | ((createOptions == create) ? SQLITE_OPEN_CREATE : 0)), null))
         {
            // fprintf(stderr, "%s\n", s); // interesting
            printf($"EDASQLite: Can't open database (%s): %s\n", path, sqlite3_errmsg(db));
            sqlite3_close(db);
         }
         else
         {
            bool success = true;
            char command[1024];

            sqlite3_exec(db, "PRAGMA page_size=4096;", null, null, null);

            sprintf(command, "CREATE TABLE eda_table_fields(Table_Name TEXT, Name TEXT, Type TEXT, Length INT);");
            sqlite3_exec(db, command, null, null, null);

            if(createOptions != readOnly)
            {
               sqlite3_exec(db, "PRAGMA locking_mode=exclusive", null, null, null);
               sqlite3_exec(db, "DELETE FROM eda_table_fields WHERE Name = 'lockDummy'", null, null, null);
               if(sqlite3_exec(db, "INSERT INTO eda_table_fields (Table_Name, Name, Type, Length) VALUES ('lockDummy', 'lockDummy', 'lockDummy', 'lockDummy')", null, null, null))
                  success = false;
               else
                  sqlite3_exec(db, "DELETE FROM eda_table_fields WHERE Name = 'lockDummy'", null, null, null);
            }

            if(success)
               result = SQLiteDatabase { db = db };
         }
         delete path;
      }
      return result;
   }
}

class SQLiteField : Field
{
   char * name;
   Class type;
   int length;
   public LinkElement<SQLiteField> link;
   int num;
   int sqliteType;
   SQLiteTable tbl;

   ~SQLiteField()
   {
      delete name;
   }

   const String GetName()
   {
      return name;
   }
   Class GetType()
   {
      return type;
   }
   int GetLength() { return length; }
   Field GetPrev()
   {
      return link.prev;
   }
   Field GetNext()
   {
      return link.next;
   }
   Table GetTable()
   {
      return tbl;
   }
}

class SQLiteDatabase : Database
{
   sqlite3 * db;
   AVLTree<const String> collations { };

   ~SQLiteDatabase()
   {
      sqlite3_exec(db, "PRAGMA locking_mode=normal", null, null, null);
      // "Simply setting the locking-mode to NORMAL is not enough - locks are not released until the next time the database file is accessed."
      sqlite3_exec(db, "SELECT COUNT(*) from eda_table_fields", null, null, null);
      sqlite3_close(db);
   }

   uint ObjectsCount(ObjectType type)
   {
      // TODO
      return 0;
   }

   bool RenameObject(ObjectType type, const String name, const String rename)
   {
      // TODO
      return false;
   }

   bool DeleteObject(ObjectType type, const String name)
   {
      // TODO
      return false;
   }

   Table OpenTable(const String name, OpenOptions options)
   {
      char command[1024];
      //int result;
      int nRows = 0, nCols = 0;
      char ** t;
      SQLiteTable table = null;
      if(options.type == tablesList)
      {
         SQLiteField field;
         strcpy(command, "SELECT name FROM sqlite_master WHERE type='table' AND name!='eda_table_fields';");
         table = SQLiteTable { db = this, specialStatement = CopyString(command) };
         field = { tbl = table, name = CopyString("Name"), type = class(String), num = -1, sqliteType = SQLITE_TEXT };
         LinkTable(table);
         incref field;
         table._fields.Add(field);
      }
      else if(options.type == fieldsList)
      {
         SQLiteField field;

         sprintf(command, "SELECT Name, Type, Length FROM eda_table_fields WHERE Table_Name='%s';", name);
         table = SQLiteTable { db = this, specialStatement = CopyString(command) };
         LinkTable(table);
         field = { tbl = table, name = CopyString("Name"), type = class(String), num = -1, sqliteType = SQLITE_TEXT };
         incref field;
         table._fields.Add(field);
         field = { tbl = table, name = CopyString("Type"), type = class(Class), num = 0, sqliteType = SQLITE_TEXT };
         incref field;
         table._fields.Add(field);
         field = { tbl = table, name = CopyString("Length"), type = class(int), num = 1, sqliteType = SQLITE_INTEGER };
         incref field;
         table._fields.Add(field);
      }
      else if(options.type == tableRows)
      {
         bool addFields = false;

         sprintf(command, "SELECT Name FROM eda_table_fields WHERE Table_Name='%s';", name);
         /*result = */sqlite3_get_table(db, command, &t, &nRows, &nCols, null);
         if(!nRows && !nCols)
            addFields = true;

         sqlite3_free_table(t);

         sprintf(command, "SELECT sql FROM sqlite_master WHERE type='table' AND name='%s';", name);
         nCols = 0, nRows = 0;
         /*result = */sqlite3_get_table(db, command, &t, &nRows, &nCols, null);

         if((nCols || nRows) || options.create)
         {
            table = SQLiteTable { db = this, name = CopyString(name) };
            LinkTable(table);
            if(!nCols && !nRows)
               table.mustCreate = true;
            else
            {
               if(addFields)
               {
                  int r;
                  for(r = 1; r <= nRows; r++)      // There should be only 1 row here
                  {
                     char * sql = t[nCols * r];
                     char * bracket = strchr(sql, '(');
                     if(bracket)
                     {
                        int c = 0;
                        bracket++;
                        while(true)
                        {
                           char ch;
                           char fieldName[256];
                           char dataType[256];
                           int d;
                           int start = c;
                           int sqliteType = SQLITE_BLOB;
                           Class type = class(int);
                           fieldName[0] = 0;
                           dataType[0] = 0;

                           while((ch = bracket[c++]))
                           {
                              if(ch == ',' || ch == ')')
                                 break;
                           }
                           for(d = c-1; d >= 0 && bracket[d] != ' '; d--);

                           memcpy(fieldName, bracket + start, d - start);
                           fieldName[d - start] = 0;

                           memcpy(dataType, bracket + d + 1, c - d - 2);
                           dataType[c - d - 2] = 0;

                           while(ch && bracket[c] == ' ') c++;

                           if(!strcmp(dataType, "REAL")) { sqliteType = SQLITE_FLOAT; type = class(double); }
                           else if(!strcmp(dataType, "TEXT")) { sqliteType = SQLITE_TEXT; type = class(String); }
                           else if(!strcmp(dataType, "INTEGER")) { sqliteType = SQLITE_INTEGER; type = class(int); }
                           else if(!strcmp(dataType, "BLOB")) { sqliteType = SQLITE_BLOB; type = class(char *); } //class(byte *);

                           sprintf(command, "INSERT INTO eda_table_fields (Table_Name, Name, Type, Length) VALUES ('%s', '%s', '%s', %d);", name,
                              fieldName, type.name, 0);
                           /*result = */sqlite3_exec(db, command, null, null, null);

                           {
                              SQLiteField field { tbl = table, name = CopyString(fieldName), type = type, num = table._fields.count, sqliteType = sqliteType };
                              incref field;
                              table._fields.Add(field);
                           }

                           if(!ch || ch == ')') break;
                        }
                     }
                  }
               }
               else
               {
                  Table refTable = null;
                  sqlite3_stmt * statement;

                  sprintf(command, "SELECT Name, Type, Length FROM eda_table_fields WHERE Table_Name='%s';", name);
                  /*result = */sqlite3_prepare_v2(db, command, -1, &statement, null);

                  while(sqlite3_step(statement) != SQLITE_DONE)
                  {
                     const char * fieldName = (const char *)sqlite3_column_text(statement, 0);
                     const char * typeName = (const char *)sqlite3_column_text(statement, 1);
                     int length = sqlite3_column_int(statement, 2);
                     Class type = null;
                     int sqliteType = SQLITE_BLOB;

                     type.OnGetDataFromString(typeName);

                     if(type)
                     {
                        if(!strcmp(type.dataTypeString, "int") || !strcmp(type.dataTypeString, "unsigned int") ||
                           !strcmp(type.dataTypeString, "long") || !strcmp(type.dataTypeString, "long int") ||
                           !strcmp(type.dataTypeString, "uint") || !strcmp(type.dataTypeString, "uint32") ||
                           !strcmp(type.dataTypeString, "int64") || !strcmp(type.dataTypeString, "unsigned int64") || !strcmp(type.dataTypeString, "uint64") ||
                           !strcmp(type.dataTypeString, "short") || !strcmp(type.dataTypeString, "unsigned short") || !strcmp(type.dataTypeString, "uint16") ||
                           !strcmp(type.dataTypeString, "char") || !strcmp(type.dataTypeString, "unsigned char") || !strcmp(type.dataTypeString, "byte"))
                           sqliteType = SQLITE_INTEGER;
                        else if(!strcmp(type.dataTypeString, "double") || !strcmp(type.dataTypeString, "float"))
                           sqliteType = SQLITE_FLOAT;
                        else if(!strcmp(type.dataTypeString, "String") || !strcmp(type.dataTypeString, "char *"))
                           sqliteType = SQLITE_TEXT;
                        else
                        {
                           if(strcmp(type.fullName, "CIString") && !collations.Find(type.fullName))
                           {
                              collations.Add(type.fullName);
                              sqlite3_create_collation_v2(table.db.db, type.fullName, SQLITE_UTF8, type, CollationCompare, null);
                           }
                           sqliteType = SQLITE_BLOB;
                        }
                     }

                     {
                        Table * fTable = (Table *)(intptr)eClass_GetProperty(type, "table");
                        SQLiteField field { tbl = table, name = CopyString(fieldName), type = type, length = length, num = table._fields.count, sqliteType = sqliteType };
                        incref field;
                        if(fTable) refTable = *fTable;
                        if(!table.primaryKey && refTable && !strcmp(refTable.name, table.name))
                           table.primaryKey = field;

                        table._fields.Add(field);
                     }
                  }
                  sqlite3_finalize(statement);
               }
            }
         }
         sqlite3_free_table(t);
      }
      return (Table)table;
   }

   bool Begin()
   {
      char command[1024];
      int result;
      sprintf(command, "BEGIN;");
      result = sqlite3_exec(db, command, null, null, null);
      if(result)
         PrintLn($"BEGIN FAILED!");
      return result == SQLITE_OK;
   }

   bool Commit()
   {
      char command[1024];
      int result;
      sprintf(command, "COMMIT;");
      result = sqlite3_exec(db, command, null, null, null);
      if(result)
         PrintLn($"COMMIT FAILED!");
      return result == SQLITE_OK;
   }

   bool CreateCustomFunction(const char * name, SQLCustomFunction customFunction)
   {
      bool result = false;
#if !defined(__EMSCRIPTEN__)
      Class cfClass = customFunction._class;
      customFunction.method = eClass_FindMethod(cfClass, "function", cfClass.module);
      if(customFunction.method)
      {
         String typeString = CopyString(customFunction.method.dataTypeString);
         char * tokens[256];
         int count = TokenizeWith(typeString, sizeof(tokens)/sizeof(tokens[0]), tokens, "(,)", false);
         int c;
         bool variadic = false;

         for(c = 0; c < count; c++)
         {
            Class type = null;
            bool pointer = false;
            const String arg = tokens[c];
            char * space;
            TrimLSpaces(tokens[c], tokens[c]);
            if(strchr(arg, '*')) pointer = true;
            if(pointer)
               // Using String for generic pointer...
               type = class(String);
            else
            {
               if((space = strchr(arg, ' '))) *space = 0;
               if(!strcmp(arg, "void"))
                  type = null;
               else if(!strcmp(arg, "..."))
                  variadic = true;
               else
               {
                  if(cfClass.templateParams.count)
                  {
                     ClassTemplateParameter p;
                     int id = 0;
                     for(p = cfClass.templateParams.first; p; p = p.next, id++)
                     {
                        if(!strcmp(p.name, arg))
                           break;
                     }
                     if(p && cfClass.templateArgs)
                        arg = cfClass.templateArgs[id].dataTypeString;
                  }
                  type = eSystem_FindClass(customFunction._class.module, arg);
                  if(!type)
                     type = eSystem_FindClass(customFunction._class.module.application, arg);
               }
            }
            if(c == 0)
               customFunction.returnType = type;
            else
               customFunction.args.Add(type);
         }
         delete typeString;
         if(variadic)
         {
            result = false;
            // Variadic args don't make sense for SQL custom functions
            // Note that different CIF must be prepared for different set of arguments
            // ffi_prep_cif_var(&customFunction.cif, FFI_DEFAULT_ABI, args.count-1, rType, argTypes);
         }
         else
         {
            customFunction.rType = FFIGetType(customFunction.returnType, true);
            customFunction.argTypes.Add((void *)&ffi_type_pointer);    // This pointer for SQLCustomFunction object
            for(a : customFunction.args) customFunction.argTypes.Add((void *)FFIGetType(a, false));
            ffi_prep_cif(&customFunction.cif, FFI_DEFAULT_ABI, customFunction.argTypes.count, customFunction.rType, (ffi_type **) customFunction.argTypes.array);
            result = sqlite3_create_function(db, name, customFunction.args.count, SQLITE_UTF8, customFunction, SQLiteFunctionProcessor, null, null) == SQLITE_OK;
         }
      }
#endif
      return result;
   }
}

static class FFITypesHolder : Map<Class, String> { ~FFITypesHolder() { Free(); } }
FFITypesHolder structFFITypes { };
__attribute__((unused)) static Iterator dummy; // TOFIX: forward struct declaration issues on Clang

public ffi_type * FFIGetType(Class type, bool structByValue)
{
#if !defined(__EMSCRIPTEN__)
   if(type)
      switch(type.type)
      {
         // Pointer Types
         case structClass:
            if(structByValue)
            {
               MapIterator<Class, String> it { map = structFFITypes };
               ffi_type * ffiType = null;
               if(it.Index(type, false))
                  ffiType = (void *)it.data;
               else
               {
                  /*
                  DataMember member;
                  Array<String> memberTypes { };
                  for(member = type.membersAndProperties.first; member; member = member.next)
                  {
                     if(!member.isProperty)
                     {
                        memberTypes.Add(FFIGetType(member.dataType
                     }
                  }
                  */
                  ffiType = new0 ffi_type[1];
                  ffiType->size = type.structSize;
                  ffiType->type = FFI_TYPE_STRUCT;
                  structFFITypes[type] = (void *)ffiType;
               }
               return ffiType;
            }
         case normalClass:
         case noHeadClass:
         case unionClass:
            return &ffi_type_pointer;
         // Scalar Types
         case bitClass:
         case enumClass:
         case systemClass:
         case unitClass:
                 if(!strcmp(type.dataTypeString, "float"))  return &ffi_type_float;
            else if(!strcmp(type.dataTypeString, "double")) return &ffi_type_double;
            else
               switch(type.typeSize)
               {
                  case 1: return &ffi_type_uint8;
                  case 2: return &ffi_type_uint16;
                  case 4: return &ffi_type_uint32;
                  case 8: return &ffi_type_uint64;
               }
      }
   else
      return &ffi_type_void;
#endif
   return null;
}

static SerialBuffer staticBuffer { };
void SQLiteFunctionProcessor(sqlite3_context* context, int n, sqlite3_value** values)
{
#if !defined(__EMSCRIPTEN__)
   SQLCustomFunction sqlFunction = sqlite3_user_data(context);

   /*  // Simple 1 pointer param returning a string
   void * p = sqlFunction.method.function(sqlFunction, sqlite3_value_text(values[0]));
   sqlite3_result_text(context, p, strlen(p), SQLITE_TRANSIENT);
   */
   int64 retData = 0;
   void * ret = &retData;
   Array<String> args { size = sqlFunction.args.count + 1 };
   Iterator<String> ffiArg { sqlFunction.argTypes };
   Iterator<String> arg { args };
   int i = 0;

   // this * for the SQLCustomFunction
   args[0] = (void *)&sqlFunction;
   ffiArg.Next();
   // Get the arguments from SQLite
   for(a : sqlFunction.args)
   {
      ffi_type * type = (ffi_type *)sqlFunction.argTypes[i+1];
      if(i >= n) break;
      switch(a.type)
      {
         case normalClass:
         case noHeadClass:
         case structClass:
         case unionClass:
         {
            void ** data = new void *[1];
            args[i+1] = (void *)data;
            if(a == class(String))
            {
               int numBytes = sqlite3_value_bytes(values[i]);
               const char * text = (const char *)sqlite3_value_text(values[i]);
               *(char **)data = text ? new byte[numBytes+1] : null;
               if(text)
                  memcpy(*(char **)data, text, numBytes+1);
            }
            else
            {
               SerialBuffer buffer = staticBuffer; //{ };
               buffer.pos = 0;
               buffer._size = sqlite3_value_bytes(values[i]);
               buffer._buffer = (byte *)sqlite3_value_text(values[i]);
               //buffer._buffer = sqlite3_value_blob(curStatement);
               buffer.count = buffer._size;
               if(a.type == structClass)
                  *data = new byte[a.structSize];
               ((void (*)(void *, void *, void *))(void *)a._vTbl[__ecereVMethodID_class_OnUnserialize])(a, (a.type == structClass) ? *data : data, buffer);
               buffer._buffer = null;
               //delete buffer;
            }
            break;
         }
         case bitClass:
         case enumClass:
         case systemClass:
         case unitClass:
            if(type == &ffi_type_double || type == &ffi_type_float)
            {
               double d = sqlite3_value_double(values[i]);
               if(a.typeSize == 8)
               {
                  double * data = new double[1];
                  args[i+1] = (void *)data;
                  *data = d;
               }
               else
               {
                  float * data = new float[1];
                  args[i+1] = (void *)data;
                  *data = (float)d;
               }
            }
            else
            {
               switch(a.typeSize)
               {
                  case 8:
                  {
                     int64 * data = new int64[1];
                     args[i+1] = (void *)data;
                     *data = sqlite3_value_int64(values[i]);
                     break;
                  }
                  case 4:
                  {
                     int * data = new int[1];
                     args[i+1] = (void *)data;
                     *data = sqlite3_value_int(values[i]);
                     break;
                  }
                  case 2:
                  {
                     short * data = new short[1];
                     int value;
                     args[i+1] = (void *)data;
                     value = sqlite3_value_int(values[i]);
                     if(value < 0)
                        *data = (short)value;
                     else
                        *(uint16 *)data = (uint16)value;
                     break;
                  }
                  case 1:
                  {
                     char * data = new char[1];
                     int value;
                     args[i+1] = data;
                     value = sqlite3_value_int(values[i]);
                     if(value < 0)
                        *data = (char)value;
                     else
                        *(byte *)data = (byte)value;
                     break;
                  }
               }
            }
            break;
      }
      i++;
      ffiArg.Next();
   }
   if(sqlFunction.returnType && sqlFunction.returnType.type == structClass)
      ret = new byte[sqlFunction.returnType.typeSize];
   ffi_call(&sqlFunction.cif, (void *)sqlFunction.method.function, ret, args.array);
   // Give SQLite the return value
   if(sqlFunction.returnType)
   {
      ffi_type * type = sqlFunction.rType;
      Class r = sqlFunction.returnType;
      switch(r.type)
      {
         case normalClass:
         case noHeadClass:
         case structClass:
         case unionClass:
         {
            void * data = ret ? *(void **)ret : null;
            if(r.type == structClass)
               data = ret;
            if(r == class(String))
            {
               if(data)
                  sqlite3_result_text(context, (char *)data, strlen((char *)data), SQLITE_TRANSIENT);
               else
                  sqlite3_result_text(context, null, 0, SQLITE_TRANSIENT);
            }
            else
            {
               SerialBuffer buffer { };
               ((void (*)(void *, void *, void *))(void *)r._vTbl[__ecereVMethodID_class_OnSerialize])(r, data, buffer);
               sqlite3_result_text(context, (char *)buffer._buffer, buffer.count, SQLITE_TRANSIENT);
               delete buffer;

               // Avoid destroying Strings for now... (Returning memory owned by the Custom Function)
               ((void (*)(void *, void *))(void *)r._vTbl[__ecereVMethodID_class_OnFree])(r, data);
            }

            if(r.type == structClass)
               delete ret;
            break;
         }
         case bitClass:
         case enumClass:
         case systemClass:
         case unitClass:
            if(type == &ffi_type_double || type == &ffi_type_float)
            {
               if(r.typeSize == 8)
                  sqlite3_result_double(context, *(double *)ret);
               else
                  sqlite3_result_double(context, (double)*(float *)ret);
            }
            else
            {
               switch(r.typeSize)
               {
                  case 8:
                     sqlite3_result_int64(context, (sqlite3_int64)*(int64 *)ret);
                     break;
                  case 4:
                     sqlite3_result_int(context, *(int *)ret);
                     break;
                  case 2:
                  {
                     int value;
                     //if((int)data < 0)
                        value = (int)*(short *)ret;
                     //else
                        //value = (int)*(uint16 *)ret;
                     sqlite3_result_int(context, value);
                     break;
                  }
                  case 1:
                  {
                     int value;
                     //if((int)data < 0)
                        value = (int)*(char *)ret;
                     //else
                        //value = (int)*(byte *)ret;
                     sqlite3_result_int(context, value);
                     break;
                  }
               }
            }
            break;
      }
   }

   // Free Stuff up
   arg.Next();
   for(type : sqlFunction.args; arg.Next())
   {
      // Free instance
      void * data = *(void **)arg.data;
      ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type, data);
      if(type.type == structClass)
         delete data;
      // Free arg holder
      data = arg.data;
      delete data;
   }
   delete args;
#endif
}

class SQLiteTable : Table
{
   char * name;
   bool mustCreate;
   SQLiteDatabase db;
   LinkList<SQLiteField> _fields { };
   char * specialStatement;
   SQLiteField primaryKey;
   FieldIndex * indexFields;
   int indexFieldsCount;
   int64 lastID;

   Field AddField(const String fieldName, Class type, int length)
   {
      SQLiteField field;
      char command[1024];
      char dataType[256];
      int sqliteType;
      int result;
      Table refTable = null;
      Field idField = null;
      command[0] = 0;

      if(FindField(fieldName)) return null;

      if(!strcmp(type.dataTypeString, "int") || !strcmp(type.dataTypeString, "unsigned int") ||
         !strcmp(type.dataTypeString, "long") || !strcmp(type.dataTypeString, "long int") ||
         !strcmp(type.dataTypeString, "uint") || !strcmp(type.dataTypeString, "uint32") ||
         !strcmp(type.dataTypeString, "int64") || !strcmp(type.dataTypeString, "unsigned int64") || !strcmp(type.dataTypeString, "uint64") ||
         !strcmp(type.dataTypeString, "short") || !strcmp(type.dataTypeString, "unsigned short") || !strcmp(type.dataTypeString, "uint16") ||
         !strcmp(type.dataTypeString, "char") || !strcmp(type.dataTypeString, "unsigned char") || !strcmp(type.dataTypeString, "byte"))
      {
         strcpy(dataType, "INTEGER");
         sqliteType = SQLITE_INTEGER;
      }
      else if(!strcmp(type.dataTypeString, "double") || !strcmp(type.dataTypeString, "float"))
      {
         strcpy(dataType, "REAL");
         sqliteType = SQLITE_FLOAT;
      }
      else if(!strcmp(type.name, "CIString"))
      {
         strcpy(dataType, "TEXT");
         sqliteType = SQLITE_BLOB;
      }
      else if(!strcmp(type.dataTypeString, "String") || !strcmp(type.dataTypeString, "char *"))
      {
         strcpy(dataType, "TEXT");
         sqliteType = SQLITE_TEXT;
      }
      else
      {
         //strcpy(dataType, "BLOB");
         strcpy(dataType, "TEXT");
         sqliteType = SQLITE_BLOB;

         if(!db.collations.Find(type.fullName))
         {
            db.collations.Add(type.fullName);
            result = sqlite3_create_collation_v2(db.db, type.fullName, SQLITE_UTF8, type, CollationCompare, null);
         }
      }
      if(sqliteType != SQLITE_BLOB && eClass_IsDerived(type, class(eda::Id)) && type != class(eda::Id))
      {
         Table * table = (Table *)(intptr)eClass_GetProperty(type, "table");
         if(table) refTable = *table;
         if(refTable)
         {
            if(primaryKey || refTable != this)
            {
               for(idField = refTable.firstField; idField; idField = idField.next)
                  if(eClass_IsDerived(type, idField.type)) break;

               if(!idField)
                  PrintLn("WARNING: field not yet created for class ", (String)type.name);
            }
            else
               idField = primaryKey;
         }
         else
         {
            PrintLn($"WARNING: Table not yet created for class ", (String)type.name);
         }
      }

      if(mustCreate)
      {
         if(sqliteType == SQLITE_BLOB)
         {
            if(!strcmp(type.name, "CIString"))
               sprintf(command, "CREATE TABLE `%s`(%s %s COLLATE NOCASE);", name, fieldName, dataType);
            else
               sprintf(command, "CREATE TABLE `%s`(%s %s COLLATE '%s');", name, fieldName, dataType, type.fullName);
         }
         else if(refTable)
         {
            if(!idField && refTable == this)
               sprintf(command, "CREATE TABLE `%s`(`%s` %s PRIMARY KEY);", name, fieldName, dataType);
            else if(idField)
               sprintf(command, "CREATE TABLE `%s`(`%s` %s REFERENCES `%s`(`%s`));", name, fieldName, dataType, refTable.name, idField.name);
         }
         else
            sprintf(command, "CREATE TABLE `%s`(`%s` %s);", name, fieldName, dataType);
         result = sqlite3_exec(db.db, command, null, null, null);
         if(result) return null;
         mustCreate = false;
      }
      else
      {
         if(sqliteType == SQLITE_BLOB)
         {
            if(!strcmp(type.name, "CIString"))
               sprintf(command, "ALTER TABLE `%s` ADD `%s` %s COLLATE NOCASE;", name, fieldName, dataType);
            else
               sprintf(command, "ALTER TABLE `%s` ADD `%s` %s COLLATE `%s`;", name, fieldName, dataType, type.fullName);
         }
         else if(refTable)
         {
            if(!idField && refTable == this)
            {
               PrintLn($"WARNING: ALTER TABLE DOESN'T WORK WITH PRIMARY KEY FOR ", (String)name);
               sprintf(command, "ALTER TABLE `%s` ADD `%s` %s PRIMARY KEY;", name, fieldName, dataType);
            }
            else if(idField)
               sprintf(command, "ALTER TABLE `%s` ADD `%s` %s REFERENCES `%s`(`%s`);", name, fieldName, dataType, refTable.name, idField.name);
         }
         else
            sprintf(command, "ALTER TABLE `%s` ADD `%s` %s;", name, fieldName, dataType);
         result = sqlite3_exec(db.db, command, null, null, null);
         if(result) return null;
      }

      sprintf(command, "INSERT INTO eda_table_fields (Table_Name, Name, Type, Length) VALUES ('%s', '%s', '%s', %d);", name,
         fieldName, type.name, length);
      result = sqlite3_exec(db.db, command, null, null, null);

      field = { name = CopyString(fieldName), type = type, num = _fields.count, sqliteType = sqliteType };
      incref field;
      _fields.Add(field);
      if(!primaryKey && refTable == this)
         primaryKey = field;
      return (Field)field;
   }

   Field FindField(const String name)
   {
      for(f : _fields; !strcmp(f.name, name))
      {
         if(!primaryKey)
         {
            if(f.sqliteType != SQLITE_BLOB && eClass_IsDerived(f.type, class(eda::Id)))
            {

               Table * tablePtr = (Table *)(intptr)eClass_GetProperty(f.type, "table");
               if(tablePtr && *tablePtr == this)
                  primaryKey = f;
            }
         }
         return (Field)f;
      }
      return null;
   }

   bool GenerateIndex(int count, FieldIndex * fieldIndexes, bool init)
   {
      char command[1024];
      int c;
      int result;
      char indexName[4096];

      delete indexFields;
      indexFieldsCount = count;
      indexFields = new FieldIndex[count];
      memcpy(indexFields, fieldIndexes, count * sizeof(FieldIndex));

      // TODO: USE CODED INDEX NAME INSTEAD?
      strcpy(indexName, "index_");
      strcat(indexName, name);
      strcat(indexName, "_");
      for(c = 0; c<count; c++)
      {
         if(fieldIndexes[c].field)
         {
            if(count == 1 && fieldIndexes[c].field == primaryKey)
               return true;
            strcat(indexName, fieldIndexes[c].field.name);
            if(fieldIndexes[c].memberField)
            {
               strcat(indexName, ".");
               strcat(indexName, fieldIndexes[c].memberField.name);
            }
            strcat(indexName, (fieldIndexes[c].order == ascending) ? "+" : "-");
         }
         else
            return false;
      }

      sprintf(command, "CREATE INDEX IF NOT EXISTS `%s` ON `%s` (", indexName, name);
      for(c = 0; c<count; c++)
      {
         char columnName[1024];
         sprintf(columnName, "`%s` %s", fieldIndexes[c].field.name, (fieldIndexes[c].order == ascending) ? "ASC" : "DESC");
         if(c > 0) strcat(command, ", ");
         strcat(command, columnName);
      }
      strcat(command, ");");
      result = sqlite3_exec(db.db, command, null, null, null);

      return result == SQLITE_OK;
   }

   const String GetName()
   {
      return name;
   }

   Field GetFirstField()
   {
      return _fields.first;
   }

   Field GetPrimaryKey()
   {
      return primaryKey;
   }

   uint GetFieldsCount()
   {
      return _fields.count;
   }

   uint GetRowsCount()
   {
      char command[1024];
      char **t;
      int nCols, nRows;
      int result;
      uint rowCount = 0;
      sprintf(command, "SELECT COUNT(*) FROM `%s`;", name);
      result = sqlite3_get_table(db.db, command, &t, &nRows, &nCols, null);
      if(result == SQLITE_OK)
      {
         rowCount = atoi(t[1]);
         sqlite3_free_table(t);
      }
      return rowCount;
   }

   // Returns true if not ordered by row ID
   bool GetIndexOrder(char * fullOrder, bool flip)
   {
      if(!flip && (!indexFields || (indexFieldsCount == 1 && indexFields[0].field == primaryKey && indexFields[0].order == ascending)))
      {
         strcpy(fullOrder, " ORDER BY ROWID");
         return false;
      }
      else
      {
         int c;
         strcpy(fullOrder, " ORDER BY ");
         for(c = flip ? indexFieldsCount-1 : 0; flip ? (c >= 0) : (c < indexFieldsCount); flip ? c-- : c++)
         {
            char order[1024];
            FieldIndex * fIndex = &indexFields[c];
            order[0] = 0;
            if(c) strcat(order, ", ");
            strcat(order, "`");
            strcat(order, fIndex->field.name);
            strcat(order, "`");
            if(fIndex->order == (flip ? ascending : descending)) strcat(order, " DESC");
            strcat(fullOrder, order);
         }
         return true;
      }
   }

   Container<Field> GetFields()
   {
      return (Container<Field>)_fields;
   }

   DriverRow CreateRow()
   {
      char command[1024];
      sqlite3_stmt * statement;
      sqlite3_stmt * sysIDStmt = null, * insertStmt = null, * deleteStmt = null, * selectRowIDsStmt = null, * setRowIDStmt = null;
      sqlite3_stmt * prevStmt = null, * nextStmt = null, * lastStmt = null, * insertIDStmt = null;

      if(specialStatement)
         strcpy(command, specialStatement);
      else
      {
         char order[1024];
         /*sprintf(command, "SELECT ROWID, * FROM `%s` WHERE ? = ?;", name);
         sqlite3_prepare_v2(db.db, command, -1, &findStmt, null);*/
         sprintf(command, "SELECT ROWID, * FROM `%s` WHERE ROWID = ?;", name);
         sqlite3_prepare_v2(db.db, command, -1, &sysIDStmt, null);

         sprintf(command, "INSERT INTO `%s` DEFAULT VALUES;", name);
         sqlite3_prepare_v2(db.db, command, -1, &insertStmt, null);

         sprintf(command, "INSERT INTO `%s` (ROWID) VALUES(?);", name);
         sqlite3_prepare_v2(db.db, command, -1, &insertIDStmt, null);

         sprintf(command, "DELETE FROM `%s` WHERE ROWID = ?;", name);
         sqlite3_prepare_v2(db.db, command, -1, &deleteStmt, null);

         sprintf(command, "SELECT ROWID, * FROM `%s` WHERE ROWID < ? ORDER BY ROWID DESC LIMIT 1;", name);
         sqlite3_prepare_v2(db.db, command, -1, &prevStmt, null);

         sprintf(command, "SELECT ROWID, * FROM `%s` WHERE ROWID > ? ORDER BY ROWID LIMIT 1;", name);
         sqlite3_prepare_v2(db.db, command, -1, &nextStmt, null);

         sprintf(command, "SELECT MAX(ROWID), * FROM `%s`", name);
         sqlite3_prepare_v2(db.db, command, -1, &lastStmt, null);

         /*sprintf(command, "UPDATE `%s` SET ? = ? WHERE ROWID = ?;", name);

         sqlite3_prepare_v2(db.db, command, -1, &updateStmt, null);*/

         GetIndexOrder(order, false);
         sprintf(command, "SELECT ROWID, * FROM `%s`%s;", name, order);
      }
      sqlite3_prepare_v2(db.db, command, -1, &statement, null);

      sprintf(command, "SELECT ROWID FROM `%s` WHERE ROWID > ?", name);
      sqlite3_prepare_v2(db.db, command, -1, &selectRowIDsStmt, null);

      sprintf(command, "UPDATE `%s` SET ROWID = ? WHERE ROWID = ?", name);
      sqlite3_prepare_v2(db.db, command, -1, &setRowIDStmt, null);

      return SQLiteRow
         { tbl = this, defaultStatement = statement, curStatement = statement, sysIDStatement = sysIDStmt,
           insertStatement = insertStmt, deleteStatement = deleteStmt, selectRowIDsStmt = selectRowIDsStmt, setRowIDStmt = setRowIDStmt,
           previousStatement = prevStmt, nextStatement = nextStmt, lastStatement = lastStmt, insertIDStatement = insertIDStmt };
   }

   ~SQLiteTable()
   {
      delete name;
      delete specialStatement;
      delete indexFields;
      _fields.Free();
   }
}

class SQLiteRow : DriverRow
{
   SQLiteTable tbl;
   sqlite3_stmt * curStatement;

   sqlite3_stmt * defaultStatement;
   sqlite3_stmt * findStatement;
   sqlite3_stmt * prevFindStatement, * lastFindStatement;
   sqlite3_stmt * nextFindStatement;
   sqlite3_stmt * sysIDStatement;
   sqlite3_stmt * queryStatement;
   sqlite3_stmt * selectRowIDsStmt;
   sqlite3_stmt * setRowIDStmt;
   sqlite3_stmt * lastStatement;
   sqlite3_stmt * previousStatement;
   sqlite3_stmt * nextStatement;

   sqlite3_stmt * insertStatement;
   sqlite3_stmt * deleteStatement;
   sqlite3_stmt * updateStatement;
   sqlite3_stmt * insertIDStatement;
   bool done;
   done = true;
   int64 rowID;
   // Because we use GoToSysID() and the sysIDStatement when searching for a primary key with Find(),
   // this flag is used to distinguish between a Find() and a GoToSysID() for Select(next) purposes:
   bool findSysID;
   int findBindId;

   bool Nil()
   {
      return done;
   }

   ~SQLiteRow()
   {
      if(defaultStatement) sqlite3_finalize(defaultStatement);
      if(findStatement)    sqlite3_finalize(findStatement);
      if(prevFindStatement)sqlite3_finalize(prevFindStatement);
      if(lastFindStatement)sqlite3_finalize(lastFindStatement);
      if(nextFindStatement)sqlite3_finalize(nextFindStatement);
      if(sysIDStatement)   sqlite3_finalize(sysIDStatement);
      if(insertStatement)  sqlite3_finalize(insertStatement);
      if(deleteStatement)  sqlite3_finalize(deleteStatement);
      if(updateStatement)  sqlite3_finalize(updateStatement);
      if(queryStatement)   sqlite3_finalize(queryStatement);
      if(selectRowIDsStmt) sqlite3_finalize(selectRowIDsStmt);
      if(setRowIDStmt)     sqlite3_finalize(setRowIDStmt);
      if(previousStatement)sqlite3_finalize(previousStatement);
      if(nextStatement)    sqlite3_finalize(nextStatement);
      if(lastStatement)    sqlite3_finalize(lastStatement);
      if(insertIDStatement)    sqlite3_finalize(insertIDStatement);
   }

   bool Select(MoveOptions move)
   {
      int result;
      bool stepping = curStatement == previousStatement || curStatement == nextStatement || curStatement == lastStatement;
      if(!curStatement)
         curStatement = defaultStatement;
      switch(move)
      {
         case first:
         {
            sqlite3_reset(curStatement);
            result = sqlite3_step(curStatement);
            done = result == SQLITE_DONE || (result && result != SQLITE_ROW);
            if(done) { rowID = 0; sqlite3_reset(curStatement); return false; }
            rowID = sqlite3_column_int64(curStatement, 0);
            break;
         }
         case last:
         {
            sqlite3_reset(curStatement);
            curStatement = lastStatement;
            result = sqlite3_step(curStatement);
            done = result == SQLITE_DONE || (result && result != SQLITE_ROW);
            if(done) { rowID = 0; sqlite3_reset(curStatement); return false; }
            rowID = sqlite3_column_int64(curStatement, 0);
            break;
         }
         case middle:
            break;
         case next:
         case previous:
         {
            // For sysID statement, for a Find() we want to go through next/previous in order, otherwise we just go to nil
            if((move == next && curStatement != prevFindStatement && curStatement != lastFindStatement && !stepping && (curStatement != sysIDStatement || findSysID)) ||
               (move == previous && (curStatement == prevFindStatement || curStatement == lastFindStatement)))
            {
               result = sqlite3_step(curStatement);
               done = result == SQLITE_DONE || (result && result != SQLITE_ROW);
               if(done) { rowID = 0; sqlite3_reset(curStatement); return false; }
               rowID = sqlite3_column_int64(curStatement, 0);
            }
            else if(curStatement == prevFindStatement || curStatement == findStatement || curStatement == nextFindStatement || curStatement == lastFindStatement)
            {
               if(rowID)
               {
                  int bindId = findBindId;
                  sqlite3_reset((move == next) ? nextFindStatement : prevFindStatement);
                  BindCursorData((move == next) ? nextFindStatement : prevFindStatement, move,
                     (move == next && (!tbl.indexFields || (tbl.indexFieldsCount == 1 && tbl.indexFields[0].field == tbl.primaryKey && tbl.indexFields[0].order == ascending))) ? false : true, &bindId);
                  sqlite3_reset(curStatement);
                  curStatement = (move == next) ? nextFindStatement : prevFindStatement;
                  result = sqlite3_step(curStatement);
                  done = result == SQLITE_DONE || (result && result != SQLITE_ROW);
                  if(done) { rowID = 0; sqlite3_reset(curStatement); return false; }
                  rowID = sqlite3_column_int64(curStatement, 0);
               }
               else
               {
                  sqlite3_reset((move == next) ? findStatement : lastFindStatement);
                  sqlite3_reset(curStatement);
                  curStatement = (move == next) ? findStatement : lastFindStatement;
                  result = sqlite3_step(curStatement);
                  done = result == SQLITE_DONE || (result && result != SQLITE_ROW);
                  if(done) { rowID = 0; sqlite3_reset(curStatement); return false; }
                  rowID = sqlite3_column_int64(curStatement, 0);
               }
            }
            else
            {
               sqlite3_reset(curStatement);
               curStatement = (move == previous) ? (rowID ? previousStatement : lastStatement) : (rowID ? nextStatement : defaultStatement);
               sqlite3_bind_int64(curStatement, 1, (sqlite3_int64)rowID);
               result = sqlite3_step(curStatement);
               done = result == SQLITE_DONE || (result && result != SQLITE_ROW);
               if(done) { rowID = 0; sqlite3_reset(curStatement); return false; }
               rowID = sqlite3_column_int64(curStatement, 0);
            }
            break;
         }
         case nil:
            sqlite3_reset(curStatement);
            rowID = 0;
            done = true;
            break;
         case here:
            break;
      }
      return true;
   }

   bool Query(const char * queryString)
   {
      bool status = true;
      int result;

      if(curStatement)
         sqlite3_reset(curStatement);
      if(queryStatement)
      {
         sqlite3_finalize(queryStatement);
         queryStatement = null;
      }

      if(queryString)
      {
         result = sqlite3_prepare_v2(tbl.db.db, queryString, -1, &queryStatement, null);
         if(!result)
         {
            curStatement = queryStatement;
            if(!strchr(queryString, '?'))
            {
               result = sqlite3_step(queryStatement);

               done = result == SQLITE_DONE || (result && result != SQLITE_ROW);
               if(done) { rowID = 0; sqlite3_reset(queryStatement); return false; }

               rowID = sqlite3_column_int64(queryStatement, 0);
            }
         }
         else
         {
            printf("SQLite Query Error: %s\n", queryString);
            status = false;
         }
      }
      else
         curStatement = null;
      return status;
   }

   bool BindData(sqlite3_stmt * statement, int pos, SQLiteField fld, typed_object data, SerialBuffer * bufferOut)
   {
      int result = 1;
      Class dataType = fld.type;
      SerialBuffer buffer = null;
      switch(fld.sqliteType)
      {
         case SQLITE_INTEGER:
         {
            switch(dataType.typeSize)
            {
               case 8:
                  result = sqlite3_bind_int64(statement, pos, (sqlite3_int64)*(int64 *)data);
                  break;
               case 4:
                  result = sqlite3_bind_int(statement, pos, *(int *)data);
                  break;
               case 2:
               {
                  int value;
                  if((int)data < 0)
                     value = (int)*(short *)data;
                  else
                     value = (int)*(uint16 *)data;
                  result = sqlite3_bind_int(statement, pos, value);
                  break;
               }
               case 1:
               {
                  int value;
                  if((int)data < 0)
                     value = (int)*(char *)data;
                  else
                     value = (int)*(byte *)data;
                  result = sqlite3_bind_int(statement, pos, value);
                  break;
               }
            }
            break;
         }
         case SQLITE_FLOAT:
         {
            if(dataType.typeSize == 8)
               result = sqlite3_bind_double(statement, pos, *(double *)data);
            else
               result = sqlite3_bind_double(statement, pos, (double)*(float *)data);
            break;
         }
         case SQLITE_TEXT:
         {
            if((char *)data)
               result = sqlite3_bind_text(statement, pos, (char *)data, strlen((char *)data), SQLITE_TRANSIENT);
            else
               result = sqlite3_bind_null(statement, pos);
            break;
         }
         case SQLITE_BLOB:
         case SQLITE_NULL:
         {
            if((void *)data && dataType)
            {
               buffer = SerialBuffer { };
               ((void (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnSerialize])(dataType, data, buffer);
               result = sqlite3_bind_text(statement, pos, (char *)buffer._buffer, buffer.count, SQLITE_TRANSIENT);
            }
            else
               result = sqlite3_bind_null(statement, pos);
            break;
         }
      }
      if(bufferOut)
         *bufferOut = buffer;
      else
         delete buffer;
      return !result;
   }

   void AddCursorWhereClauses(char * command, MoveOptions move, bool useIndex)
   {
      if(move == next || move == previous)
      {
         // Where clauses for index
         if(useIndex)
         {
            int c;
            bool gotPrimaryKey = false;

            strcatf(command, " AND (");
            for(c = ((move == next) ? 0 : tbl.indexFieldsCount-1); (move == next) ? c < tbl.indexFieldsCount : c >= 0; (move == next) ? c++ : c--)
            {
               char where[1024];
               FieldIndex * fIndex = &tbl.indexFields[c];
               where[0] = 0;

               strcat(where, "`");
               strcat(where, fIndex->field.name);
               strcat(where, "` ");
               strcat(where, (fIndex->order == ((move == next) ? descending : ascending)) ? "<" : ">");
               strcat(where, " ? OR (");
               strcat(where, fIndex->field.name);
               if(fIndex->field == tbl.primaryKey)
                  gotPrimaryKey = true;
               strcat(where, " = ? AND (");
               strcat(command, where);
            }
            strcat(command, gotPrimaryKey ? "1)" : ((move == next) ? "ROWID > ?)" : "ROWID < ?)"));
            for(c = 0; c < tbl.indexFieldsCount; c++)
               strcat(command, "))");
         }
         else
            strcatf(command, (move == next) ? " AND ROWID > ?" : " AND ROWID < ?");
      }
   }

   void BindCursorData(sqlite3_stmt * stmt, MoveOptions move, bool useIndex, int * bindId)
   {
      if(move == next || move == previous)
      {
         // The binds for the Extra ordering Where clauses
         if(useIndex)
         {
            int c;
            /* // Code to not rely on curStatement being set up
            SQLiteRow dataRow = (SQLiteRow)tbl.CreateRow();
            dataRow.GoToSysID((uint)rowID);
            */
            for(c = ((move == next) ? 0 : tbl.indexFieldsCount-1); (move == next) ? c < tbl.indexFieldsCount : c >= 0; (move == next) ? c++ : c--)
            {
               FieldIndex * fIndex = &tbl.indexFields[c];
               int64 data;
               SQLiteField fld = (SQLiteField)fIndex->field;
               Class type = fld.type;
               void * dataPtr;
               SerialBuffer buffer;

               if(type.type == unitClass && !type.typeSize)
               {
                  Class dataType = eSystem_FindClass(type.module, type.dataTypeString);
                  if(dataType)
                     type = dataType;
               }
               if(type.type == structClass)
               {
                  data = (int64)(intptr)new0 byte[type.structSize];
                  dataPtr = (void *)(intptr)data;
               }
               // ((bool (*)())(void *)dataRow.GetData)(dataRow, fld, type, (type.type == structClass) ? (void *)data : &data);
               ((bool (*)())(void *)this.GetData)(this, fld, type, (type.type == structClass) ? (void *)(intptr)data : &data);
               if(type.type == normalClass || type.type == noHeadClass)
                  dataPtr = (void *)(intptr)data;
               else
                  dataPtr = &data;
               ((bool (*)())(void *)this.BindData)(this, stmt, (*bindId)++, fld, type, dataPtr, &buffer);
               // NOTE: The data is bound twice, for there are 2x '?' in the query from AddCursorWhereClauses
               // Reuse the buffer for Blobs...
               if(fld.sqliteType == SQLITE_BLOB || fld.sqliteType == SQLITE_NULL)
               {
                  sqlite3_bind_text(stmt, (*bindId)++, (char *)buffer._buffer, buffer.count, SQLITE_TRANSIENT);
                  delete buffer;
               }
               else
                  ((bool (*)())(void *)this.BindData)(this, stmt, (*bindId)++, fld, type, dataPtr, null);

               ((void (*)(void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnFree])(type, dataPtr);
            }
            // delete dataRow;
         }

         // Bind for the rowid
         sqlite3_bind_int64(stmt, (*bindId)++, (sqlite3_int64)rowID);
      }
   }

   bool Find(Field fld, MoveOptions move, MatchOptions match, typed_object data)
   {
      char order[1024], command[2048];
      int result;
      bool useIndex;
      sqlite3_stmt * stmt = null;
      int bindId = 1;

      if(fld == tbl.primaryKey)
      {
         if(curStatement) { sqlite3_reset(curStatement); curStatement = null; }
         if(findStatement) { sqlite3_finalize(findStatement); findStatement = null; }
         if(nextFindStatement) { sqlite3_finalize(nextFindStatement); nextFindStatement = null; }
         if(prevFindStatement) { sqlite3_finalize(prevFindStatement); prevFindStatement = null; }
         if(lastFindStatement) { sqlite3_finalize(lastFindStatement); lastFindStatement = null; }
         result = GoToSysID(*(Id *)data);
         if(result)
            findSysID = true;
         return result != 0;
      }

      useIndex = tbl.GetIndexOrder(order, false);
      // Basic Find
      sprintf(command, "SELECT ROWID, * FROM `%s` WHERE `%s` = ?", tbl.name, fld.name);
      AddCursorWhereClauses(command, move, useIndex);
      strcat(command, order);
      strcat(command, ";");
      result = sqlite3_prepare_v2(tbl.db.db, command, -1, &stmt, null);
      BindData(stmt, bindId++, (SQLiteField)fld, data, null);
      BindCursorData(stmt, move, useIndex, &bindId);

      // Currently, we can't reset curStatement until after BindCursorData, as current data is read from it
      if(curStatement) { sqlite3_reset(curStatement); curStatement = null; }
      if(findStatement) { sqlite3_finalize(findStatement); findStatement = null; }
      if(nextFindStatement) { sqlite3_finalize(nextFindStatement); nextFindStatement = null; }
      if(prevFindStatement) { sqlite3_finalize(prevFindStatement); prevFindStatement = null; }
      if(lastFindStatement) { sqlite3_finalize(lastFindStatement); lastFindStatement = null; }

      curStatement = findStatement = stmt;
      findBindId = bindId;

      // For going back to forward find
      bindId = 1;
      sprintf(command, "SELECT ROWID, * FROM `%s` WHERE `%s` = ?", tbl.name, fld.name);
      AddCursorWhereClauses(command, next, useIndex);
      strcat(command, order);
      strcat(command, ";");
      result = sqlite3_prepare_v2(tbl.db.db, command, -1, &stmt, null);
      BindData(stmt, bindId++, (SQLiteField)fld, data, null);
      nextFindStatement = stmt;

      // Backwards
      tbl.GetIndexOrder(order, true);
      // For tracing back finds
      bindId = 1;
      sprintf(command, "SELECT ROWID, * FROM `%s` WHERE `%s` = ?", tbl.name, fld.name);
      AddCursorWhereClauses(command, previous, true);
      strcat(command, order);
      strcat(command, ";");
      result = sqlite3_prepare_v2(tbl.db.db, command, -1, &stmt, null);
      BindData(stmt, bindId++, (SQLiteField)fld, data, null);
      prevFindStatement = stmt;

      // For tracing back from last
      bindId = 1;
      sprintf(command, "SELECT ROWID, * FROM `%s` WHERE `%s` = ?", tbl.name, fld.name);
      strcat(command, order);
      strcat(command, ";");
      result = sqlite3_prepare_v2(tbl.db.db, command, -1, &stmt, null);
      BindData(stmt, bindId++, (SQLiteField)fld, data, null);
      lastFindStatement = stmt;

      result = sqlite3_step(findStatement);

      done = result == SQLITE_DONE || (result && result != SQLITE_ROW);
      if(done)
      {
         rowID = 0;
         sqlite3_reset(findStatement);
      }
      else
         rowID = sqlite3_column_int64(findStatement, 0);
      return !done;
   }

   bool FindMultiple(FieldFindData * findData, MoveOptions move, int numFields)
   {
#define BINDDATA \
         for(c = 0; c < numFields; c++) \
         { \
            FieldFindData * fieldFind = &findData[c]; \
            SQLiteField sqlFld = (SQLiteField)findData->field; \
            Class dataType = sqlFld.type; \
            BindData(stmt, bindId++, sqlFld, (dataType.type == structClass || dataType.type == noHeadClass || dataType.type == normalClass) ? fieldFind->value.p : &fieldFind->value.i64, null); \
         }

      if(numFields)
      {
         char criterias[4096], command[4096], order[1024];
         int result;
         int c;
         bool useIndex;
         sqlite3_stmt * stmt = null;
         int bindId = 1;

         // Criterias
         sprintf(criterias, "SELECT ROWID, * FROM `%s` WHERE `", tbl.name);
         for(c = 0; c < numFields; c++)
         {
            FieldFindData * fieldFind = &findData[c];

            if(c) strcat(criterias, " AND `");
            strcat(criterias, fieldFind->field.name);
            strcat(criterias, "` = ?");
         }

         useIndex = tbl.GetIndexOrder(order, false);
         // Basic Find (multiple)
         strcpy(command, criterias);
         AddCursorWhereClauses(command, move, useIndex);
         strcat(command, order);
         strcat(command, ";");
         result = sqlite3_prepare_v2(tbl.db.db, command, -1, &stmt, null);
         BINDDATA;
         BindCursorData(stmt, move, useIndex, &bindId);

         // Currently, we can't reset curStatement until after BindCursorData, as current data is read from it
         if(curStatement) { sqlite3_reset(curStatement); curStatement = null; }
         if(findStatement) { sqlite3_finalize(findStatement); findStatement = null; }
         if(nextFindStatement) { sqlite3_finalize(nextFindStatement); nextFindStatement = null; }
         if(prevFindStatement) { sqlite3_finalize(prevFindStatement); prevFindStatement = null; }
         if(lastFindStatement) { sqlite3_finalize(lastFindStatement); lastFindStatement = null; }

         curStatement = findStatement = stmt;
         findBindId = bindId;

         // For tracing back forward finds
         bindId = 1;
         strcpy(command, criterias);
         AddCursorWhereClauses(command, previous, true);
         strcat(command, order);
         strcat(command, ";");
         result = sqlite3_prepare_v2(tbl.db.db, command, -1, &stmt, null);
         BINDDATA;
         nextFindStatement = stmt;

         // Backwards
         tbl.GetIndexOrder(order, true);
         // For tracing back finds
         bindId = 1;
         strcpy(command, criterias);
         AddCursorWhereClauses(command, next, useIndex);
         strcat(command, order);
         strcat(command, ";");
         result = sqlite3_prepare_v2(tbl.db.db, command, -1, &stmt, null);
         BINDDATA;
         prevFindStatement = stmt;

         // For tracing back from last
         bindId = 1;
         strcpy(command, criterias);
         strcat(command, order);
         strcat(command, ";");
         result = sqlite3_prepare_v2(tbl.db.db, command, -1, &stmt, null);
         BINDDATA;
         lastFindStatement = stmt;

         result = sqlite3_step(findStatement);
         done = result == SQLITE_DONE || (result && result != SQLITE_ROW);
         if(done)
         {
            rowID = 0;
            sqlite3_reset(findStatement);
         }
         else
            rowID = sqlite3_column_int64(findStatement, 0);
         return !done;
      }
      return false;
   }

   bool Synch(DriverRow to)
   {
      SQLiteRow rowTo = (SQLiteRow)to;
      if(tbl && rowTo.tbl && !strcmp(tbl.name, rowTo.tbl.name))
         return GoToSysID((uint)rowTo.rowID);
      return false;
   }

   bool Add(uint64 id)
   {
      int result;
      //char command[1024];
      //sprintf(command, "INSERT INTO `%s` DEFAULT VALUES;", tbl.name);
      //result = sqlite3_exec(tbl.db.db, command, null, null, null);
      if(id)
      {
         sqlite3_bind_int64(insertIDStatement, 1, (sqlite3_int64)id);
         result = sqlite3_step(insertIDStatement);
      }
      else
         result = sqlite3_step(insertStatement);
      if(result == SQLITE_DONE)     // if(result == SQLITE_OK)
      {
         rowID = sqlite3_last_insert_rowid(tbl.db.db);
         if(rowID > MAXDWORD)
         {
            int64 lastID = tbl.lastID;

            sqlite3_bind_int64(selectRowIDsStmt, 1, (sqlite3_int64)lastID);
            while(true)
            {
               int64 id;
               result = sqlite3_step(selectRowIDsStmt);
               if(result == SQLITE_DONE || result != SQLITE_ROW) break;
               id = sqlite3_column_int64(selectRowIDsStmt, 0);
               if(id - lastID > 1) break;
               lastID = id;
            }
            sqlite3_reset(selectRowIDsStmt);

            sqlite3_bind_int64(setRowIDStmt, 2, (sqlite3_int64)rowID);
            rowID = lastID + 1;
            tbl.lastID = rowID;
            sqlite3_bind_int64(setRowIDStmt, 1, (sqlite3_int64)rowID);
            result = sqlite3_step(setRowIDStmt);
            sqlite3_reset(setRowIDStmt);
         }
         sqlite3_reset(id ? insertIDStatement : insertStatement);
         curStatement = sysIDStatement;
         findSysID = false;
         sqlite3_reset(curStatement);
         sqlite3_bind_int64(sysIDStatement, 1, (sqlite3_int64)rowID);
         result = sqlite3_step(curStatement);
         done = false; // Make sure 'nil' is false
         return true;
      }
      sqlite3_reset(insertStatement);
      return false;
   }

   bool Delete()
   {
      int result;
      //char command[1024];
      //sprintf(command, "DELETE FROM `%s` WHERE ROWID = %d;", tbl.name, rowID);
      //result = sqlite3_exec(tbl.db.db, command, null, null, null);
      sqlite3_bind_int64(deleteStatement, 1, (sqlite3_int64)rowID);
      result = sqlite3_step(deleteStatement);
      sqlite3_reset(deleteStatement);
      rowID = 0;
      return result == SQLITE_OK || result == SQLITE_DONE;
   }

   bool GetData(Field fld, typed_object &data)
   {
      SQLiteField sqlFld = (SQLiteField)fld;
      int num = sqlFld.num + 1;
      Class dataType = *&sqlFld.type;


      switch(sqlFld.sqliteType)
      {
         case SQLITE_INTEGER:
         {
            switch(dataType.typeSize)
            {
               case 8:
                  if(fld == tbl.primaryKey)
                     *(int64 *)data = rowID;
                  else
                     *(int64 *)data = sqlite3_column_int64(curStatement, num);
                  break;
               case 4:
                  if(fld == tbl.primaryKey)
                     *(int *)data = (int)(uint)rowID;
                  else
                     *(int *)data = sqlite3_column_int(curStatement, num);
                  break;
               case 2:
               {
                  int value;
                  if(fld == tbl.primaryKey)
                     value = (int)(uint)rowID;
                  else
                     value = sqlite3_column_int(curStatement, num);
                  if(value < 0)
                     *(short *)data = (short)value;
                  else
                     *(uint16 *)data = (uint16)value;
                  break;
               }
               case 1:
               {
                  int value;
                  if(fld == tbl.primaryKey)
                     value = (int)(uint)rowID;
                  else
                     value = sqlite3_column_int(curStatement, num);
                  if(value < 0)
                     *(char *)data = (char)value;
                  else
                     *(byte *)data = (byte)value;
                  break;
               }
            }
            break;
         }
         case SQLITE_FLOAT:
         {
            double d = sqlite3_column_double(curStatement, num);
            if(dataType.typeSize == 8)
               *(double *)data = d;
            else
               *(float *)data = (float)d;
            break;
         }
         case SQLITE_TEXT:
         {
            int numBytes = sqlite3_column_bytes(curStatement, num);
            const char * text = (const char *)sqlite3_column_text(curStatement, num);
            *(char **)data = text ? new byte[numBytes+1] : null;
            if(text)
               memcpy(*(char **)data, text, numBytes+1);
            break;
         }
         case SQLITE_BLOB:
         {
            SerialBuffer buffer { };
            //buffer._buffer = sqlite3_column_blob(curStatement, num);
            buffer._size = sqlite3_column_bytes(curStatement, num);
            buffer._buffer = (byte *)sqlite3_column_text(curStatement, num);
            buffer.count = buffer._size;

            ((void (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnUnserialize])(dataType, data, buffer);

            buffer._buffer = null;
            delete buffer;
            break;
         }
      }
      return true;
   }

   bool SetData(Field fld, typed_object data)
   {
      SQLiteField sqlFld = (SQLiteField)fld;
      int result;
      char command[1024];

      if(updateStatement)
         sqlite3_finalize(updateStatement);
      sprintf(command, "UPDATE `%s` SET `%s` = ? WHERE ROWID = ?;", tbl.name, sqlFld.name);
      // TODO: Shouldn't we cache those update statements per field?
      result = sqlite3_prepare_v2(tbl.db.db, command, -1, &updateStatement, null);
      sqlite3_bind_int64(updateStatement, 2, (sqlite3_int64)rowID);
      BindData(updateStatement, 1, (SQLiteField)fld, data, null);
      result = sqlite3_step(updateStatement);
      sqlite3_reset(updateStatement);
      if(fld == tbl.primaryKey)
         rowID = *(uint64 *)data;
      return result == SQLITE_DONE;
   }

   uint64 GetSysID()
   {
      return (int64)rowID;
   }

   bool GoToSysID(uint64 id)
   {
      //char command[1024];
      int result;
      rowID = (int64)id;
      //if(statement)
         //sqlite3_finalize(statement);
      //sprintf(command, "SELECT ROWID, * FROM `%s` WHERE ROWID = ?;", tbl.name);
      //result = sqlite3_prepare_v2(tbl.db.db, command, -1, &statement, null);

      findSysID = false;
      if(curStatement)
         sqlite3_reset(curStatement);

      curStatement = sysIDStatement;
      sqlite3_reset(sysIDStatement);
      sqlite3_bind_int64(curStatement, 1, (sqlite_int64)rowID);
      result = sqlite3_step(curStatement);
      done = result == SQLITE_DONE || (result && result != SQLITE_ROW);
      if(done) { rowID = 0; sqlite3_reset(curStatement); return false; }
      return !done;
   }

   bool SetQueryParam(int paramID, int value)
   {
      int result;
      if(curStatement != queryStatement)
      {
         if(curStatement) sqlite3_reset(curStatement);
         curStatement = queryStatement;
      }
      sqlite3_reset(queryStatement);
      result = sqlite3_bind_int(queryStatement, paramID, value);
      return !result;
   }

   bool SetQueryParam64(int paramID, int64 value)
   {
      int result;
      if(curStatement != queryStatement)
      {
         if(curStatement) sqlite3_reset(curStatement);
         curStatement = queryStatement;
      }
      sqlite3_reset(queryStatement);
      result = sqlite3_bind_int64(queryStatement, paramID, (sqlite_int64)value);
      return !result;
   }

   bool SetQueryParamText(int paramID, const char * data)
   {
      int result;
      if(curStatement != queryStatement)
      {
         if(curStatement) sqlite3_reset(curStatement);
         curStatement = queryStatement;
      }
      sqlite3_reset(queryStatement);
      if(data)
         result = sqlite3_bind_text(queryStatement, paramID, (char *)data, strlen((char *)data), SQLITE_TRANSIENT);
      else
         result = sqlite3_bind_text(queryStatement, paramID, null, 0, SQLITE_TRANSIENT);
      return !result;
   }

   bool SetQueryParamObject(int paramID, const void * data, Class type)
   {
      int result;
      if(curStatement != queryStatement)
      {
         if(curStatement) sqlite3_reset(curStatement);
         curStatement = queryStatement;
      }
      sqlite3_reset(queryStatement);
      {
         SerialBuffer buffer { };
         ((void (*)(void *, const void *, void *))(void *)type._vTbl[__ecereVMethodID_class_OnSerialize])(type, data, buffer);
         result = sqlite3_bind_text(queryStatement, paramID, (char *)buffer._buffer, buffer.count, SQLITE_TRANSIENT);
         delete buffer;
      }
      return !result;
   }

   bool BindQueryData(int pos, SQLiteField fld, typed_object data)
   {
      if(curStatement != queryStatement)
      {
         if(curStatement) sqlite3_reset(curStatement);
         curStatement = queryStatement;
      }
      sqlite3_reset(queryStatement);
      return BindData(queryStatement, pos, fld, data, null);
   }

   bool GetQueryData(int num, SQLiteField fld, typed_object & data)
   {
      SQLiteField sqlFld = (SQLiteField)fld;
      Class dataType = *&sqlFld.type;

      switch(sqlFld.sqliteType)
      {
         case SQLITE_INTEGER:
         {
            switch(dataType.typeSize)
            {
               case 8:
                  if(fld == tbl.primaryKey)
                     *(int64 *)data = rowID;
                  else
                     *(int64 *)data = sqlite3_column_int64(curStatement, num);
                  break;
               case 4:
                  if(fld == tbl.primaryKey)
                     *(int *)data = (int)(uint)rowID;
                  else
                     *(int *)data = sqlite3_column_int(curStatement, num);
                  break;
               case 2:
               {
                  int value;
                  if(fld == tbl.primaryKey)
                     value = (int)(uint)rowID;
                  else
                     value = sqlite3_column_int(curStatement, num);
                  if(value < 0)
                     *(short *)data = (short)value;
                  else
                     *(uint16 *)data = (uint16)value;
                  break;
               }
               case 1:
               {
                  int value;
                  if(fld == tbl.primaryKey)
                     value = (int)(uint)rowID;
                  else
                     value = sqlite3_column_int(curStatement, num);
                  if(value < 0)
                     *(char *)data = (char)value;
                  else
                     *(byte *)data = (byte)value;
                  break;
               }
            }
            break;
         }
         case SQLITE_FLOAT:
         {
            double d = sqlite3_column_double(curStatement, num);
            if(dataType.typeSize == 8)
               *(double *)data = d;
            else
               *(float *)data = (float)d;
            break;
         }
         case SQLITE_TEXT:
         {
            int numBytes = sqlite3_column_bytes(curStatement, num);
            const char * text = (const char *)sqlite3_column_text(curStatement, num);
            *(char **)data = text ? new byte[numBytes+1] : null;
            if(text)
               memcpy(*(char **)data, text, numBytes+1);
            break;
         }
         case SQLITE_BLOB:
         {
            SerialBuffer buffer { };
            //buffer._buffer = sqlite3_column_blob(curStatement, num);
            buffer._size = sqlite3_column_bytes(curStatement, num);
            buffer._buffer = (byte *)sqlite3_column_text(curStatement, num);
            buffer.count = buffer._size;

            ((void (*)(void *, void *, void *))(void *)dataType._vTbl[__ecereVMethodID_class_OnUnserialize])(dataType, data, buffer);

            buffer._buffer = null;
            delete buffer;
            break;
         }
      }
      return true;
   }

   /*char * GetExtraColumn(int paramID)
   {
      SQLiteField lastFld = tbl._fields.last;
      return sqlite3_column_text(curStatement, lastFld.num + 1 + paramID);
   }*/
   const char * GetColumn(int paramID)
   {
      return (const char *)sqlite3_column_text(curStatement, paramID);
   }
}