File: dbd_sqlite3.c

package info (click to toggle)
libdbi-drivers 0.9.0-13
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,160 kB
  • sloc: ansic: 19,030; sh: 10,963; xml: 2,759; makefile: 584
file content (1890 lines) | stat: -rw-r--r-- 55,139 bytes parent folder | download | duplicates (5)
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
/*
 * libdbi-drivers - database drivers for libdbi, a database independent
 * abstraction layer for C.
 * Copyright (C) 2002-2007, Markus Hoenicka
 * http://libdbi-drivers.sourceforge.net
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * dbd_sqlite3.c: SQLite3 database support (using libsqlite3)
 * Copyright (C) 2005-2007, Markus Hoenicka <mhoenicka@users.sourceforge.net>
 * http://libdbi-drivers.sourceforge.net
 * 
 * $Id: dbd_sqlite3.c,v 1.49 2013/01/08 23:55:54 mhoenicka Exp $
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#define _GNU_SOURCE /* we need asprintf */

/* this is defined by the Makefile and passed via -D */
/* #define DBDIR /usr/local/var/lib/libdbi/sqlite3 */

#ifndef HAVE_ATOLL
long long atoll(const char *str);
#endif

#ifndef HAVE_STRTOLL
long long strtoll(const char *nptr, char **endptr, int base);
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <limits.h> /* defines _POSIX_PATH_MAX */
#include <dirent.h> /* directory listings */
#include <unistd.h> /* stat */
#include <sys/stat.h> /* S_ISXX macros */
#include <sys/types.h> /* directory listings */
#include <ctype.h> /* toupper, etc */

#include <dbi/dbi.h>
#include <dbi/dbi-dev.h>
#include <dbi/dbd.h>

#include <sqlite3.h>
#include "dbd_sqlite3.h"

static const dbi_info_t driver_info = {
  "sqlite3",
  "SQLite3 database support (using libsqlite3)",
  "Markus Hoenicka <mhoenicka@users.sourceforge.net>",
  "http://libdbi-drivers.sourceforge.net",
  "dbd_sqlite3 v" VERSION,
  __DATE__
};

static const char *custom_functions[] = SQLITE3_CUSTOM_FUNCTIONS;
static const char *reserved_words[] = SQLITE3_RESERVED_WORDS;
static const char default_dbdir[] = DBDIR;

/* the encoding strings */
static const char sqlite3_encoding_UTF8[] = "UTF-8";
static const char sqlite3_encoding_UTF16[] = "UTF-16";

/* pointers to sqlite3 functions - avoids tons of if/elses */
/* int (*my_sqlite3_open)(const char *,sqlite3 **); */

/* forward declarations */
static int _real_dbd_connect(dbi_conn_t *conn, const char* database);
static void _translate_sqlite3_type(enum enum_field_types fieldtype, unsigned short *type, unsigned int *attribs);
static void _get_row_data(dbi_result_t *result, dbi_row_t *row, unsigned long long rowidx);
static int find_result_field_types(char* field, dbi_conn_t *conn, const char* statement);
static int getTables(char** tables, int index, const char* statement, char* curr_table);
static void freeTables(char** tables, int table_count);
static char* get_field_type(char*** ptr_result_table, const char* curr_field_name, int numrows);
static size_t sqlite3_escape_string(char *to, const char *from, size_t length);
static int wild_case_compare(const char *str,const char *str_end,
		      const char *wildstr,const char *wildend,
		      char escape);
static const char* _conn_get_dbdir(dbi_conn_t *conn);


/* the real functions */
void dbd_register_driver(const dbi_info_t **_driver_info, const char ***_custom_functions, const char ***_reserved_words) {
  /* this is the first function called after the driver module is loaded into memory */
  *_driver_info = &driver_info;
  *_custom_functions = custom_functions;
  *_reserved_words = reserved_words;
}

int dbd_initialize(dbi_driver_t *driver) {
  /* perform any database-specific server initialization.
   * this is called right after dbd_register_driver().
   * return -1 on error, 0 on success. if -1 is returned, the driver will not
   * be added to the list of available drivers. */

  /* this indicates the driver can be safely unloaded when libdbi is
     shut down. Change the value to '0' (zero) if the driver, or a
     library it is linked against, installs exit handlers via
     atexit() */
  _dbd_register_driver_cap(driver, "safe_dlclose", 1);

  /* this indicates the database engine supports transactions */
  _dbd_register_driver_cap(driver, "transaction_support", 1);
  
  /* this indicates the database engine supports savepoints */
  _dbd_register_driver_cap(driver, "savepoint_support", 1);

  return 0;
}

int dbd_finalize(dbi_driver_t *driver) {
	/* perform any database-specific client library shutdown.
	 * this is called right before dlclose()ing the driver.
	 * return -1 on error, 0 on success. */

	return 0;
}

int dbd_connect(dbi_conn_t *conn) {
  /* connect using the database set with the "dbname" option */
  return _real_dbd_connect(conn, "");
}

static int _real_dbd_connect(dbi_conn_t *conn, const char* database) {
  /* connect using the database passed as an argument. If passed NULL
     or an empty string, this function tries to use the database set
     with the "dbname" option */
  sqlite3 *sqcon;
  int sqlite3_errcode;
  char* sq_errmsg = NULL;
  char* db_fullpath = NULL;

  /* ToDo: make OS-independent */
  const char dirsep[] = "/";

  const char *dbname;
  const char *dbdir;
  const char *encoding;

  int timeout;
  dbi_result dbi_result;

  /* initialize error stuff */
  conn->error_number = 0;
  conn->error_message = NULL;

  /* sqlite3 does not use hostname, username, password, port */
  if (database && *database) {
    dbname = database;
  }
  else {
    dbname = dbi_conn_get_option(conn, "dbname");
  }

  if (!dbname) {
    _dbd_internal_error_handler(conn, "no database specified", DBI_ERROR_CLIENT);
    return -1;
  }

  encoding = dbi_conn_get_option(conn, "encoding");

  if (!encoding) {
    /* use UTF-8 as default */
    encoding = sqlite3_encoding_UTF8;
  }

  dbdir = _conn_get_dbdir(conn);
	
  if (!dbdir) {
    _dbd_internal_error_handler(conn, "no database directory specified", DBI_ERROR_CLIENT);
    return -1;
  }

  /* the requested database is a file in the given directory. Assemble
     full path of database */
  db_fullpath = malloc(strlen(dbname)+strlen(dbdir)+2); /* leave room
							   for \0 and / */
  if (db_fullpath == NULL) {
    _dbd_internal_error_handler(conn, NULL, DBI_ERROR_NOMEM);
    return -1;
  }

  /* start with an empty string */
  db_fullpath[0] = '\0';

  if (strcmp(dbname, ":memory:")) {
    if (dbdir && *dbdir) {
      strcpy(db_fullpath, dbdir);
    }
    if (db_fullpath[strlen(db_fullpath)-1] != *dirsep) {
      /* db_fullpath length was checked above */
      strcat(db_fullpath, dirsep);
    }
  }
  /* else: open an in-memory database which does not require the path prefix */
  if (dbname && *dbname) {
    /* db_fullpath length was checked above */
    strcat(db_fullpath, dbname);
  }

  /*   fprintf(stderr, "try to open %s<<\n", db_fullpath); */
  if (!strcmp(encoding, sqlite3_encoding_UTF8)) {
    sqlite3_errcode = sqlite3_open(db_fullpath, &sqcon);
  }
  else {
    sqlite3_errcode = sqlite3_open16(db_fullpath, &sqcon);
  }

  free(db_fullpath);
	
  if (sqlite3_errcode) {

    /* todo: check the return code */

    /* sqlite3 creates a database the first time we try to access
       it. If this function fails, there's usually a problem with
       access rights or an existing database is corrupted or created
       with an incompatible version */
    if (sq_errmsg) {
      _dbd_internal_error_handler(conn, sq_errmsg, (const int) sqlite3_errcode);
      free(sq_errmsg);
    }
    else {
      _dbd_internal_error_handler(conn, "could not open database", (const int) sqlite3_errcode);
    }
    return -1;
  }
  else {
    conn->connection = (void *)sqcon;
    if (dbname) {
      conn->current_db = strdup(dbname);
    }
  }

  /* set the SQLite timeout to timeout milliseconds. The older
     SQLite3-specific setting takes precedence over the generic timeout
     option for backwards compatibility */
  timeout = dbi_conn_get_option_numeric(conn, "sqlite3_timeout");

  if (timeout == -1) {
    /* generic timeout is specified in seconds, not milliseconds */
    timeout = 1000*dbi_conn_get_option_numeric(conn, "timeout");
    if (timeout == -1) {
      timeout = 0;
    }
  }

  sqlite3_busy_timeout(sqcon, timeout);

  /* this is required to make SQLite work like other database engines
     in that it returns the column information even if there are no
     rows in a result set */
  dbi_result = dbd_query(conn, "PRAGMA empty_result_callbacks=1");
  
  if (dbi_result) {
    dbi_result_free(dbi_result);
  }

  return 0;
}

