File: dbd_sqlite.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 (1432 lines) | stat: -rw-r--r-- 40,963 bytes parent folder | download | duplicates (6)
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
/*
 * libdbi-drivers - 3rd-party 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_sqlite.c: SQLite database support (using libsqlite)
 * Copyright (C) 2002-2007, Markus Hoenicka <mhoenicka@users.sourceforge.net>
 * http://libdbi-drivers.sourceforge.net
 * 
 * $Id: dbd_sqlite.c,v 1.55 2013/01/09 21:30:20 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/sqlite */

#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 <sqlite.h>
#include "dbd_sqlite.h"

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

static const char *custom_functions[] = SQLITE_CUSTOM_FUNCTIONS;
static const char *reserved_words[] = SQLITE_RESERVED_WORDS;
static const char default_dbdir[] = DBDIR;

/* the encoding strings */
static const char sqlite_encoding_UTF8[] = "UTF-8";
/* the following is an assumption that is most likely correct */
static const char sqlite_encoding_ISO8859[] = "ISO-8859-1";

/* forward declarations */
int _real_dbd_connect(dbi_conn_t *conn, const char* database);
void _translate_sqlite_type(enum enum_field_types fieldtype, unsigned short *type, unsigned int *attribs);
void _get_row_data(dbi_result_t *result, dbi_row_t *row, unsigned int rowidx);
int find_result_field_types(char* field, dbi_conn_t *conn, const char* statement);
char* get_field_type(const char* statement, const char* curr_field_name);
static size_t sqlite_escape_string(char *to, const char *from, size_t length);
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, "");
}

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 */
  sqlite *sqcon;
  char* sq_errmsg = NULL;
  char* db_fullpath = NULL;

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

  const char *dbname;
  const char *dbdir;

  int timeout;

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

  /* sqlite 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;
  }

  /* sqlite specific options */
  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 (dbdir && *dbdir) {
    strcpy(db_fullpath, dbdir);
  }
  if (db_fullpath[strlen(db_fullpath)-1] != *dirsep) {
    strcat(db_fullpath, dirsep);
  }
  if (dbname && *dbname) {
    strcat(db_fullpath, dbname);
  }

/*   fprintf(stderr, "try to open %s<<\n", db_fullpath); */
  sqcon = sqlite_open(db_fullpath, 0 /* param not used */, &sq_errmsg);
  free(db_fullpath);
	
  if (!sqcon) {
    /* sqlite 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, DBI_ERROR_CLIENT);
      free(sq_errmsg);
    }
    else {
      _dbd_internal_error_handler(conn, "could not open database", 0);
    }
    return -1;
  }
  else {
    conn->connection = (void *)sqcon;
    if (dbname) {
      conn->current_db = strdup(dbname);
    }
  }

  /* set the SQLite timeout to timeout milliseconds. The older
     SQLite-specific setting takes precedence over the generic timeout
     option for backwards compatibility */
  timeout = dbi_conn_get_option_numeric(conn, "sqlite_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;
    }
  }

  sqlite_busy_timeout(sqcon, timeout);	
  
  return 0;
}