int dbd_disconnect(dbi_conn_t *conn) {
  if (conn->connection) {
    sqlite3_close((sqlite3 *)conn->connection);
    if (conn->error_number) {
      conn->error_number = 0;
    }
    if (conn->error_message) {
      free(conn->error_message);
      conn->error_message = NULL;
    }
  }
  return 0;
}

int dbd_fetch_row(dbi_result_t *result, unsigned long long rowidx) {
  dbi_row_t *row = NULL;

  if (result->result_state == NOTHING_RETURNED) {
    return 0;
  }

  if (result->result_state == ROWS_RETURNED) {
    /* get row here */
    row = _dbd_row_allocate(result->numfields);
    _get_row_data(result, row, rowidx);
    _dbd_row_finalize(result, row, rowidx);
  }
	
  return 1; /* 0 on error, 1 on successful fetchrow */
}

int dbd_free_query(dbi_result_t *result) {
  if (result->result_handle) {
    sqlite3_free_table((char **)result->result_handle);
  }
  return 0;
}

int dbd_goto_row(dbi_result_t *result, unsigned long long rowidx, unsigned long long currowidx) {
  result->currowidx = rowidx;
  return 1;
}

int dbd_get_socket(dbi_conn_t *conn){
  /* sqlite3 does not use sockets, so we'll always return 0 */
  return (int)0;
}

const char *dbd_get_encoding(dbi_conn_t *conn){
  const char* encoding;
  /* encoding is a compile-time option with the sqlite3
     library. Instead of using the sqlite3-provided string, we use the
     iana.org names */

  encoding = dbi_conn_get_option(conn, "encoding");

  if (!encoding) {
    /* use UTF-8 as default */
    encoding = sqlite3_encoding_UTF8;
  }
  /* todo: implement utf8 vs utf16 distinction */
  return encoding;
}

const char* dbd_encoding_to_iana(const char *db_encoding) {
  /* nothing to translate, return original encoding */
  return db_encoding;
}

const char* dbd_encoding_from_iana(const char *iana_encoding) {
  /* nothing to translate, return original encoding */
  return iana_encoding;
}

char *dbd_get_engine_version(dbi_conn_t *conn, char *versionstring) {
  dbi_result_t *dbi_result;
  const char *versioninfo = NULL;

  /* initialize return string */
  *versionstring = '\0';

  dbi_result = dbd_query(conn, "SELECT sqlite_version()");

  if (dbi_result) {
    if (dbi_result_next_row(dbi_result)) {
      versioninfo = dbi_result_get_string_idx(dbi_result, 1);
      strncpy(versionstring, versioninfo, VERSIONSTRING_LENGTH-1);
      versionstring[VERSIONSTRING_LENGTH-1] = '\0';
    }
    dbi_result_free(dbi_result);
  }

  return versionstring;
}

dbi_result_t *dbd_list_dbs(dbi_conn_t *conn, const char *pattern) {
  char *sq_errmsg = NULL;
  char old_cwd[_POSIX_PATH_MAX] = "";
  char sql_command[_POSIX_PATH_MAX+64];
  int retval;
  size_t entry_size;
  DIR *dp;
  struct dirent *entry;
  struct dirent *result;
  struct stat statbuf;
  dbi_result rs;

  /* sqlite3 has no builtin function to list databases. Databases are just
     files in the data directory. We search for matching files and fill a
     temporary table with what we've found. Then we query this table and
     pretend sqlite3 has done all the work */
  const char *sq_datadir = _conn_get_dbdir(conn);

  /* this is not nice but we have to drop the table even if it does not
     exist (sqlite3 has no way to list *temporary* tables so we can't check
     for it's existence). Then we start over with a fresh table lest we
     want duplicates.
     Update: Now apparently there is a system table that lists
     temporary tables, but the DROP TABLE error doesn't hurt and is
     most likely faster than checking for the existence of the table */
  rs = dbd_query(conn, "DROP TABLE libdbi_databases");
  dbi_result_free(rs);
  rs = dbd_query(conn, "CREATE TEMPORARY TABLE libdbi_databases (dbname VARCHAR(255))");
  dbi_result_free(rs);

  if (sq_datadir && (dp = opendir(sq_datadir)) == NULL) {
    _dbd_internal_error_handler(conn, "could not open data directory", DBI_ERROR_CLIENT);
    return NULL;
  }

  /* allocate memory for readdir_r(3) */
  entry_size = _dirent_buf_size(dp);
  if (entry_size == 0) {
    return NULL;
  }

  entry = (struct dirent *) malloc (entry_size);
  if (entry == NULL) {
    return NULL;
  }

  memset (entry, 0, entry_size);

  getcwd(old_cwd, _POSIX_PATH_MAX);
  chdir(sq_datadir);

  while (1) {
    result = NULL;
    retval = readdir_r(dp, entry, &result);
    if (retval != 0 || result == NULL) {
      break;
    }

    stat(entry->d_name, &statbuf);
    if (S_ISREG(statbuf.st_mode)) {

      /* todo: check this string */

      /* we do a magic number check here to make sure we
	 get only databases, not random files in the current directory.
	 SQLite3 databases start with the string:
	 
	 SQLite format 3

      */
      FILE* fp;

      if ((fp = fopen(entry->d_name, "r")) != NULL) {
	char magic_text[16] = "";

	if (fread(magic_text, 1, 15, fp) < 15) {
	  /* either we can't read at all, or the file is too small
	     for a sqlite3 database anyway */
	  fclose(fp);
	  continue;
	}

	/* terminate magic text */
	magic_text[15] = '\0';

	if (strcmp(magic_text, "SQLite format 3")) {
	  /* this file is not meant for us */
	  fclose(fp);
	  continue;
	}

	/* close file again, we're done reading */
	fclose(fp);

	/* match filename to a pattern, or use all found files */
	if (pattern) {
	  if (wild_case_compare(entry->d_name, &entry->d_name[strlen(entry->d_name)], pattern, &pattern[strlen(pattern)], '\\') == 0) {
	    snprintf(sql_command, _POSIX_PATH_MAX+64, "INSERT INTO libdbi_databases VALUES ('%s')", entry->d_name);
	    retval = sqlite3_exec((sqlite3*)(conn->connection), sql_command, NULL, NULL, &sq_errmsg);
	  }
	}
	else {
	  snprintf(sql_command, _POSIX_PATH_MAX+64, "INSERT INTO libdbi_databases VALUES ('%s')", entry->d_name);
	  retval = sqlite3_exec((sqlite3*)(conn->connection), sql_command, NULL, NULL, &sq_errmsg);
	}	  

	if (sq_errmsg) {
	  _dbd_internal_error_handler(conn, sq_errmsg, (const int) retval);
	  free(sq_errmsg);
	  break;
	}
      }
      /* else: we can't read it, so forget about it */
    }
  } /* end while */

  free(entry);
  closedir(dp);
  chdir(old_cwd);

  /* now query our temporary table */
  return dbd_query(conn, "SELECT dbname FROM libdbi_databases");
}

dbi_result_t *dbd_list_tables(dbi_conn_t *conn, const char *db, const char *pattern) {
  /* list tables in a database. The current implementation lists permanent
     tables only, as most applications know about the temporary tables
     they created anyway.
  */
  dbi_result_t *dbi_result;
  dbi_conn_t* tempconn;
  dbi_inst instance;
  int retval;
  char* sq_errmsg = NULL;
  char* sql_cmd;
  dbi_result_t *rs;

  /* this function tries to query a specific database, so we need a
     separate connection to that other database, retrieve the table names,
     and feed them to a temporary table in our main connection */
  instance = dbi_driver_get_instance(dbi_conn_get_driver(conn));
  tempconn = dbi_conn_new_r("sqlite3", instance);

  /* we explicitly cast to (char*) as we discard the "const" thing here */
  dbi_conn_set_option(tempconn, "dbname", (char*)db);
  dbi_conn_set_option(tempconn, "sqlite3_dbdir", (char*)_conn_get_dbdir(conn));

  if (dbi_conn_connect(tempconn) < 0) {
    _dbd_internal_error_handler(conn, NULL, DBI_ERROR_NOCONN);
    dbi_conn_close(tempconn);
    return NULL;
  }
  
  /* create temporary table for table names. The DROP command won't hurt
     if the table doesn't exist yet */
  rs = dbd_query(conn, "DROP TABLE libdbi_tablenames");
  dbi_result_free(rs);
  rs = dbd_query(conn, "CREATE TEMPORARY TABLE libdbi_tablenames (tablename VARCHAR(255))");
  dbi_result_free(rs);
  /*   fprintf(stderr, "created temporary table\n"); */

  /* sqlite3 does not support the SHOW command, so we have to extract the
     information from the accessory sqlite3_master table */
  if (pattern == NULL) {
    asprintf(&sql_cmd, "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name");
  }
  else {
    asprintf(&sql_cmd, "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%s' ORDER BY name", pattern);
  }
  dbi_result = dbd_query(tempconn, sql_cmd);
  free(sql_cmd);
  /*   fprintf(stderr, "select from sqlite3_master has run\n"); */
  if (dbi_result) {
    while (dbi_result_next_row(dbi_result)) {
      asprintf(&sql_cmd, "INSERT INTO libdbi_tablenames VALUES ('%s')", dbi_result_get_string(dbi_result, "name"));
      retval = sqlite3_exec((sqlite3*)(conn->connection), sql_cmd, NULL, NULL, &sq_errmsg);
      free(sql_cmd);
      sqlite3_free(sq_errmsg);
    }
    dbi_result_free(dbi_result);
  }
  else {
    dbi_conn_error(tempconn, (const char**)&sq_errmsg);
  }

  //  sqlite3_close((sqlite3*)(tempconn->connection));
  dbi_conn_close(tempconn);

  return dbd_query(conn, "SELECT tablename FROM libdbi_tablenames ORDER BY tablename");
}

size_t dbd_quote_string(dbi_driver_t *driver, const char *orig, char *dest) {
  /* foo's -> 'foo\'s' */
  size_t len;
	
  strcpy(dest, "'");
  len = sqlite3_escape_string(dest+1, orig, strlen(orig));	
  strcat(dest, "'");
	
  return len+2;
}

size_t dbd_conn_quote_string(dbi_conn_t *conn, const char *orig, char *dest) {
  return dbd_quote_string(conn->driver, orig, dest);
}

size_t dbd_quote_binary(dbi_conn_t *conn, const unsigned char *orig, size_t from_length, unsigned char **ptr_dest) {
  unsigned char *temp;
  size_t len;

  if ((temp = malloc(from_length*2)) == NULL) {
    return 0;
  }

  strcpy((char *)temp, "\'");
  if (from_length) {
    len = _dbd_encode_binary(orig, from_length, temp+1);
  }
  else {
    len = 0;
  }
  strcat((char *)temp, "'");

  *ptr_dest = temp;

  return len+2;
}

dbi_result_t *dbd_query(dbi_conn_t *conn, const char *statement) {
  /* allocate a new dbi_result_t and fill its applicable members:
   * 
   * result_handle, numrows_matched, and numrows_changed.
   * everything else will be filled in by DBI */
	
  dbi_result_t *result;
  int query_res;
  int numrows;
  int numcols;
  char** result_table;
  char* errmsg;
  int idx = 0;
  unsigned short fieldtype;
  unsigned int fieldattribs;
  dbi_error_flag errflag = 0;

  query_res = sqlite3_get_table((sqlite3*)conn->connection,
			       statement,
			       &result_table,
			       &numrows,
			       &numcols,
			       &errmsg);

  if (query_res) {
    return NULL;
  }
	
  result = _dbd_result_create(conn, (void *)result_table, numrows, (unsigned long long)sqlite3_changes((sqlite3*)conn->connection));
/*    printf("numrows:%d, numcols:%d<<\n", numrows, numcols); */
  _dbd_result_set_numfields(result, numcols);

  /* assign types to result */
  while (idx < numcols) {
    int type;
    char *item;
    
    type = find_result_field_types(result_table[idx], conn, statement);
    /*     printf("type: %d<<\n", type); */
    _translate_sqlite3_type(type, &fieldtype, &fieldattribs);

    /* we need the field name without the table name here */
    item = strchr(result_table[idx], (int)'.');
    if (!item) {
      item = result_table[idx];
    }
    else {
      item++;
    }

    _dbd_result_add_field(result, idx, item, fieldtype, fieldattribs);
    idx++;
  }
  
  return result;
}

dbi_result_t *dbd_query_old(dbi_conn_t *conn, const char *statement) {
  /* allocate a new dbi_result_t and fill its applicable members:
   * 
   * result_handle, numrows_matched, and numrows_changed.
   * everything else will be filled in by DBI */
	
  dbi_result_t *result;
  int query_res;
  int numrows;
  int numcols;
  char** result_table;
  char* errmsg;
  int idx = 0;
  unsigned short fieldtype;
  unsigned int fieldattribs;
  dbi_error_flag errflag = 0;

  query_res = sqlite3_get_table((sqlite3*)conn->connection,
				statement,
				&result_table,
				&numrows,
				&numcols,
				&errmsg);

  if (query_res) {
    if(result_table != NULL) {
      sqlite3_free_table(result_table);
    }
    return NULL;
  }
	
  result = _dbd_result_create(conn, (void *)result_table, numrows, (unsigned long long)sqlite3_changes((sqlite3*)conn->connection));
  /*   printf("numrows:%d, numcols:%d<<\n", numrows, numcols); */
  _dbd_result_set_numfields(result, numcols);

  /* assign types to result */
  while (idx < numcols) {
    int type;
    char *item;
    
    type = find_result_field_types(result_table[idx], conn, statement);
    /*     printf("type: %d<<\n", type); */
    _translate_sqlite3_type(type, &fieldtype, &fieldattribs);

    /* we need the field name without the table name here */
    item = strchr(result_table[idx], (int)'.');
    if (!item) {
      item = result_table[idx];
    }
    else {
      item++;
    }

    _dbd_result_add_field(result, idx, item, fieldtype, fieldattribs);
    idx++;
  }
  
  return result;
}