int dbd_disconnect(dbi_conn_t *conn) {
  if (conn->connection) {
    sqlite_close((sqlite *)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) {
    sqlite_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){
  /* sqlite does not use sockets, so we'll always return 0 */
  return (int)0;
}

const char *dbd_get_encoding(dbi_conn_t *conn){
  /* encoding is a compile-time option with the sqlite
     library. Instead of using the sqlite-provided string, we use the
     iana.org names */
  if (!strcmp(sqlite_encoding, "UTF-8")) {
    return sqlite_encoding_UTF8;
  }
  else {
    return sqlite_encoding_ISO8859;
  }
}

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] = "";
  int retval;
  size_t entry_size;
  DIR *dp;
  struct dirent *entry;
  struct dirent *result;
  struct stat statbuf;
  dbi_result rs;

  /* sqlite 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 sqlite 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 (sqlite 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)) {
      /* we do a magic number check here to make sure we
	 get only databases, not random files in the current directory.
	 SQLite databases start with the string:
	 
	 ** This file contains an SQLite 2.1 database **

      */
      FILE* fp;

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

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

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

	if (strcmp(magic_text, "** This file contains an SQLite 2.1 database **")) {
	  /* 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) {
	    retval = sqlite_exec_printf((sqlite*)(conn->connection), "INSERT INTO libdbi_databases VALUES ('%s')", NULL, NULL, &sq_errmsg, entry->d_name);
	    if (sq_errmsg) {
	      _dbd_internal_error_handler(conn, sq_errmsg, retval);
	      free(sq_errmsg);
	      break;
	    }
	  }
	}
	else {
	  retval = sqlite_exec_printf((sqlite*)(conn->connection), "INSERT INTO libdbi_databases  VALUES ('%s')", NULL, NULL, &sq_errmsg, entry->d_name);
	  
	  if (sq_errmsg) {
	    _dbd_internal_error_handler(conn, sq_errmsg, 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("sqlite", 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, "sqlite_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"); */

  /* sqlite does not support the SHOW command, so we have to extract the
     information from the accessory sqlite_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 sqlite_master has run\n"); */
  if (dbi_result) {
    while (dbi_result_next_row(dbi_result)) {
      retval = sqlite_exec_printf((sqlite*)(conn->connection), "INSERT INTO libdbi_tablenames VALUES ('%s')", NULL, NULL, NULL /* no error messages please */, dbi_result_get_string(dbi_result, "name"));
    }
    dbi_result_free(dbi_result);
  }
  else {
    dbi_conn_error(tempconn, (const char**)&sq_errmsg);
  }

  /* sqlite_close((sqlite*)(tempconn->connection)); */
  dbi_conn_close(tempconn);

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

dbi_result_t *dbd_query_null(dbi_conn_t *conn, const unsigned char *statement, size_t st_length) {
	return NULL;
}

size_t dbd_quote_string(dbi_driver_t *driver, const char *orig, char *dest) {
  /* foo's -> 'foo\'s' */
  size_t len;
	
  strcpy(dest, "'");
  len = sqlite_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 = sqlite_get_table((sqlite*)conn->connection,
			       statement,
			       &result_table,
			       &numrows,
			       &numcols,
			       &errmsg);

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

  /* assign types to result */
  while (idx < numcols) {
/*     printf("idx: %d<< numcols:%d\n", idx, numcols); */
    int type;
    char *item;
    
    type = find_result_field_types(result_table[idx], conn, statement);
/*     printf("type: %d<<\n", type); */
    _translate_sqlite_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;
}

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;
  }
}

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

     sqlite is typeless (with one exception) on purpose. You can
     declare types with the CREATE TABLE statement, but they serve
     descriptive purposes only. Therefore libsqlite does not provide
     any helper function to find out about the type of a given field.

     However, sqlite stores the CREATE TABLE commands as a string in
     an internal table, so we can try to look up the types in these
     strings. 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. SQLite does
     not seem to have fixed limits. We use a default limit of 128 here
     which can be increased in dbd_sqlite.h if need arises.
   */

  char* item;
  char* table;
  char* my_statement = NULL;
  char curr_table[MAX_IDENT_LENGTH] = "";
  char curr_field_name[MAX_IDENT_LENGTH];
  char curr_field_name_up[MAX_IDENT_LENGTH];
  char **table_result_table;
  char *curr_type;
  char* errmsg;
  int query_res;
  int table_numrows = 0; /* int seems ok as sqlite does not use longlongs */
  int table_numcols = 0;
  int type;
  dbi_error_flag errflag = 0;

  /* check whether field contains the table info. It does if the
   notation "table.field" is used */
  item = strchr(field, (int)'.');
  if (!item) {
    /* the field does not contain the table info. However, the latter
     may be available in the original statement, so let's look
     there first*/
    my_statement = strdup(statement);
    if (!my_statement) {
      return 0;
    }

    if (!(table = strstr(my_statement, " from "))) {
      table = strstr(my_statement, " FROM ");
    }

    if (!table) {
/*       fprintf(stderr, "no from keyword found\n"); */
      return 0;
    }

    *table = '\0'; /* terminate string, leaves only field names */

    if ((table = strstr(my_statement, field)) != NULL
	&& table != my_statement
	&& *(table-1) == '.') {
      /* the field name is there, isolate preceding table */
      *(table-1) = '\0';

      while (table > my_statement
	     && *table != ' '
	     && *table != ',') {
	table--;
      }

      if (*table == ' '
	  || *table == ',') {
	table++;
      }

      /* table should now point to the table name */
      strcpy(curr_table, table);
    }
    else {
      /* as a last resort assume that all fields are from the same table
	 which we have to extract from the statement that created the
	 result */

      /* To get started, we use the first item after 'from' or 'FROM'
	 as the table name (we currently ignore pathologic cases like
	 'FroM' or 'froM'. We could uppercase a copy but we need the
	 table name as is, so it is going to get complex) */
      if (!(table = strstr(statement, " from "))) {
	table = strstr(statement, " FROM ");
      }
      
      if (!table) {
	/*       fprintf(stderr, "no from keyword found\n"); */
	return 0;
      }
      
      /* set ptr to possible start of item after 'from' */
      table += 6;
      
      /* skip spaces */
      while (*table == ' ') {
	table++;
      }

      /* table now points to the table name; find the end of table */
      item = table;
      while (*item && *item != ' ' && *item != ',' && *item != ';') {
	item++;
      }
      strncpy(curr_table, table, item-table);
      curr_table[item-table] = '\0'; /* terminate just in case */

      /* for obvious reasons, the internal tables do not contain the
	 commands how they were created themselves. We have to use known
	 values for the field types */
      if (!strcmp(curr_table, "sqlite_master") ||
	  !strcmp(curr_table, "sqlite_temp_master")) {
	if (!strcmp(field, "rootpage")) {
	  return FIELD_TYPE_LONG;
	}
	else {
	  return FIELD_TYPE_STRING;
	}
      }
    }
    free(my_statement);
    strcpy(curr_field_name, field);
  }
  else {   /* each field contains table info */
    strncpy(curr_table, field, item-field);
    curr_table[item-field] = '\0';
    strcpy(curr_field_name, item+1);
  }

/*   printf("curr_table went to %s<<\ncurr_field_name went to %s<<\n", curr_table, curr_field_name); */
  /* check for known functions which may appear here instead
     of field names. There is some overlap, i.e. some function work
     both on strings and numbers. These cases would have to be
     analyzed by checking the arguments */
  /* ToDo: find the matching closing bracket and submit this function
     call to the builtin typeof() SQL function. This should return a
     distinction between text and numeric types. However, the size and
     subtype of a numeric column can't be deduced as easily */
  strcpy(curr_field_name_up, curr_field_name);

  /* uppercase string, reuse item */
  item = curr_field_name_up;
  while (*item) {
    *item = (char)toupper((int)*item);
    item++;
  }

  if (strstr(curr_field_name_up, "ABS(")
      || strstr(curr_field_name_up, "LAST_INSERT_ROWID(")
      || strstr(curr_field_name_up, "LENGTH(")
      || strstr(curr_field_name_up, "MAX(")
      || strstr(curr_field_name_up, "MIN(")
      || strstr(curr_field_name_up, "RANDOM(*)")
      || strstr(curr_field_name_up, "ROUND(")
      || strstr(curr_field_name_up, "AVG(")
      || strstr(curr_field_name_up, "COUNT(")
      || strstr(curr_field_name_up, "SUM(")) {
    return FIELD_TYPE_LONG;
  }
  else if (strstr(curr_field_name_up, "COALESCE(")
	   || strstr(curr_field_name_up, "GLOB(")
	   || strstr(curr_field_name_up, "LIKE(")
	   || strstr(curr_field_name_up, "LOWER(")
	   || strstr(curr_field_name_up, "SUBSTR(")
	   || strstr(curr_field_name_up, "UPPER(")) {
    return FIELD_TYPE_STRING;
  }
      

  /* curr_table now contains the name of the table that the field
     belongs to. curr_field_name contains the name of the field.
     Look up the field type in the sqlite_master table */

  /* first try in the table containing permanent tables */
  query_res = sqlite_get_table_printf((sqlite*)conn->connection,
				      "SELECT tbl_name, sql FROM sqlite_master where tbl_name='%s'",
				      &table_result_table,
				      &table_numrows,
				      &table_numcols,
				      &errmsg,
				      curr_table);

  if (query_res || !table_numrows) {
	if(table_result_table != NULL) {
	  sqlite_free_table(table_result_table);
	}
    /* now try in the table ocntaining temporary tables */
    query_res = sqlite_get_table_printf((sqlite*)conn->connection,
					"SELECT tbl_name, sql FROM sqlite_temp_master where tbl_name='%s'",
					&table_result_table,
					&table_numrows,
					&table_numcols,
					&errmsg,
					curr_table);
    
    if (query_res || !table_numrows) {
      _dbd_internal_error_handler(conn, errmsg, query_res);
      if (table_result_table != NULL) {
	sqlite_free_table(table_result_table);
      }
/*       printf("field not found\n"); */
      return 0;
    }
  }
  

  /* table_result_table[3] now contains the sql statement that created
     the table containing the current field */
  /*  parse the sql statement to find the type of the current field */
/*   printf("table_result_table[3]=%s<<\ncurr_field_name=%s<<\n", table_result_table[3], curr_field_name); */

  /* curr_type will point to an allocated string */
  curr_type = get_field_type(table_result_table[3], curr_field_name);

  /* free memory */
  sqlite_free_table(table_result_table);

  if (!curr_type) {
/*     printf("out of memory\n"); */
    return 0;
  }
  
  /* 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: %s<<\n", curr_type); */
  if (strstr(curr_type, "BLOB")
      || strstr(curr_type, "BYTEA")) {
    type = FIELD_TYPE_BLOB;
  }
  else 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, "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, "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("type went to %d<<\n", type); */
  return type;
}