dbi_result_t *dbd_query_null(dbi_conn_t *conn, const unsigned char *statement, size_t st_length) {
  /* todo: implement using sqlite3_prepare and friends */
  return NULL;
}

int dbd_transaction_begin(dbi_conn_t *conn) {
  if (dbd_query(conn, "BEGIN") == NULL) {
    return 1;
  }
  else {
    return 0;
  }
}

int dbd_transaction_commit(dbi_conn_t *conn) {
  if (dbd_query(conn, "COMMIT") == NULL) {
    return 1;
  }
  else {
    return 0;
  }
}

int dbd_transaction_rollback(dbi_conn_t *conn) {
  if (dbd_query(conn, "ROLLBACK") == NULL) {
    return 1;
  }
  else {
    return 0;
  }
}

int dbd_savepoint(dbi_conn_t *conn, const char *savepoint) {
  char* query;

  if (!savepoint) {
    return 1;
  }

  asprintf(&query, "SAVEPOINT %s", savepoint);

  if (dbd_query(conn, query) == NULL) {
    free(query);
    return 1;
  }
  else {
    free(query);
    return 0;
  }
}

int dbd_rollback_to_savepoint(dbi_conn_t *conn, const char *savepoint) {
  char* query;

  if (!savepoint) {
    return 1;
  }

  asprintf(&query, "ROLLBACK TO SAVEPOINT %s", savepoint);

  if (dbd_query(conn, query) == NULL) {
    free(query);
    return 1;
  }
  else {
    free(query);
    return 0;
  }
}

int dbd_release_savepoint(dbi_conn_t *conn, const char *savepoint) {
  char* query;

  if (!savepoint) {
    return 1;
  }

  asprintf(&query, "RELEASE SAVEPOINT %s", savepoint);

  if (dbd_query(conn, query) == NULL) {
    free(query);
    return 1;
  }
  else {
    free(query);
    return 0;
  }
}

static int find_result_field_types(char* field, dbi_conn_t *conn, const char* statement) {

  /*
    field is the name of the field which we want to know the type of
    conn is the connection
    statement is the query string

    returns the type as a FIELD_TYPE_XXX value

    sqlite3 uses a type system insufficient for libdbi. You don't
    even have to declare the column types if you don't want to.

    However, sqlite3 stores the types as used in the CREATE TABLE
    commands and makes them available through the table_info
    pragma. It is a VERY GOOD idea to declare the types if we want
    the following to work

    The code assumes that table and field names do not exceed a given
    length limit. PostgreSQL uses 32 which is a bit low. Sqlite3 does
    not seem to have fixed limits. We use a default limit of 128 here
    which can be increased in dbd_sqlite3.h if need arises.
  */

  int curr_table_index;
  char* statement_copy = strdup(statement);
  char* item;
  char curr_field[MAX_IDENT_LENGTH];
  char curr_field_lower[MAX_IDENT_LENGTH];
  char curr_table[MAX_IDENT_LENGTH];
  char* tables[MAX_TABLES_IN_QUERY];
  int table_count = 0;
  int type;
  int counter;

  item = strchr(field, (int)'.');
  if ( !item ) {
    strcpy(curr_field, field);
    strcpy(curr_table, "");
  }
  else {
    strcpy(curr_field, item+1);
    strncpy(curr_table, field, item-field);
    curr_table[item-field] = '\0';
  }
  //printf("table = %s\ncolumn = %s\n",curr_table,curr_field);

  /* If curr_table is empty, this means we have to get the
     select tables from the statement (it is possible there is more than one),
     otherwise we have the table for this field.
     It would seem that even if the table is aliased in the statement,
     we still have the original table name.
     sqlite3_get_table returns the tablename and not the alias when returning table.column.
     It probably isn't a good idea to rely on this, but we will.

     I knew it wasn't a good idea :( Select using distinct breaks the above assumptions.
     now we have to resolve the table name as well (if it is given). */

  /* We have to assume that curr_table is an alias.
     This call will resolve the curr_table if given
     */
  //printf("curr_table before getTables = %s\n",curr_table);
  table_count = getTables(tables,0,statement_copy,curr_table);
  //printf("curr_table after getTables = %s\n",curr_table);
  //printf("%s\n",statement_copy);
  //printf("*********TABLELIST************\n");
  //for ( counter = 0 ; counter < table_count ; counter++) {
  //   printf("[%i] %s\n",counter,tables[counter]);
  //}

  // resolve our curr_field to a real column
  char* token;
  char* saveptr;
  char* itemstore;
  int as_flag = 0;
  int function_flag = 0;
  int expression_flag = 0;
  int from_flag = 0;

  token = strtok_r(statement_copy, " ,;", &saveptr);
  while( token != NULL ) {
    //printf("checking %s\n",token);
    // check to see if there is a tablename on this field
    item = strchr(token, (int)'.');
    if ( item != NULL ) {
      // discard the tablename
      token = item+1;
      //printf("checking %s\n",token);
    }
    /* if the from flag is set, we're not interested in any tokens
     * until we hit another select.
     */
    if ( from_flag == 1 ) {
      if( strcmp(token,"(select") == 0 ||
	  strcmp(token,"(SELECT" ) == 0 ||
	  strcmp(token,"select") == 0 ||
	  strcmp(token,"SELECT" ) == 0
	  ) {
	from_flag = 0;
      }
    }
    else {
      if ( as_flag == 0 ) {
	if( strcmp(token,"as") == 0 || strcmp(token,"AS" ) == 0 ) {
	  as_flag = 1;
	}
	else {
	  // reset function and expression flags
	  function_flag = 0;
	  expression_flag = 0;
	  itemstore = token;
	  // check if this is a function
	  item = strchr(itemstore,'(');
	  if ( item != NULL ) {
	    if ( item == itemstore ) {
	      /* I started to try to parse for this scenario, and
		 realized that I was descending into a pit of parsing
		 that would never end.  if it turns out that our
		 curr_field aliases something that comes after this
		 case it will more than likely be wrong and the end
		 result is the field type will resolve to string.

		 so we have to create a rule for creating sql
		 statements with this case and document it so users
		 know how to form their statements and know how to
		 receive their results

		 The rule here is that if you want to enclose your
		 result field in brackets, you must have an alias for
		 it, and the 'as' must be spaced from the closing
		 bracket.  e.g. (<some expression that could be
		 anything really>) as <alias>

		 The result will be obtainable as string, period.

		 if this is the case then this field is enclosed in brackets
		 check for the closing bracket in this token */

	      expression_flag = 1;
	      int opens = 1;
	      while ( opens > 0 && *item != '\0' ) {
		item++;
		if ( *item == '(' )
		  opens++;
		if ( *item == ')' )
		  opens--;
	      }
	      if ( opens > 0 ) {
		// this token doesn't have the complete field
		// get the next token etc...
		int field_complete = 0;
		while ( field_complete == 0 ) {
		  token = strtok_r(NULL, " ,;", &saveptr);
		  item = token;
		  while ( opens > 0 && *item != '\0' ) {
		    if ( *item == '(' )
		      opens++;
		    if ( *item == ')' )
		      opens--;
		    item++;
		  }
		  if ( opens == 0 ) {
		    field_complete = 1;
		  }
		}
	      }
	    } // if item == itemstore

	    else {
	      // we have a function here
	      /*
	       * As for expressions we need a documented rule for
	       * having a function as a result column.  The opening
	       * bracket should be attached to the function name, e.g
	       * count(, not count ( the function must be aliased and
	       * the 'as' must be spaced from the closing bracket. e.g
	       * <function>( <function parameters> ) as <alias>
	       */
	      function_flag = 1;
	      int opens = 1;
	      while ( opens > 0 && *item != '\0' ) {
		item++;
		if ( *item == '(' )
		  opens++;
		if ( *item == ')' )
		  opens--;
	      }
	      if ( opens > 0 ) {
		// this token doesn't have the complete function
		// get the next token etc...
		int function_complete = 0;
		while ( function_complete == 0 ) {
		  token = strtok_r(NULL, " ,;", &saveptr);
		  item = token;
		  while ( opens > 0 && *item != '\0' ) {
		    if ( *item == '(' )
		      opens++;
		    if ( *item == ')' )
		      opens--;
		    item++;
		  }
		  if ( opens == 0 ) {
		    function_complete = 1;
		  }
		}
	      }
	    }
	  }
	  if ( strcmp(token, "from") == 0 || strcmp(token, "FROM") == 0 ) {
	    from_flag = 1;
	  }
	}
      }
      else {
	if ( strcmp(token,curr_field) == 0 ) {
	  // our curr_field is an alias for the field in itemstore
	  // if the expresion flag is set we know that the field type is string
	  if ( expression_flag == 1 ) {
	    free(statement_copy);
	    return FIELD_TYPE_STRING;
	  }
	  if ( function_flag == 1 ) {
	    // itemstore has at least the functionname( in it
	    strcpy(curr_field,itemstore);
	    strcpy(curr_field_lower, curr_field);
	    item = curr_field_lower;
	    while (*item) {
	      *item = (char)tolower((int)*item);
	      item++;
	    }
            //printf("Field is a function - %s\n",curr_field_lower);
	    free(statement_copy);
	    if ( strstr(curr_field_lower,"avg(") ||
		 strstr(curr_field_lower,"sum(") ||
		 strstr(curr_field_lower,"total(") ||
		 strstr(curr_field_lower,"abs(") ||
		 strstr(curr_field_lower,"round(") ) {
	      return FIELD_TYPE_FLOAT;
	    }
	    if ( strstr(curr_field_lower,"julianday(") ||
		 strstr(curr_field_lower,"count(") ||
		 strstr(curr_field_lower,"max(") ||
		 strstr(curr_field_lower,"min(") ||
		 strstr(curr_field_lower,"last_insert_rowid(") ||
		 strstr(curr_field_lower,"length(") ) {
	      return FIELD_TYPE_LONG;
	    }
	    if ( strstr(curr_field_lower,"random(") ) {
	      return FIELD_TYPE_LONGLONG;
	    }
	    if ( strstr(curr_field_lower,"randomblob(") ||
		 strstr(curr_field_lower,"zeroblob(") ||
		 strstr(curr_field_lower,"total(") ||
		 strstr(curr_field_lower,"abs(") ||
		 strstr(curr_field_lower,"round(") ) {
	      return FIELD_TYPE_BLOB;
	    }
	    if ( strstr(curr_field_lower,"date(") ||
		 strstr(curr_field_lower,"time(") ||
		 strstr(curr_field_lower,"datetime(") ||
		 strstr(curr_field_lower,"strftime(") ||
		 strstr(curr_field_lower,"group_concat(") ||
		 strstr(curr_field_lower,"coalesce(") ||
		 strstr(curr_field_lower,"glob(") ||
		 strstr(curr_field_lower,"ifnull(") ||
		 strstr(curr_field_lower,"hex(") ||
		 strstr(curr_field_lower,"like(") ||
		 strstr(curr_field_lower,"lower(") ||
		 strstr(curr_field_lower,"ltrim(") ||
		 strstr(curr_field_lower,"nullif(") ||
		 strstr(curr_field_lower,"quote(") ||
		 strstr(curr_field_lower,"replace(") ||
		 strstr(curr_field_lower,"rtrim(") ||
		 strstr(curr_field_lower,"sqlite_version(") ||
		 strstr(curr_field_lower,"substr(") ||
		 strstr(curr_field_lower,"trim(") ||
		 strstr(curr_field_lower,"typeof(") ||
		 strstr(curr_field_lower,"upper(") ) {
	      return FIELD_TYPE_STRING;
	    }
	    // if we get here we have a function we don't know
	    free(statement_copy);
	    return FIELD_TYPE_STRING;
	  }
	  item = strchr(itemstore,'.');
	  if ( item != NULL ) {
	    strcpy(curr_field,item+1);
	  }
	  else {
	    strcpy(curr_field,itemstore);
	  }
	}
	as_flag = 0;
      }
    }
    token = strtok_r(NULL, " ,;", &saveptr);
  }
  //printf("table = %s\ncolumn = %s\n",curr_table,curr_field);
  free(statement_copy);

  /* now we have to look for the field type in the curr_table
   * If curr_table is empty, we have to search through the table list
   */
  char sql_command[MAX_IDENT_LENGTH+80];
  char **table_result_table;
  char *curr_type = NULL;
  char* errmsg;
  int query_res;
  int table_numrows = 0;
  int table_numcols = 0;
  dbi_error_flag errflag = 0;

  if ( strlen(curr_table) > 0 ) {
    snprintf(sql_command, MAX_IDENT_LENGTH+80, "PRAGMA table_info(%s)", curr_table);
    query_res = sqlite3_get_table((sqlite3*)conn->connection,
				  sql_command,
				  &table_result_table,
				  &table_numrows,
				  &table_numcols,
				  &errmsg);

    if (query_res || !table_numrows) {
      /* The table we have doesn't seem to exist in the database!
       * fallback to to string
       */
      //printf("singletable unknown !\n");
      return FIELD_TYPE_STRING;
    }
    curr_type = get_field_type(&table_result_table, curr_field, table_numrows);
    sqlite3_free_table(table_result_table);
    if (!curr_type) {
      /* the field was not found in the table!
       * fallback to string
       */
      //printf("field not in singletable !\n");
      return FIELD_TYPE_STRING;
    }
  }
  else {
    /* process the table list
     * It should be noted here that we stop searching the tables on the
     * first match of the curr_field from the list of tables
     * The reasoning here is that fields with the same name will
     * probably be the same type.  Obviously, this is a hole.
     */
    if ( table_count > 0 ) {

      for ( counter = 0 ; counter < table_count ; counter++ ) {
/* 	printf("searching table %s\n",tables[counter]); */
	snprintf(sql_command, MAX_IDENT_LENGTH+80, "PRAGMA table_info(%s)", tables[counter]);
	query_res = sqlite3_get_table((sqlite3*)conn->connection,
				      sql_command,
				      &table_result_table,
				      &table_numrows,
				      &table_numcols,
				      &errmsg);

	if (query_res || !table_numrows) {
	  /* This table doesn't seem to exist in the database!
	   * fallback to to string
	   */
/* 	  printf("table not found\n"); */
	  // continue processing
	}
	else {
	  curr_type = get_field_type(&table_result_table, curr_field, table_numrows);
	  sqlite3_free_table(table_result_table);
	  if (!curr_type) {
	    /* the field was not found in this table!
	     * fallback to string
	     */
	    // continue processing
	  }
	}
	if ( curr_type )
	  break;
      }
      if (!curr_type) {
	/* the field was not found in any of the tables!
	 * fallback to string
	 */
/* 	printf("field not in any table !\n"); */
	return FIELD_TYPE_STRING;
      }
    }
    else {
      /* no tables in the statement ?!
       * fallback to string
       */
      printf("no tables in statement !\n");
      return FIELD_TYPE_STRING;
    }
  }

  freeTables(tables, table_count);

  /* convert type to uppercase, reuse item */
  item = curr_type;
  while (*item) {
    *item = (char)toupper((int)*item);
    item++;
  }

  /* the following code tries to support as many of the SQL types as
     possible, including those extensions supported by MySQL and
     PostgreSQL. Some conflicts remain, like the REAL type which is a
     different thing in MySQL and PostgreSQL */

/*      printf("field type before type assignment: %s<<\n", curr_type);  */
  if (strstr(curr_type, "CHAR(") /* note the opening bracket */
      || strstr(curr_type, "CLOB")
      || strstr(curr_type, "TEXT") /* also catches TINYTEXT */
      || strstr(curr_type, "VARCHAR")
      || strstr(curr_type, "ENUM")
      || strstr(curr_type, "SET")
      || strstr(curr_type, "YEAR")) { /* MySQL 2 or 4 digit year (string) */
    type = FIELD_TYPE_STRING;
  }
  else if (strstr(curr_type, "BLOB")
	   || strstr(curr_type, "BYTEA")) {
    type = FIELD_TYPE_BLOB;
  }
  else if (strstr(curr_type, "CHAR") /* this is a 1-byte value */
	   || strstr(curr_type, "TINYINT")
	   || strstr(curr_type, "INT1")) {
    type = FIELD_TYPE_TINY;
  }
  else if (strstr(curr_type, "SMALLINT")
	   || strstr(curr_type, "INT2")) {
    type = FIELD_TYPE_SHORT;
  }
  else if (strstr(curr_type, "MEDIUMINT")) {
    type = FIELD_TYPE_INT24;
  }
  else if (strstr(curr_type, "BIGINT")
	   || strstr(curr_type, "INTEGER PRIMARY KEY") /* BAD BAD HACK */
	   || strstr(curr_type, "INT8")) {
    type = FIELD_TYPE_LONGLONG;
  }
  else if (strstr(curr_type, "INTEGER")
	   || strstr(curr_type, "INT")
	   || strstr(curr_type, "INT4")) {
    type = FIELD_TYPE_LONG;
  }
  else if (strstr(curr_type, "DECIMAL") ||
	   strstr(curr_type, "NUMERIC")) {
    type = FIELD_TYPE_DECIMAL;
  }
  else if (strstr(curr_type, "TIMESTAMP")
	   || strstr(curr_type, "DATETIME")) {
    type = FIELD_TYPE_TIMESTAMP;
  }
  else if (strstr(curr_type, "DATE")) {
    type = FIELD_TYPE_DATE;
  }
  else if (strstr(curr_type, "TIME")) {
    type = FIELD_TYPE_TIME;
  }
  else if (strstr(curr_type, "DOUBLE") /* also catches "double precision" */
	   || strstr(curr_type, "FLOAT8")) {
    type = FIELD_TYPE_DOUBLE;
  }
  else if (strstr(curr_type, "REAL") /* this is PostgreSQL "real", not
					MySQL "real" which is a
					synonym of "double" */
	   || strstr(curr_type, "FLOAT")
	   || strstr(curr_type, "FLOAT4")) {
    type = FIELD_TYPE_FLOAT;
  }
  else {
    type = FIELD_TYPE_STRING; /* most reasonable default */
  }

  free(curr_type);
/*   printf("GET FIELD TYPE RETURNS %d !\n",type); */
  return type;
}