char* get_field_type(const char* statement, const char* curr_field_name) {
  /*
    statement is a ptr to a string with the "create table" statement
    curr_field_name is a ptr to a string containing the name of the
    field we need the type of.

    returns the field type as an allocated string or NULL
    if an error occurred
  */
  char *item;
  char* saveptr;
  char *my_statement;
  char *field_name;
  char *end_field_name;
  char *type;
  char *curr_type = NULL;

  /* make a copy that we may modify */
  if ((my_statement = strdup(statement)) == NULL) {
    return NULL;
  }

  /* the field list of the "create table" statement starts after the 
     first opening bracket */
  item = strchr(my_statement, '(');
  if (!item) {
    free(my_statement);
    return NULL;
  }

  /* make item point to the first item in the comma-separated list */
  item++;

  /* now tokenize the field list */
  for (item = strtok_r(item, ",", &saveptr); item; item = strtok_r(NULL, ",", &saveptr)) {
/*     printf("item:%s<<\n", item); */

    /* skip leading whitespace */
    field_name = item;
    while ((*field_name == ' ') || (*field_name == '\n')) {
      field_name++;
    }

    /* terminate field name */
    end_field_name = field_name+1;
    while (*end_field_name != ' ') {
      end_field_name++;
    }
    *end_field_name = '\0';

/*     printf("field_name:%s<<\n", field_name); */

    /* analyze type if the field name is the one we want to check */
    if (!strcmp(field_name, curr_field_name)) {
      /* skip leading whitespace */
      type = end_field_name + 1;
      while (*type == ' ') {
	type++;
      }

      curr_type = strdup(type);
/*       printf("curr_type:%s<<\n"); */
      break;
    }
  }

  free(my_statement);
  return curr_type;
}

const char *dbd_select_db(dbi_conn_t *conn, const char *db) {
  /*
    sqlite 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) {
    sqlite_close((sqlite *)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 */
  int result = 0;

  if (conn->error_number) {
    *err_no = conn->error_number;
    result++;
  }
  if (conn->error_message) {
    *errstr = strdup(conn->error_message);
    result += 2;
  }
  return result;
}


unsigned long long dbd_get_seq_last(dbi_conn_t *conn, const char *sequence) {
  return (unsigned long long)sqlite_last_insert_rowid((sqlite*)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 SQLITE DATA FETCHING STUFF */

void _translate_sqlite_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;
}


void _get_row_data(dbi_result_t *result, dbi_row_t *row, unsigned int 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:
	data->d_long = (int) atol(raw); break;
      case DBI_INTEGER_SIZE8:
	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++

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 sqlite_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, "sqlite_dbdir");
	
  if (!dbdir) {
    /* use default directory instead */
    dbdir = default_dbdir;
  }

  return dbdir;
}