/* Similar to C99 strstr() except ensures that there is
 * white space around needle. */
char *strstr_ws(const char *haystack, const char *needle){
   const char *c = NULL;
   int len;

   len = strlen(needle);

   c = haystack;

   while( (c = strstr(c,needle)) != NULL){
      if(c == haystack) return NULL;
      if( ( *(c-1)  == ' ' || *(c-1) == '\t' || *(c-1) == '\n')
         &&
          ( c[len] == ' '  || c[len] == '\t' || c[len] == '\n'))
           return (char*) c;
   }

   return NULL;
}

static int getTables(char** tables, int index, const char* statement, char* curr_table) {
  //printf("getTables\n");
/*   printf("processing %s\n",statement); */
  char* item;
  char* start;
  int join_flag = 0;
  int as_flag = 0;
  int not_word_flag = 0;

  // the table list will start after 'from' and finish at the last occurrence of
  // 'where' | 'group' | 'having' | 'union' | 'intersect' | 'except' | 'order' | 'limit'

  char* endwords[] = {"where","group","having","union","intersect","except","order","limit"};
  char* nottables[] = {"natural","left","right","full","outer","inner","cross","join","as","on"};

  if ( !(item = strstr_ws(statement, "from")) ) {
    if ( !(item = strstr_ws(statement, "FROM")) )
/*       printf("no from clause\n"); */
      return index;
  }
  item += strlen("from");

  while ( *item != '\0' ) {
/*     printf("begin parsing at %s\n", item); */
    if ( *item == ' '|| *item == '\t' || *item == ',' ) {
      item++;
    }
    else {
/*       printf("word start at %s\n", item); */
      start = item; // mark the start of the word
      if ( *item == '(' ) {
	//printf("sub select\n");
	int opens = 1;
	while ( opens > 0 ) {
	  item++;
	  if ( *item == '(' )
	    opens++;
	  if ( *item == ')' )
	    opens--;
	}
	char substatement[item-start];
	strncpy(substatement,start+1,item-(start+1));
	substatement[item-(start+1)] = '\0';
	index = getTables(tables,index,substatement,curr_table);
	//printf("index is at %d\n",index);
	item ++;
      }
      else {
/* 	printf("actual word starting here: %s\n", item); */
	while ( *item && *item != ',' && *item != ' ' && *item != '\t'
                                      && *item != ')' && *item != ';' ) {
	  item++;
	}
	char word[item-start+1];
	char word_lower[item-start+1];
	strncpy(word,start,item-start);
	word[item-start] = '\0';
	strncpy(word_lower,start,item-start);
	word_lower[item-start] = '\0';
	int i = 0;
	while (word_lower[i]) {
	  word_lower[i] = tolower(word_lower[i]);
	  i++;
	}
	// if word is an end word we can return
	for ( i = 0 ; i < (sizeof(endwords)/sizeof *(endwords)) ; i++ ) {
	  if ( strcmp(endwords[i],word_lower) == 0 ) {
/* 	    printf("end word!\n"); */
	    return index;
	  }
	}
	// if word is not a table we ignore it and continue
	for ( i = 0 ; i < (sizeof(nottables)/sizeof *(nottables)) ; i++ ) {
	  if ( strcmp(nottables[i],word_lower) == 0 ) {
/* 	    printf("not a table: %s\n", word_lower); */
	    // if we encounter join or as we set
	    // a flag because we know what to do next
	    if ( strcmp("join",word_lower) == 0 ) {
	      //printf("join found\n");
	      join_flag = 1;
	    }
	    if ( strcmp("as",word_lower) == 0 ) {
	      //printf("as found\n");
	      as_flag = 1;
	    }
	    not_word_flag = 1;
	    break;
	  }
	}
	if ( not_word_flag == 1) {
/* 	  printf("skipping word\n"); */
	  not_word_flag = 0;
	}
	else {
	  if ( as_flag == 1) {
            // if this word matches what is currently in curr_table
	    // then curr_table is an alias for the last found table
	    //printf("++++ AS FLAG ++++ curr_table = %s , word = %s\n",curr_table,word);
	    if ( strcmp(curr_table,word) == 0 ) {
/* 	      printf("Setting curr_table\n",curr_table,word); */
	      strcpy(curr_table,tables[index - 1]);
            }
	    as_flag = 0;
	    //printf("++++ AS FLAG ++++ curr_table set to %s\n",curr_table);
	  }
	  else {
/* 	    printf("found table!\n"); */
	    // if we get here the word is a table name
	    tables[index] = strdup(word);
/* 	    printf("table index %d = %s\n",index,tables[index]); */
	    index++;
	    if ( join_flag == 1) {
	      //printf("skipping after joined table\n");
	      // we can ignore everything until the next ',' or 'join'
	      join_flag = 0;
	      int skip_flag = 1;
	      while ( skip_flag == 1 ) {
		if ( *item == ' '|| *item == '\t' ) {
		  item++;
		}
		else {
		  start = item; // mark the start of the word
		  // this will skip over the using (id-list)
		  if ( *item == '(' ) {
		    //printf("skip over the using (id-list)\n");
		    int opens = 1;
		    while ( opens > 0 ) {
		      item++;
		      if ( *item == '(' )
			opens++;
		      if ( *item == ')' )
			opens--;
		    }
		  }
		  while ( *item && *item != ','  && *item != ' '
                                && *item != '\t' && *item != '(') {
		    item++;
		  }
		  if ( *item == '\0' ) {
/* 		    printf("returning %d, *item went to NULL1\n",index); */
		    return index;
		  }
		  if ( *item == ',') {
		    //printf("stop skip after comma\n");
		    // we have come to a comma, so we can stop skipping
		    skip_flag = 0;
		    break;
		  }

		  char word_lower[item-start+1];
		  strncpy(word_lower,start,item-start);
		  word_lower[item-start] = '\0';
		  int i = 0;
		  while (word_lower[i]) {
		    word_lower[i] = tolower(word_lower[i]);
		    i++;
		  }
		  if ( strcmp("join",word_lower) == 0 ) {
		    //printf("stop skip after join found\n");
		    // we have found the next join, stop skipping
		    join_flag = 1;
		    skip_flag = 0;
		    break;
		  }
                  for ( i = 0 ; i < (sizeof(endwords)/sizeof *(endwords)) ; i++ ) {
                     if ( strcmp(endwords[i],word_lower) == 0 ) {
                        /* printf("end word!\n"); */
                        return index;
                    }
                  }
		}
	      }
	    } // if join_flag
	  } // if as_flag else
	} // if not_word_flag else
	if ( *item == '\0' ) {
/* 	  printf("returning %d",index); */
	  return index;
	}
        item++;
      } // if *item == '(' else
    } // if *item == ' '|| *item == '\t' || *item == ',' else
  } // while
/*   printf("returning %d\n",index); */
  return index;
}

static void freeTables(char** tables, int table_count) {
  int counter;

  for ( counter = 0 ; counter < table_count ; counter++ ) {
    if (*(tables[counter])) {
      free(tables[counter]);
    }
  }
}

static char* get_field_type(char*** ptr_result_table, const char* curr_field_name, int numrows) {
  /*
    ptr_table is a ptr to a string array as returned by the
    sqlite3_get_table() function called with the table_info pragma.
    The array is 6 cols wide and contains one row for each field in
    the table. The first row contains the column names, but it is not
    included in numrows, so the real data start at [6].  The columns
    are: Number|column_name|type|may_be_null|default_value|pk?  Thus,
    the column names are in [6+6*i], and the corresponding type of the
    result is in [7+6*i]. pk is set to 1 if the column is part of a
    primary key. An autoincrementing column is identified by type
    INTEGER and by being the only column with pk set to 1 in this
    table
    curr_field_name is a ptr to a string holding the field name
    numrows is the number of rows in the string array

    returns the field type as an allocated string or NULL
    if an error occurred
  */
  char* curr_type = NULL;
  int i;
  int pk_count = 0;

  for (i=6;i<=numrows*6;i+=6) {
    if (!strcmp((*ptr_result_table)[i+1], curr_field_name)) {
      curr_type = strdup((*ptr_result_table)[i+2]);
    }
    if (strcmp((*ptr_result_table)[i+5], "1") == 0) {
      pk_count++;
    }
  }
/*   printf("curr_type of %s went to %s<<\n", curr_field_name, curr_type); */

  /* sqlite has the bad habit to turn INTEGER PRIMARY KEY columns into
     INTEGER columns when using the table_info pragma. If a column is
     an INTEGER and the only column with pk set to "1", turn it back
     to INTEGER PRIMARY KEY */

  if (curr_type) {
    if (pk_count == 1
	&& (strcmp(curr_type, "INTEGER") == 0
	    || strcmp(curr_type, "integer") == 0)) {
      free(curr_type);
      curr_type = strdup("INTEGER PRIMARY KEY");
    }
  }
  return curr_type;
}

const char *dbd_select_db(dbi_conn_t *conn, const char *db) {
  /*
    sqlite3 does not separate connecting to a database server and using
    or opening a database. If we want to switch to a different database,
    we have to drop the current connection and create a new one
    instead, using the new database.
  */

  if (!db || !*db) {
    return NULL;
  }

  if (conn->connection) {
    sqlite3_close((sqlite3 *)conn->connection);
  }

  if (_real_dbd_connect(conn, db)) {
    return NULL;
  }

  return db;
}

int dbd_geterror(dbi_conn_t *conn, int *err_no, char **errstr) {
  /* put error number into err_no, error string into errstr
   * return 0 if error, 1 if err_no filled, 2 if errstr filled, 3 if both err_no and errstr filled */

  *err_no = sqlite3_errcode((sqlite3 *)conn->connection);
  *errstr = strdup((char*)sqlite3_errmsg((sqlite3 *)conn->connection));
  return 3;
}


unsigned long long dbd_get_seq_last(dbi_conn_t *conn, const char *sequence) {
  return (unsigned long long)sqlite3_last_insert_rowid((sqlite3*)conn->connection);
}

unsigned long long dbd_get_seq_next(dbi_conn_t *conn, const char *sequence) {
  _dbd_internal_error_handler(conn, NULL, DBI_ERROR_UNSUPPORTED);
  return 0;
}

int dbd_ping(dbi_conn_t *conn) {

  if (dbd_query(conn, "SELECT 1") == NULL) {
    return 0;
  }
  else {
    return 1;
  }
}

/* CORE SQLITE3 DATA FETCHING STUFF */

static void _translate_sqlite3_type(enum enum_field_types fieldtype, unsigned short *type, unsigned int *attribs) {
  unsigned int _type = 0;
  unsigned int _attribs = 0;
/*   printf("fieldtype:%d<<\n", fieldtype); */
  switch (fieldtype) {
  case FIELD_TYPE_TINY:
    _type = DBI_TYPE_INTEGER;
    _attribs |= DBI_INTEGER_SIZE1;
    break;
  case FIELD_TYPE_YEAR:
    _attribs |= DBI_INTEGER_UNSIGNED;
  case FIELD_TYPE_SHORT:
    _type = DBI_TYPE_INTEGER;
    _attribs |= DBI_INTEGER_SIZE2;
    break;
  case FIELD_TYPE_INT24:
    _type = DBI_TYPE_INTEGER;
    _attribs |= DBI_INTEGER_SIZE3;
    break;
  case FIELD_TYPE_LONG:
    _type = DBI_TYPE_INTEGER;
    _attribs |= DBI_INTEGER_SIZE4;
    break;
  case FIELD_TYPE_LONGLONG:
    _type = DBI_TYPE_INTEGER;
    _attribs |= DBI_INTEGER_SIZE8;
    break;
			
  case FIELD_TYPE_FLOAT:
    _type = DBI_TYPE_DECIMAL;
    _attribs |= DBI_DECIMAL_SIZE4;
    break;
  case FIELD_TYPE_DOUBLE:
    _type = DBI_TYPE_DECIMAL;
    _attribs |= DBI_DECIMAL_SIZE8;
    break;
			
  case FIELD_TYPE_DATE: /* TODO parse n stuph to native DBI unixtime type. for now, string */
    _type = DBI_TYPE_DATETIME;
    _attribs |= DBI_DATETIME_DATE;
    break;
  case FIELD_TYPE_TIME:
    _type = DBI_TYPE_DATETIME;
    _attribs |= DBI_DATETIME_TIME;
    break;
  case FIELD_TYPE_DATETIME:
  case FIELD_TYPE_TIMESTAMP:
    _type = DBI_TYPE_DATETIME;
    _attribs |= DBI_DATETIME_DATE;
    _attribs |= DBI_DATETIME_TIME;
    break;
			
  case FIELD_TYPE_DECIMAL: /* decimal is actually a string, has arbitrary precision, no floating point rounding */
  case FIELD_TYPE_ENUM:
  case FIELD_TYPE_SET:
  case FIELD_TYPE_VAR_STRING:
  case FIELD_TYPE_STRING:
    _type = DBI_TYPE_STRING;
    break;
			
  case FIELD_TYPE_TINY_BLOB:
  case FIELD_TYPE_MEDIUM_BLOB:
  case FIELD_TYPE_LONG_BLOB:
  case FIELD_TYPE_BLOB:
    _type = DBI_TYPE_BINARY;
    break;
			
  default:
    _type = DBI_TYPE_STRING;
    break;
  }
	
  *type = _type;
  *attribs = _attribs;
}


static void _get_row_data(dbi_result_t *result, dbi_row_t *row, unsigned long long rowidx) {
  char **result_table = result->result_handle;
  
  unsigned int curfield = 0;
  char *raw = NULL;
  unsigned int sizeattrib;
  dbi_data_t *data;

  while (curfield < result->numfields) {
    /* rowidx appears to be 0-based, but the first row always contains
       the column names */
    raw = result_table[curfield + ((rowidx+1)*result->numfields)];
    data = &row->field_values[curfield];
    
    row->field_sizes[curfield] = 0;
    /* this will be set to the string size later on if the field is indeed a string */

    if (raw == NULL) { /* no data available */
      _set_field_flag( row, curfield, DBI_VALUE_NULL, 1);
      curfield++;
      continue;
    }
    
    switch (result->field_types[curfield]) {
    case DBI_TYPE_INTEGER:
      sizeattrib = _isolate_attrib(result->field_attribs[curfield], DBI_INTEGER_SIZE1, DBI_INTEGER_SIZE8);
      switch (sizeattrib) {
      case DBI_INTEGER_SIZE1:
	data->d_char = (char) atol(raw); break;
      case DBI_INTEGER_SIZE2:
	data->d_short = (short) atol(raw); break;
      case DBI_INTEGER_SIZE3:
      case DBI_INTEGER_SIZE4:
/* 	printf("returning a long via data->d_long\n"); */
	data->d_long = (int) atol(raw); break;
      case DBI_INTEGER_SIZE8:
/* 	printf("returning a long long via data->d_longlong\n"); */
	data->d_longlong = (long long) atoll(raw); break; /* hah, wonder if that'll work */
      default:
	break;
      }
      break;
    case DBI_TYPE_DECIMAL:
      sizeattrib = _isolate_attrib(result->field_attribs[curfield], DBI_DECIMAL_SIZE4, DBI_DECIMAL_SIZE8);
      switch (sizeattrib) {
      case DBI_DECIMAL_SIZE4:
	data->d_float = (float) strtod(raw, NULL); break;
      case DBI_DECIMAL_SIZE8:
	data->d_double = (double) strtod(raw, NULL); break;
      default:
	break;
      }
      break;
    case DBI_TYPE_STRING:
      data->d_string = strdup(raw);
      row->field_sizes[curfield] = strlen(raw);
      break;
    case DBI_TYPE_BINARY:
      data->d_string = strdup(raw);
      row->field_sizes[curfield] = _dbd_decode_binary(data->d_string, data->d_string);
      break;
    case DBI_TYPE_DATETIME:
      sizeattrib = _isolate_attrib(result->field_attribs[curfield], DBI_DATETIME_DATE, DBI_DATETIME_TIME);
      data->d_datetime = _dbd_parse_datetime(raw, sizeattrib);
      break;
      
    default:
      data->d_string = strdup(raw);
      row->field_sizes[curfield] = strlen(raw);
      break;
    }
    
    curfield++;
  }
}

/* this function is stolen from MySQL and somewhat simplified for our
   needs */
/* it appears to return 0 on a match, 1 if no match is found, and -1
   in some odd cases */

#define wild_many (char)'%'
#define wild_one (char)'_'
#define INC_PTR(A,B) A++

static int wild_case_compare(const char *str,const char *str_end,
		      const char *wildstr,const char *wildend,
		      char escape) {
  int result= -1;				// Not found, using wildcards
  unsigned char cmp;

  while (wildstr != wildend) {
    while (*wildstr != wild_many && *wildstr != wild_one) {
      if (*wildstr == escape && wildstr+1 != wildend) {
	wildstr++;
      }
      if (str == str_end || *wildstr++ != *str++) {
	return(1);				// No match
      }
      if (wildstr == wildend) {
	return (str != str_end);		// Match if both are at end
      }
      result=1;					// Found an anchor char
    }
    if (*wildstr == wild_one)	{
      do {
	if (str == str_end) {			// Skip one char if possible
	  return (result);
	}
	INC_PTR(str,str_end);
      } while (++wildstr < wildend && *wildstr == wild_one);
      if (wildstr == wildend) {
	break;
      }
    }

    if (*wildstr == wild_many) {		// Found wild_many
      wildstr++;
      /* Remove any '%' and '_' from the wild search string */
      for ( ; wildstr != wildend ; wildstr++) {
	if (*wildstr == wild_many) {
	  continue;
	}
	if (*wildstr == wild_one) {
	  if (str == str_end) {
	    return (-1);
	  }
	  INC_PTR(str,str_end);
	  continue;
	}
	break;					// Not a wild character
      }
      if (wildstr == wildend) {
	return(0);				// Ok if wild_many is last
      }
      if (str == str_end) {
	return -1;
      }

      if ((cmp= *wildstr) == escape && wildstr+1 != wildend) {
	cmp= *++wildstr;
      }
      INC_PTR(wildstr,wildend);			// This is compared trough cmp
      /*        cmp=likeconv(cmp);    */
      do {
	while (str != str_end && *str != cmp) {
	  str++;
	}
	if (str++ == str_end) {
	  return (-1);
	}

	{
	  int tmp=wild_case_compare(str,str_end,wildstr,wildend,escape);
	  if (tmp <= 0) {
	    return (tmp);
	  }
	}
      } while (str != str_end && wildstr[0] != wild_many);
      return(-1);
    }
  }
  return (str != str_end ? 1 : 0);
}

/* this function is stolen from MySQL. The quoting was changed to the
   SQL standard, i.e. single and double quotes are escaped by doubling,
   not by a backslash. Newlines and carriage returns are left alone */
static size_t sqlite3_escape_string(char *to, const char *from, size_t length)
{
  const char *to_start=to;
  const char *end;

  for (end=from+length; from != end ; from++)
    {
      switch (*from) {
      case 0:				/* Must be escaped for 'mysql' */
	*to++= '\\';
	*to++= '0';
	break;
      case '\'':
	*to++= '\''; /* double single quote */
	*to++= '\'';
	break;
      case '\032':			/* This gives problems on Win32 */
	*to++= '\\';
	*to++= 'Z';
	break;
      default:
	*to++= *from;
      }
    }
  *to=0;
  return (size_t) (to-to_start);
}

/* this is a convenience function to retrieve the database directory */
static const char* _conn_get_dbdir(dbi_conn_t *conn) {
  const char* dbdir;

  dbdir = dbi_conn_get_option(conn, "sqlite3_dbdir");
	
  if (!dbdir) {
    /* use default directory instead */
    dbdir = default_dbdir;
  }

  return dbdir;
}