File: pgtclSqlite.c

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

#include <tcl.h>

#include "pgtclCmds.h"
#include "pgtclId.h"

#include <sqlite3.h>

#define LAPPEND_STRING(i, o, s) Tcl_ListObjAppendElement((i), (o), Tcl_NewStringObj((s), -1));

// From tclsqlite.c, part 1 of the hack, sqlite3 conveniently guarantees that the first element in
// the userdata for an sqlite proc is the sqlite3 database.
//
// I have verified with Richard Hipp at the Tcl2017 conference that this behaviour is intentional
// and stable. -- PDS 2018
/*
** There is one instance of this structure for each SQLite database
** that has been opened by the SQLite TCL interface.
**
** If this module is built with SQLITE_TEST defined (to create the SQLite
** testfixture executable), then it may be configured to use either
** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
*/
struct SqliteDb {
  sqlite3 *db;               /* The "real" database structure. MUST BE FIRST */
  // other stuff we don't look at, but probably should maybe use to validate...
};

//
// Prepare a statement, and finalize it first if it's already prepared
//
int
Pg_sqlite_prepare(Tcl_Interp *interp, sqlite3 *sqlite_db, char *sql, sqlite3_stmt **statement_ptr)
{
	if(*statement_ptr) {
		sqlite3_finalize(*statement_ptr);
		*statement_ptr = NULL;
	}

	if(sqlite3_prepare_v2(sqlite_db, sql, -1, statement_ptr, NULL) != SQLITE_OK) {
		Tcl_AppendResult(interp, sqlite3_errmsg(sqlite_db), (char *)NULL);
		return TCL_ERROR;
	}

	if(!*statement_ptr) {
		Tcl_AppendResult(interp, "Empty SQL statement provided.", (char *)NULL);
		return TCL_ERROR;
	}

	return TCL_OK;
}

int
Pg_sqlite_begin(Tcl_Interp *interp, sqlite3 *sqlite_db)
{
	char *errMsg;
	if(sqlite3_exec(sqlite_db, "begin;", NULL, NULL, &errMsg) != SQLITE_OK) {
                Tcl_AppendResult(interp, errMsg, " when beginning a transaction", (char *)NULL);
                return TCL_ERROR;
        }
	return TCL_OK;
}

int
Pg_sqlite_commit(Tcl_Interp *interp, sqlite3 *sqlite_db)
{
	char *errMsg;
	if(sqlite3_exec(sqlite_db, "commit;", NULL, NULL, &errMsg) != SQLITE_OK) {
                Tcl_AppendResult(interp, errMsg, " when comitting a transaction", (char *)NULL);
                return TCL_ERROR;
        }
	return TCL_OK;
}

int
Pg_sqlite_wal_checkpoint(Tcl_Interp *interp, sqlite3 *sqlite_db)
{
	char *errMsg;
	if(sqlite3_exec(sqlite_db, "PRAGMA wal_checkpoint(PASSIVE);", NULL, NULL, &errMsg) != SQLITE_OK) {
                Tcl_AppendResult(interp, errMsg, " when doing a WAL checkpoint", (char *)NULL);
                return TCL_ERROR;
        }
	return TCL_OK;
}

//
// Commit a statement, checkpoint, and prepare it again
//
int
Pg_sqlite_recommit(Tcl_Interp *interp, sqlite3 *sqlite_db, char *sql, sqlite3_stmt **statement_ptr)
{
	if(Pg_sqlite_commit(interp, sqlite_db) != TCL_OK)
		return TCL_ERROR;

	if(Pg_sqlite_wal_checkpoint(interp, sqlite_db) != TCL_OK)
		return TCL_ERROR;

	if(Pg_sqlite_begin(interp, sqlite_db) != TCL_OK)
		return TCL_ERROR;

	return TCL_OK;
}

//
// Exec a Sqlite3 statement embedded in a Tcl object.
//
int Pg_sqlite_execObj(Tcl_Interp *interp, sqlite3 *sqlite_db, Tcl_Obj *obj)
{
	sqlite3_stmt *statement = NULL;
	int           result = TCL_OK;

	if(Pg_sqlite_prepare(interp, sqlite_db, Tcl_GetString(obj), &statement) != TCL_OK) {
		result = TCL_ERROR;
	} else if(sqlite3_step(statement) != SQLITE_DONE) {
		Tcl_AppendResult(interp, sqlite3_errmsg(sqlite_db), (char *)NULL);
		result = TCL_ERROR;
	}

	if(statement)
		sqlite3_finalize(statement);

	return result;
}

// We don't use the internal Sqlite3 types because we may need to do some special handling for types mapped from
// PostgreSQL. For example, PostgreSQL booleans present as strings, but Sqlite3 booleans are integer 0 or 1.
enum mappedTypes {
	PG_SQLITE_INT,
	PG_SQLITE_DOUBLE,
	PG_SQLITE_TEXT,
	PG_SQLITE_BOOL,
	PG_SQLITE_NOTYPE
};

struct {
	char *name;
	enum mappedTypes type;
} mappedTypes[] = {
	{"integer",      PG_SQLITE_INT},
	{"real",         PG_SQLITE_DOUBLE},
	{"boolean",      PG_SQLITE_BOOL},
	{"int",          PG_SQLITE_INT},
	{"double",       PG_SQLITE_DOUBLE},
	{"bool",         PG_SQLITE_BOOL},
	{"text",         PG_SQLITE_TEXT},
	{NULL,           PG_SQLITE_NOTYPE}
};

// Reverse mapping primarily for debugging. Map to the first (canonical) name for a type.
char *Pg_sqlite_typename(enum mappedTypes type)
{
	static char *typenames[PG_SQLITE_NOTYPE] = { NULL };

	if (type >= PG_SQLITE_NOTYPE)
		return NULL;

	if (typenames[0] == NULL) {
		int t;

		for(t = 0; mappedTypes[t].name; t++) {
			if (typenames[mappedTypes[t].type] == NULL) {
				typenames[mappedTypes[t].type] = mappedTypes[t].name;
			}
		}
	}

	return typenames[type];
}

// Step through a list and produce an array of the types in the list. Since the list may be a list of types
// or a list of names and types, we take a start index and stride to describe the list.
int
Pg_sqlite_mapTypes(Tcl_Interp *interp, Tcl_Obj *list, int start, int stride, enum mappedTypes **arrayPtr, int *lengthPtr)
{
	Tcl_Obj          **objv;
	int                objc;
	enum mappedTypes  *array;
	int                i;
	int                col;

	if(Tcl_ListObjGetElements(interp, list, &objc, &objv) != TCL_OK)
		return TCL_ERROR;

	if (stride > 1 && (objc % stride) != 0) {
		Tcl_AppendResult(interp, "List not an even length", (char *)NULL);
		return TCL_ERROR;
	}

	array = (enum mappedTypes *)ckalloc((sizeof *array) * (objc / stride));

	for(col = 0, i = start; i < objc; col++, i += stride) {
		char *typeName = Tcl_GetString(objv[i]);
		int   t;

		for(t = 0; mappedTypes[t].name; t++) {
			if(strcmp(typeName, mappedTypes[t].name) == 0) {
				array[col] = mappedTypes[t].type;
				break;
			}
		}

		if(!mappedTypes[t].name) {
			ckfree((void *)array);
			Tcl_AppendResult(interp, "Unknown type ", typeName, (char *)NULL);
			return TCL_ERROR;
		}
	}

	*arrayPtr = array;
	*lengthPtr = col;
	return TCL_OK;
}

// Step through a list and produce an array of the names in the list. Since the list may be a list of types
// or a list of names and types, we take a stride to describe the list.
int
Pg_sqlite_getNames(Tcl_Interp *interp, Tcl_Obj *list, int stride, char ***arrayPtr, int *lengthPtr)
{
	Tcl_Obj **objv;
	int       objc;
	char    **array;
	int       i;
	int       col;

	if(Tcl_ListObjGetElements(interp, list, &objc, &objv) != TCL_OK)
		return TCL_ERROR;

	if (stride > 1 && (objc % stride) != 0) {
		Tcl_AppendResult(interp, "List not an even length", (char *)NULL);
		return TCL_ERROR;
	}

	array = (char **)ckalloc((sizeof *array) * (objc / stride));

	for(col = 0, i = 0; i < objc; col++, i += stride) {
		array[col] = Tcl_GetString(objv[i]);
	}

	*arrayPtr = array;
	*lengthPtr = col;
	return TCL_OK;
}

// PostgreSQL documentation, possible values for the boolean type:
// Valid literal values for the "true" state are: TRUE 't' 'true' 'y' 'yes' 'on' '1'
// For the "false" state, the following values can be used: FALSE 'f' 'false' 'n' 'no' 'off' '0'
// boolean values are output using the letters t and f.
// Handle all possible cases
int
Pg_sqlite_toBool(char *value)
{
	int i = 0;

	// skip 'quotes'
	if(value[i] == '\'') i++;

	switch (tolower(value[i])) {
		// off and on
		case 'o': {
			if (tolower(value[i+1]) == 'n') { return 1; }
			return 0;
		}

		// true and false
		case 't': case 'y': { return 1; }
		case 'f': case 'n': { return 0; }

		// otherwise assume it's an integer
		default: {
			return atoi(value);
		}
	}
}

// Bind a single value to an Sqlite3 prepared statement, using our internal types.
int
Pg_sqlite_bindValue(sqlite3 *sqlite_db, sqlite3_stmt *statement, int column, char *value, enum mappedTypes type, const char **errorMessagePtr)
{
	switch(type) {
		case PG_SQLITE_BOOL: {
			if (sqlite3_bind_int(statement, column+1, Pg_sqlite_toBool(value)) == SQLITE_OK)
				return TCL_OK;
			break;
		}
		case PG_SQLITE_INT: {
			int ival = atoi(value);
			if(ival == 0) {
				// It might be a boolean column mapped to an integer column
				ival = Pg_sqlite_toBool(value);
			}
			if (sqlite3_bind_int(statement, column+1, ival) == SQLITE_OK)
				return TCL_OK;
			break;
		}
		case PG_SQLITE_DOUBLE: {
			if (sqlite3_bind_double(statement, column+1, atof(value)) == SQLITE_OK)
				return TCL_OK;
			break;
		}
		case PG_SQLITE_TEXT: {
			if (sqlite3_bind_text(statement, column+1, value, -1, SQLITE_TRANSIENT) == SQLITE_OK)
				return TCL_OK;
			break;
		}
		default: {
			*errorMessagePtr = "Internal error - invalid column type";
			return TCL_ERROR;
		}
	}
	*errorMessagePtr = sqlite3_errmsg(sqlite_db);
	return TCL_ERROR;
}

//
// Generate statement to query the target DB to see if the row is already there. Returns success and fills in the indexes
// of the primary keys in the name list.
//
int
Pg_sqlite_generateCheck(Tcl_Interp *interp, sqlite3 *sqlite_db, char *tableName, char **columnNames, int nColumns, Tcl_Obj *primaryKey, sqlite3_stmt **statementPtr, int **primaryKeyIndexPtr)
{
	Tcl_Obj     **keyv;
	int           keyc;
	int          *primaryKeyIndex = NULL;
	char        **primaryKeyNames = NULL;
	Tcl_Obj      *sql = NULL;
	Tcl_Obj      *where = NULL;
	int           i;
	int           k;
	int           result = TCL_ERROR;
	sqlite3_stmt *statement = NULL;

	if(Tcl_ListObjGetElements(interp, primaryKey, &keyc, &keyv) != TCL_OK)
		goto cleanup_and_exit;

	Tcl_IncrRefCount(where = Tcl_NewObj());

	primaryKeyNames = (char **)ckalloc(keyc * (sizeof *primaryKeyNames));
	for(k = 0; k < keyc; k++) {
		char *column = Tcl_GetString(keyv[k]);
		char *space = strchr(column, ' ');
		if(space) {
			primaryKeyNames[k] = (char *)ckalloc(space - column + 1);
			*space = 0;
			strcpy(primaryKeyNames[k], column);
			*space = ' ';
		} else {
			primaryKeyNames[k] = (char *)ckalloc(strlen(column) + 1);
			strcpy(primaryKeyNames[k], column);
		}
		if(k != 0)
			Tcl_AppendStringsToObj(where, ", ", (char *)NULL);
		Tcl_AppendStringsToObj(where, primaryKeyNames[k], " = ?", (char *)NULL);
	}

	primaryKeyIndex = (int *)ckalloc((keyc + 1) * (sizeof *primaryKeyIndex));
	for(k = 0; k < keyc+1; k++) {
		primaryKeyIndex[k] = -1;
	}

	Tcl_IncrRefCount(sql = Tcl_NewObj());

	Tcl_AppendStringsToObj(sql, "SELECT ", (char *)NULL);
	for(i = 0; i < nColumns; i++) {
		char *column = columnNames[i];
		// add to the select clause
		if(i != 0)
			Tcl_AppendStringsToObj(sql, ", ", (char *)NULL);
		Tcl_AppendStringsToObj(sql, column, (char *)NULL);

		// look in primary key list
		for(k = 0; k < keyc; k++) {
			if(strcmp(column, primaryKeyNames[k]) == 0)
				break;
		}

		// if it's a primary key
		if(k < keyc) {
			// remember where it was in the column list
			primaryKeyIndex[k] = i;
		}
	}

	// if there's any unused primary keys that's an error
	for(k = 0; k < keyc; k++) {
		if(primaryKeyIndex[k] == -1)
			break;
	}
	if(k < keyc) {
		Tcl_AppendResult(interp, "Primary keys names must all be in the column list", (char *)NULL);
		goto cleanup_and_exit;
	}

	// combine select list and where clause into statement, and turn it into a string
	Tcl_AppendStringsToObj(sql, " FROM ", tableName, " WHERE (", Tcl_GetString(where), ");", (char *)NULL);

	// create statement
	if(Pg_sqlite_prepare(interp, sqlite_db, Tcl_GetString(sql), &statement) != TCL_OK) {
		goto cleanup_and_exit;
	}

	result = TCL_OK;

  cleanup_and_exit:
	// discard key names
	if(primaryKeyNames) {
		for(k = 0; k < keyc; k++) {
			ckfree((void *)primaryKeyNames[k]);
		}
		ckfree((void *)primaryKeyNames);
	}

	// save or discard primary key indexes.
	if(primaryKeyIndex) {
		if(result == TCL_OK)
			*primaryKeyIndexPtr = primaryKeyIndex;
		else
			ckfree((void *)primaryKeyIndex);
	}

	// save or discard statement
	if(statement) {
		if(result == TCL_OK)
			*statementPtr = statement;
		else
			sqlite3_finalize(statement);
	}

	// Release allocated objects
	if(sql)   Tcl_DecrRefCount (sql);
	if(where) Tcl_DecrRefCount (where);

	return result;
}

//
// Execute prepared statement from Pg_sqlite_generate_check, pulling the primary keys from the already parsed row.
//
// Return TCL_CONTINUE if
//    (a) there is a row already existing, and
//    (b) all values in the parsed row match the values retreived from the db
// Return TCL_OK if the there is no row or it doesn't match.
// Return TCL_ERROR if there is an error.
//
int
Pg_sqlite_executeCheck(Tcl_Interp *interp, sqlite3 *sqlite_db, sqlite3_stmt *statement, int *primaryKeyIndex, enum mappedTypes *columnTypes, char **row, int count)
{
	int i;
	int status = TCL_ERROR;
	int col;

	for(i = 0; -1 != (col = primaryKeyIndex[i]); i++) {
		char             *value = row[col];
		enum mappedTypes  type = columnTypes[col];
		const char       *errorMessage;

		if (Pg_sqlite_bindValue(sqlite_db, statement, i, value, type, &errorMessage) != TCL_OK) {
			Tcl_AppendResult(interp, errorMessage, (char *)NULL);
			goto cleanup_and_exit;
		}
	}

	switch (sqlite3_step(statement)) {
		case SQLITE_ROW: {
			for(i = 0; i < count; i++) {
				// NULL CHECKING
				int colType = sqlite3_column_type(statement, i);
				// Both null, matches, continue to next row
				if(colType == SQLITE_NULL && !row[i]) { continue; }
				// sqlite null, check not null, no match, return
				if(colType == SQLITE_NULL && row[i]) {
					status = TCL_OK;
					goto cleanup_and_exit;
				}
				// sqlite has value, check is null, no match, return
				if(colType != SQLITE_NULL && !row[i]) {
					status = TCL_OK;
					goto cleanup_and_exit;
				}

				// Compare columns
				switch (columnTypes[i]) {
					case PG_SQLITE_BOOL: {
						int ival = sqlite3_column_int(statement, i);
						if (Pg_sqlite_toBool(row[i]) != ival) {
							status = TCL_OK;
							goto cleanup_and_exit;
						}
						break;
					}
					case PG_SQLITE_TEXT: {
						char *sval = (char *)sqlite3_column_text(statement, i);
						if(strcmp(row[i], sval) != 0) {
							status = TCL_OK;
							goto cleanup_and_exit;
						}
						break;
					}
					case PG_SQLITE_INT: {
						int ival = sqlite3_column_int(statement, i);
						int rval = atoi(row[i]);
						if(ival != rval) {
							status = TCL_OK;
							goto cleanup_and_exit;
						}
						break;
					}
					case PG_SQLITE_DOUBLE: {
						double dval = sqlite3_column_double(statement, i);
						double rval = atof(row[i]);
						if(dval != rval) {
							status = TCL_OK;
							goto cleanup_and_exit;
						}
						break;
					}
					default: { // otherwise unhandled type, maybe should be an error?
						char *value = (char *)sqlite3_column_text(statement, i);
						if(strcmp(row[i], value) != 0) {
							status = TCL_OK;
							goto cleanup_and_exit;
						}
						break;
					}
				}
			}
			status = TCL_CONTINUE;
			goto cleanup_and_exit;
		}
		case SQLITE_DONE: {
			status = TCL_OK;
			goto cleanup_and_exit;
		}
		default: {
			Tcl_AppendResult(interp, sqlite3_errmsg(sqlite_db), (char *)NULL);
			goto cleanup_and_exit;
		}
	}

  cleanup_and_exit:
	sqlite3_reset(statement);
	sqlite3_clear_bindings(statement);
	return status;
}

// Generate SQL to *insert* a row into Sqlite3. Also create the table if required.
//
// Pulls the names from either a name list or a name-type list. Only one need be provided. If it's creating
// the table and no types are provided, it punts and assumes text.
//
// TODO: Add type list argument, or get rid of the whole separate -names and -types options.
Tcl_Obj*
Pg_sqlite_generate(Tcl_Interp *interp, sqlite3 *sqlite_db, char *sqliteTable, Tcl_Obj *nameList, Tcl_Obj *nameTypeList, Tcl_Obj *primaryKey, char *unknownKey, int newTable, int replacing)
{
	Tcl_Obj **objv;
	int       objc;
	Tcl_Obj **keyv = NULL;
	int       keyc = 0;
	Tcl_Obj  *create = NULL;
	Tcl_Obj  *sql = NULL;
	Tcl_Obj  *values = NULL;
	int       i;
	int       primaryKeyIndex = -1;
	int       stride;
	Tcl_Obj  *result = NULL;

	if(nameTypeList) {
		if(Tcl_ListObjGetElements(interp, nameTypeList, &objc, &objv) != TCL_OK)
			goto cleanup;

		if(objc & 1) {
			Tcl_AppendResult(interp, "List must have an even number of elements", (char *)NULL);
			goto cleanup;
		}

		stride = 2;
	} else {
		if(Tcl_ListObjGetElements(interp, nameList, &objc, &objv) != TCL_OK)
			goto cleanup;

		stride = 1;
	}

	if(newTable && primaryKey) {
		if(Tcl_ListObjGetElements(interp, primaryKey, &keyc, &keyv) != TCL_OK)
			goto cleanup;

		if(keyc == 1) {
			char *keyName = Tcl_GetString(keyv[0]);
			for(i = 0; i < objc; i += stride)
				if(strcmp(keyName, Tcl_GetString(objv[i])) == 0)
					break;
			if(i >= objc) {
				Tcl_AppendResult(interp, "Primary key not found in list", (char *)NULL);
				goto cleanup;
			}
			primaryKeyIndex = i/stride;
		}
	}

	Tcl_IncrRefCount(create = Tcl_NewObj());
	Tcl_IncrRefCount(sql = Tcl_NewObj());
	Tcl_IncrRefCount(values = Tcl_NewObj());

	if (newTable)
		Tcl_AppendStringsToObj(create, "CREATE TABLE ", sqliteTable, " (", (char *)NULL);

	if (replacing) {
		Tcl_AppendStringsToObj(sql, "INSERT OR REPLACE INTO ", sqliteTable, " (", (char *)NULL);
	} else {
		Tcl_AppendStringsToObj(sql, "INSERT INTO ", sqliteTable, " (", (char *)NULL);
	}

	for(i = 0; i < objc; i+= stride) {
		if (newTable) {
			Tcl_AppendToObj(create, "\n\t", -1);
			Tcl_AppendObjToObj(create, objv[i]);
			if (stride == 2) {
				Tcl_AppendToObj(create, " ", -1);
				Tcl_AppendObjToObj(create, objv[i+1]);
			} else {
				Tcl_AppendToObj(create, " TEXT", -1);
			}
			if(i == primaryKeyIndex)
				Tcl_AppendToObj(create, " PRIMARY KEY", -1);

			if(i < objc-stride)
				Tcl_AppendToObj(create, ",", -1);
		}

		if(unknownKey && strcmp(Tcl_GetString(objv[i]), unknownKey) == 0) {
			Tcl_AppendResult(interp, "Unknown key duplicates existing key", (char *)NULL);
			goto cleanup;
		}

		if(i > 0)
			Tcl_AppendToObj(sql, ", ", -1);
		Tcl_AppendObjToObj(sql, objv[i]);

		if(i > 0)
			Tcl_AppendToObj(values, ", ", -1);
		Tcl_AppendToObj(values, "?", -1);
	}

	if(unknownKey) {
		if (newTable) {
			Tcl_AppendStringsToObj(create, ",\n\t", unknownKey, " TEXT", (char *)NULL);
		}
		Tcl_AppendStringsToObj(sql, ", ", unknownKey, (char *)NULL);
		Tcl_AppendToObj(values, ",?", -1);
	}

	if(newTable && keyc > 1) {
		int i;
		Tcl_AppendToObj(create, ",\n\tPRIMARY KEY(", -1);

		for(i = 0; i < keyc; i++) {
			if(i)
				Tcl_AppendToObj(create, ", ", -1);
			Tcl_AppendObjToObj(create, keyv[i]);
		}

		Tcl_AppendToObj(create, ")", -1);
	}

	if(newTable) Tcl_AppendToObj(create, "\n);", -1);

	Tcl_AppendToObj(sql, ") VALUES (", -1);
	Tcl_AppendObjToObj(sql, values);
	Tcl_AppendToObj(sql, ");", -1);

	if(newTable) {
		if(Pg_sqlite_execObj(interp, sqlite_db, create) != TCL_OK)
			goto cleanup;
	}

	result = sql;

  cleanup:
	if(create) Tcl_DecrRefCount(create);
	if(sql && sql != result) Tcl_DecrRefCount(sql);
	if(values) Tcl_DecrRefCount(values);

	return result;
}

// Drop table
int
Pg_sqlite_dropTable(Tcl_Interp *interp, sqlite3 *sqlite_db, char *dropTable)
{
	Tcl_Obj *drop = NULL;
	int result;

	Tcl_IncrRefCount(drop = Tcl_NewObj());

	Tcl_AppendStringsToObj(drop, "DROP TABLE ", dropTable, ";", (char *)NULL);

	result = Pg_sqlite_execObj(interp, sqlite_db, drop);

	if(drop) Tcl_DecrRefCount(drop);

	return result;
}

// Part 2 of the hack, locate the ObjProc for a known sqlite3 command so I can validate that the
// userdata I've pulled out of the command provided really is a sqlite3 userdata.
int
Pg_sqlite_probe(Tcl_Interp *interp, Tcl_ObjCmdProc **procPtr)
{
	static Tcl_ObjCmdProc *sqlite3_ObjProc = NULL;

	if (sqlite3_ObjProc == NULL) {
		char               cmd_name[256];
		char               create_cmd[256];
		char               delete_cmd[256];
		struct Tcl_CmdInfo cmd_info;

		if (Tcl_Eval(interp, "package require sqlite3") != TCL_OK) {
			return TCL_ERROR;
		}

		snprintf(cmd_name, 256, "::dummy%d", getpid());
		snprintf(create_cmd, 256, "sqlite3 %s :memory:", cmd_name);
		snprintf(delete_cmd, 256, "%s close", cmd_name);

		if (Tcl_Eval(interp, create_cmd) != TCL_OK) {
			return TCL_ERROR;
		}

		if (!Tcl_GetCommandInfo(interp, cmd_name, &cmd_info)) {
			Tcl_AppendResult(interp, "pg_sqlite3 probe failed (", cmd_name, " not found)", (char *)NULL);
			Tcl_Eval(interp, delete_cmd);
			return TCL_ERROR;
		}

		if (!cmd_info.isNativeObjectProc) {
			Tcl_AppendResult(interp, "pg_sqlite3 probe failed (", cmd_name, " not a native object proc)", (char *)NULL);
			Tcl_Eval(interp, delete_cmd);
			return TCL_ERROR;
		}

		sqlite3_ObjProc = cmd_info.objProc;
		Tcl_Eval(interp, delete_cmd);

		if (!sqlite3_ObjProc) {
			Tcl_AppendResult(interp, "pg_sqlite3 probe failed (", cmd_name, " not a native object proc)", (char *)NULL);
			return TCL_ERROR;
		}
	}
	*procPtr = sqlite3_ObjProc;

	return TCL_OK;
}

// Error/end-of-file handling wrapped around Tcl_GetsObj
int
Pg_sqlite_gets(Tcl_Interp *interp, Tcl_Channel chan, Tcl_Obj **lineObjPtr)
{
	Tcl_SetStringObj(*lineObjPtr, "", -1);

	if(Tcl_GetsObj(chan, *lineObjPtr) == -1) {
		if(Tcl_Eof(chan)) {
			return TCL_BREAK;
		} else {
			Tcl_AppendResult (interp, Tcl_ErrnoMsg(Tcl_GetErrno()), (char *)NULL);
			return TCL_ERROR;
		}
	}

	return TCL_OK;
}

// Split a string up into an array of named columns. Modifies the input string.
int
Pg_sqlite_split_tabsep(char *row, char ***columnsPtr, int nColumns, char *sepStr, char *nullStr, const char **errorMessagePtr)
{
	int i;
	char *col;
	char *nextCol;
	char **columns = (char **)ckalloc(nColumns * sizeof *columns);
	int returnCode = TCL_OK;
	int sepLen = strlen(sepStr);

	col = row;
	i = 0;
	while(col && i < nColumns) {
		nextCol = strstr(col, sepStr);
		columns[i] = col;
		if(nextCol) {
			*nextCol = 0;
			nextCol += sepLen;
		}
		if (nullStr && strcmp(columns[i], nullStr) == 0)
			columns[i] = NULL;
		col = nextCol;
		i++;
	}
	if (col) {
		*errorMessagePtr = "Too many columns in row";
		returnCode = TCL_ERROR;
	} else if (i < nColumns) {
		*errorMessagePtr = "Not enough columns in row";
		returnCode = TCL_ERROR;
	}
	if(returnCode == TCL_OK) {
		*columnsPtr = columns;
	} else {
		ckfree((void *)columns);
	}

	return returnCode;
}

// Split a string up into a key-val list, and populate a column list with the values pulled in from the list. This
// modifies the original string.
//
// TODO, add nullStr option and code to remove value from list.
int
Pg_sqlite_split_keyval(Tcl_Interp *interp, char *row, char ***columnsPtr, int nColumns, char *sepStr, char **names, Tcl_Obj *unknownObj)
{
	char *val;
	char *key;
	char *nextVal;
	int col;
	char **columns = (char **)ckalloc(nColumns * sizeof *columns);
	int returnCode = TCL_OK;
	int sepLen = strlen(sepStr);

	Tcl_SetListObj(unknownObj, 0, NULL);
	for(col = 0; col < nColumns; col++)
		columns[col] = NULL;

	val = row;
	while(val) {
		nextVal = strstr(val, sepStr);
		if(!nextVal) {
			Tcl_AppendResult(interp, "Odd number of columns", (char *)NULL);
			returnCode = TCL_ERROR;
			break;
		}
		key = val;
		*nextVal = 0;
		nextVal += sepLen;

		val = nextVal;
		nextVal = strstr(val, sepStr);
		if(nextVal) {
			*nextVal = 0;
			nextVal += sepLen;
		}

		for(col = 0; col < nColumns; col++) {
			if(strcmp(key, names[col]) == 0) {
				break;
			}
		}
		if(col < nColumns)
			columns[col] = val;
		else {
			LAPPEND_STRING(interp, unknownObj, key);
			LAPPEND_STRING(interp, unknownObj, val);
		}

		val = nextVal;
	}

	if(returnCode == TCL_OK) {
		*columnsPtr = columns;
	} else {
		ckfree((void *)columns);
		Tcl_SetListObj(unknownObj, 0, NULL);
	}

	return returnCode;
}

int Pg_sqlite_getDB(Tcl_Interp *interp, char *cmdName, sqlite3 **sqlite_dbPtr)
{
        struct Tcl_CmdInfo  sqlite_commandInfo;
	Tcl_ObjCmdProc     *sqlite3_ObjProc = NULL;
        struct SqliteDb    *sqlite_clientData;

        if (!Tcl_GetCommandInfo(interp, cmdName, &sqlite_commandInfo)) {
                Tcl_AppendResult(interp, cmdName, " is not an sqlite3 handle", (char *)NULL);
                return TCL_ERROR;
        }

	// Get a known sqlite3 Tcl_ObjCmdProc
	if (Pg_sqlite_probe(interp, &sqlite3_ObjProc) != TCL_OK) {
		return TCL_ERROR;
	}

	if (sqlite3_ObjProc != sqlite_commandInfo.objProc) {
		Tcl_AppendResult(interp, "command ", cmdName, " is not an sqlite3 handle", (char *)NULL);
		return TCL_ERROR;
	}

        sqlite_clientData = (struct SqliteDb *)sqlite_commandInfo.objClientData;

        *sqlite_dbPtr = sqlite_clientData->db;

	return TCL_OK;
}

// Main routine, extract the sqlite handle, parse the ensemble command, and run the subcommand.
int
Pg_sqlite(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
        sqlite3            *sqlite_db;
	int                 cmdIndex;

	static const char *subCommands[] = {
		"info", "import_postgres_result", "write_tabsep", "read_tabsep", "read_tabsep_keylist",
		(char *)NULL
	};

	enum subCommands
	{
		CMD_INFO, CMD_IMPORT_POSTGRES_RESULT, CMD_WRITE_TABSEP, CMD_READ_TABSEP, CMD_READ_KEYVAL,
		NUM_COMMANDS
	};

        if (objc <= 2) {
                Tcl_WrongNumArgs(interp, 1, objv, "sqlite_handle command ?args?");
                return TCL_ERROR;
        }

	if(Pg_sqlite_getDB(interp, Tcl_GetString(objv[1]), &sqlite_db) != TCL_OK) {
		return TCL_ERROR;
	}

	if (Tcl_GetIndexFromObj(interp, objv[2], subCommands, "command", TCL_EXACT, &cmdIndex) != TCL_OK)
		return TCL_ERROR;

	int minargs[NUM_COMMANDS] = { -1 };
	int incoming[NUM_COMMANDS] = { -1 };
	char *argerr[NUM_COMMANDS] = { "" };

	// one time initialization of common code
	if(minargs[0] == -1) {
		int i;
		for(i = 0; i < NUM_COMMANDS; i++) {
			minargs[i] = 0;
			incoming[i] = 0;
			argerr[i] = "";
		}
		minargs[CMD_IMPORT_POSTGRES_RESULT] = 4;
		minargs[CMD_READ_TABSEP] = 3;
		minargs[CMD_READ_KEYVAL] = 3;
		incoming[CMD_IMPORT_POSTGRES_RESULT] = 1;
		incoming[CMD_READ_TABSEP] = 1;
		incoming[CMD_READ_KEYVAL] = 1;
		argerr[CMD_READ_TABSEP] = "?-row tabsep_row? ?-file file_handle? ?-sql sqlite_sql? ?-create new_table? ?-into table? ?-as name-type-list? ?-types type-list? ?-names name-list? ?-pkey primary_key? ?-sep sepstring? ?-null nullstring? ?-replace? ?-poll_interval count? ?-check?";
		argerr[CMD_IMPORT_POSTGRES_RESULT] = "handle ?-sql sqlite_sql? ?-create new_table? ?-into table? ?-as name-type-list? ?-types type-list? ?-names name-list? ?-rowbyrow? ?-pkey primary_key? ?-null nullstring? ?-replace? ?-poll_interval count? ?-check? ?-max col varname?";
		argerr[CMD_READ_KEYVAL] = "?-row tabsep_row? ?-file file_handle? ?-create new_table? ?-into table? ?-as name-type-list? ?-names name-list? ?-pkey primary_key? ?-sep sepstring? ?-unknown colname? ?-replace? ?-poll_interval count?";
	}

	// common variables
	Tcl_Obj           *sqliteCodeObj = NULL;
	char              *sqliteCode = NULL;
	char              *sqliteTable = NULL;
	char              *dropTable = NULL;
	sqlite3_stmt      *statement = NULL;
	int                optIndex = 4;
	Tcl_Obj           *typeList = NULL;
	Tcl_Obj           *nameTypeList = NULL;
	Tcl_Obj           *nameList = NULL;
	int                rowbyrow = 0;
	int                returnCode = TCL_OK;
	const char        *errorMessage = NULL;
	enum mappedTypes  *columnTypes = NULL;
	char             **columnNames = NULL;
	int                nColumns = 0;
	int                column;
	ExecStatusType     status;
	char              *tabsepFile = NULL;
	char              *tabsepRow = NULL;
	Tcl_Obj           *primaryKey = NULL;
	char             **columns = NULL;
	int                totalTuples = 0;
	char		  *sepString = "\t";
	char              *nullString = NULL;
	char              *unknownKey = NULL;
	int		   createTable = 0;
	int		   replaceRows = 0;
	int                pollInterval = 0;
	int		   recommitInterval = 0;
	int		   checkRow = 0;
	sqlite3_stmt      *checkStatement = NULL;
	int		  *primaryKeyIndex = NULL;
	char              *maxColumn = NULL;
	char              *maxVar = NULL;
	int                maxColumnNumber = -1;
	int                maxColumnType = PG_SQLITE_NOTYPE;

	// common code
	if(incoming[cmdIndex]) {
		optIndex = minargs[cmdIndex];

		if (objc < optIndex) {
		  common_wrong_num_args:
			Tcl_WrongNumArgs(interp, 3, objv, argerr[cmdIndex]);
			return TCL_ERROR;
		}

		while(optIndex < objc) {
			char *optName = Tcl_GetString(objv[optIndex]);
			optIndex++;
			if (optName[0] != '-') {
				goto common_wrong_num_args;
			}

			if (cmdIndex != CMD_READ_KEYVAL && strcmp(optName, "-types") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No list provided for -types", (char *)NULL);
					return TCL_ERROR;
				}
				typeList = objv[optIndex];
				optIndex++;
			} else if (strcmp(optName, "-names") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No list provided for -names", (char *)NULL);
					return TCL_ERROR;
				}
				nameList = objv[optIndex];
				optIndex++;
			} else if (strcmp(optName, "-as") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No list provided for -as", (char *)NULL);
					return TCL_ERROR;
				}
				nameTypeList = objv[optIndex];
				optIndex++;
			} else if (strcmp(optName, "-pkey") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No list provided for -pkey", (char *)NULL);
					return TCL_ERROR;
				}
				primaryKey = objv[optIndex];
				optIndex++;
			} else if (cmdIndex != CMD_IMPORT_POSTGRES_RESULT && strcmp(optName, "-sep") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No string provided for -sep", (char *)NULL);
					return TCL_ERROR;
				}
				sepString = Tcl_GetString(objv[optIndex]);
				optIndex++;
			} else if (cmdIndex != CMD_READ_KEYVAL && strcmp(optName, "-null") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No string provided for -null", (char *)NULL);
					return TCL_ERROR;
				}
				nullString = Tcl_GetString(objv[optIndex]);
				optIndex++;
			} else if (cmdIndex == CMD_READ_KEYVAL && strcmp(optName, "-unknown") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No column provided for -unknown", (char *)NULL);
					return TCL_ERROR;
				}
				unknownKey = Tcl_GetString(objv[optIndex]);
				optIndex++;
			} else if (cmdIndex != CMD_READ_KEYVAL && strcmp(optName, "-sql") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No code provided for -sql", (char *)NULL);
					return TCL_ERROR;
				}
				sqliteCode = Tcl_GetString(objv[optIndex]);
				optIndex++;
			} else if (strcmp(optName, "-create") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No table provided for -create", (char *)NULL);
					return TCL_ERROR;
				}
				sqliteTable = Tcl_GetString(objv[optIndex]);
				createTable = 1;
				optIndex++;
			} else if (strcmp(optName, "-into") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No table provided for -into", (char *)NULL);
					return TCL_ERROR;
				}
				sqliteTable = Tcl_GetString(objv[optIndex]);
				optIndex++;
			} else if (cmdIndex == CMD_IMPORT_POSTGRES_RESULT && strcmp(optName, "-max") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No column provided for -max", (char *)NULL);
					return TCL_ERROR;
				}
				maxColumn = Tcl_GetString(objv[optIndex]);
				optIndex++;
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No variable provided for -max", (char *)NULL);
					return TCL_ERROR;
				}
				maxVar = Tcl_GetString(objv[optIndex]);
				optIndex++;
			} else if (cmdIndex != CMD_IMPORT_POSTGRES_RESULT && strcmp(optName, "-row") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No string provided for -row", (char *)NULL);
					return TCL_ERROR;
				}
				tabsepRow = Tcl_GetString(objv[optIndex]);
				optIndex++;
			} else if (cmdIndex != CMD_IMPORT_POSTGRES_RESULT && strcmp(optName, "-file") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No name provided for -file", (char *)NULL);
					return TCL_ERROR;
				}
				tabsepFile = Tcl_GetString(objv[optIndex]);
				optIndex++;
			} else if (cmdIndex == CMD_IMPORT_POSTGRES_RESULT && strcmp(optName, "-rowbyrow") == 0) {
				rowbyrow = 1;
			} else if (cmdIndex != CMD_READ_KEYVAL && strcmp(optName, "-check") == 0) {
				checkRow = 1;
			} else if (strcmp(optName, "-replace") == 0) {
				replaceRows = 1;
			} else if (strcmp(optName, "-recommit") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No value provided for -recommit", (char *)NULL);
					return TCL_ERROR;
				}
				if (Tcl_GetIntFromObj(interp, objv[optIndex], &recommitInterval) == TCL_ERROR) {
					Tcl_AppendResult(interp, " in argument to '-recommit'", (char *)NULL);
					return TCL_ERROR;
				}
				if(pollInterval <= 0) // Or should this be an error?
					pollInterval = 0;
				optIndex++;
			} else if (strcmp(optName, "-poll_interval") == 0) {
				if(optIndex >= objc) {
					Tcl_AppendResult(interp, "No value provided for -poll_interval", (char *)NULL);
					return TCL_ERROR;
				}
				if (Tcl_GetIntFromObj(interp, objv[optIndex], &pollInterval) == TCL_ERROR) {
					Tcl_AppendResult(interp, " in argument to '-poll_interval'", (char *)NULL);
					return TCL_ERROR;
				}
				if(pollInterval <= 0) // Or should this be an error?
					pollInterval = 0;
				optIndex++;
			} else {
				goto common_wrong_num_args;
			}
		}

		if (cmdIndex == CMD_READ_TABSEP || cmdIndex == CMD_READ_KEYVAL) {
			if(!tabsepFile && !tabsepRow) {
				Tcl_AppendResult(interp, "command requires either -row or -file", (char *)NULL);
				return TCL_ERROR;
			}

			if(tabsepFile && tabsepRow) {
				Tcl_AppendResult(interp, "Can't use both -row and -file", (char *)NULL);
				return TCL_ERROR;
			}
		}

		if (sqliteCode && sqliteTable) {
			Tcl_AppendResult(interp, "Can't use both -sql and -into", (char *)NULL);
			return TCL_ERROR;
		}

		if (!sqliteCode && !sqliteTable) {
			Tcl_AppendResult(interp, "No sqlite destination provided", (char *)NULL);
			return TCL_ERROR;
		}

		if ((nameList || typeList) && nameTypeList) {
			Tcl_AppendResult(interp, "Can't use both -names/-types and -as", (char *)NULL);
			return TCL_ERROR;
		}

		if(typeList) {
			if (Pg_sqlite_mapTypes(interp, typeList, 0, 1, &columnTypes, &nColumns) != TCL_OK)
				return TCL_ERROR;
		}

		if(nameList) {
			if(cmdIndex == CMD_READ_KEYVAL) {
				if(Pg_sqlite_getNames(interp, nameList, 1, &columnNames, &nColumns) != TCL_OK) {
				  early_error_exit:
					if(dropTable)
						Pg_sqlite_dropTable(interp, sqlite_db, dropTable);
					if (columnNames)
						ckfree((void *)columnNames);
					if (columnTypes)
						ckfree((void *)columnTypes);
					if(sqliteCodeObj)
						Tcl_DecrRefCount(sqliteCodeObj);
					return TCL_ERROR;
				}
			} else if(!nColumns)  {
				if(Tcl_ListObjLength(interp, nameList, &nColumns) != TCL_OK) {
					goto early_error_exit;
				}
			}
		}

		if(!columnNames && nameTypeList) {
			if(Pg_sqlite_getNames(interp, nameTypeList, 2, &columnNames, &nColumns) != TCL_OK) {
				goto early_error_exit;
			}
		}

		if(sqliteTable) {
			if(nameTypeList) {
				if (Pg_sqlite_mapTypes(interp, nameTypeList, 1, 2, &columnTypes, &nColumns) != TCL_OK)
					goto early_error_exit;
			} else if(!nameList) {
				Tcl_AppendResult(interp, "No template (-as) provided for -into", (char *)NULL);
				goto early_error_exit;
			}

			sqliteCodeObj = Pg_sqlite_generate(interp, sqlite_db, sqliteTable, nameList, nameTypeList, primaryKey, unknownKey, createTable, replaceRows);
			sqliteCode = Tcl_GetString(sqliteCodeObj);
			if (!sqliteCode) {
				goto early_error_exit;
			}
			if(createTable) dropTable = sqliteTable;
		}

		if(checkRow) {
			if(!columnNames || !columnTypes || !primaryKey || !sqliteTable) {
				Tcl_AppendResult(interp, "-check requires primary key, column names, and column types", (char *)NULL);
				goto early_error_exit;
			}

			if(Pg_sqlite_generateCheck(interp, sqlite_db, sqliteTable, columnNames, nColumns, primaryKey, &checkStatement, &primaryKeyIndex) != TCL_OK) {
				goto early_error_exit;
			}
		}

		// Last try hack to guess columns
		if(!nColumns) {
			char *p = strchr(sqliteCode, '?');
			while(p) {
				p++;
				nColumns++;
				p = strchr(p, '?');
			}
		}

		if(!nColumns) {
			Tcl_AppendResult(interp, "Can't determine row length from provided arguments", (char *)NULL);
			goto early_error_exit;
		}

		if(maxColumn) {
			if (!columnNames || !columnTypes) {
				Tcl_AppendResult(interp, "Can't specify -max without column names and types",  (char *)NULL);
				goto early_error_exit;
			}
			for(maxColumnNumber = 0; maxColumnNumber < nColumns; maxColumnNumber++) {
				if(strcmp(maxColumn, columnNames[maxColumnNumber]) == 0)
					break;
			}
			if(maxColumnNumber >= nColumns) {
				Tcl_AppendResult(interp, "Argument to -max not found in columns",  (char *)NULL);
				goto early_error_exit;
			}
			switch (columnTypes[maxColumnNumber]) {
				case PG_SQLITE_INT: case PG_SQLITE_DOUBLE: case PG_SQLITE_TEXT: {
					maxColumnType = columnTypes[maxColumnNumber];
					break;
				}
				default: {
					Tcl_AppendResult(interp, "Can only track maximum of integer, float, or text columns", (char *)NULL);
					goto early_error_exit;
				}
			}
		}
	}

	switch (cmdIndex) {
		case CMD_INFO: {
			char       *dbName = NULL;
			Tcl_Obj    *infoList = NULL;
			int         doFilename = 0;
			int	    doBusy = 0;

			optIndex = 3;

			Tcl_IncrRefCount(infoList = Tcl_NewObj());

			if(objc < optIndex) {
			  info_wrong_num_args:
				Tcl_WrongNumArgs(interp, 3, objv, "?-busy? ?-filename? ?-db dbname?");
				if(infoList) Tcl_DecrRefCount(infoList);
				return TCL_ERROR;
			}

			while (optIndex < objc) {
				char *optName = Tcl_GetString(objv[optIndex]);
				optIndex++;
				if (optName[0] != '-') {
					goto info_wrong_num_args;
				}

				if (strcmp(optName, "-db") == 0) {
					if(optIndex >= objc)
						goto info_wrong_num_args;
					dbName = Tcl_GetString(objv[optIndex]);
					optIndex++;
				} else if (strcmp(optName, "-busy") == 0) {
					doBusy = 1;
				} else if (strcmp(optName, "-filename") == 0) {
					doFilename = 1;
				} else
					goto info_wrong_num_args;
			}

			// no args, do everything
			if(!doFilename && !doBusy) {
				doFilename = 1;
				doBusy = 1;
			}

			if(doFilename) {
				if(!dbName)
					dbName = "main";
				LAPPEND_STRING(interp, infoList, "filename");
				LAPPEND_STRING(interp, infoList, sqlite3_db_filename(sqlite_db, dbName));
			}

			if(doBusy) {
				sqlite3_stmt *pStmt = NULL;
				Tcl_Obj      *busyList = NULL;

				for(pStmt=sqlite3_next_stmt(sqlite_db, pStmt); pStmt; pStmt=sqlite3_next_stmt(sqlite_db, pStmt)){
					if( sqlite3_stmt_busy(pStmt) ){
						if(!busyList)
							Tcl_IncrRefCount(busyList = Tcl_NewObj());
						LAPPEND_STRING(interp, busyList, sqlite3_sql(pStmt));
					}
				}

				if(busyList) {
					LAPPEND_STRING(interp, infoList, "busy");
					Tcl_ListObjAppendElement(interp, infoList, busyList);
					Tcl_DecrRefCount(busyList);
				}
			}

			Tcl_SetObjResult(interp, infoList);
			break;
		}

		case CMD_WRITE_TABSEP: {
			Tcl_Channel channel = NULL;
			const char *channelName = NULL;
			int channelMode;
			int sqliteStatus;

			channelName = Tcl_GetString(objv[3]);
			sqliteCode = Tcl_GetString(objv[4]);

			optIndex = 5;
			nullString = "";

			if(objc < optIndex) {
			  write_wrong_num_args:
				Tcl_WrongNumArgs(interp, 3, objv, "handle sql ?-null nullstring? ?-sep sepstring? ?-poll_interval row-count?");
				return TCL_ERROR;
			}

			while (optIndex < objc) {
				char *optName = Tcl_GetString(objv[optIndex]);
				optIndex++;
				if (optName[0] != '-') {
					goto write_wrong_num_args;
				}

				if (strcmp(optName, "-null") == 0) {
					nullString = Tcl_GetString(objv[optIndex]);
					optIndex++;
				} else if (strcmp(optName, "-sep") == 0) {
					sepString = Tcl_GetString(objv[optIndex]);
					optIndex++;
				} else if (strcmp(optName, "-poll_interval") == 0) {
					if (Tcl_GetIntFromObj(interp, objv[optIndex], &pollInterval) == TCL_ERROR) {
						Tcl_AppendResult(interp, " in argument to '-poll_interval'", (char *)NULL);
						return TCL_ERROR;
					}
					if(pollInterval <= 0) // Or should this be an error?
						pollInterval = 0;
					optIndex++;
				} else
					goto write_wrong_num_args;
			}

			channel = Tcl_GetChannel(interp, channelName, &channelMode);
			if(!channel) {
				Tcl_AppendResult(interp, Tcl_ErrnoMsg(Tcl_GetErrno()), " converting ", channelName, (char *)NULL);
				return TCL_ERROR;
			}
			if (!(channelMode & TCL_WRITABLE)) {
				Tcl_AppendResult (interp, "Channel ", channelName, " is not writable", (char *)NULL);
				return TCL_ERROR;
			}

			if(Pg_sqlite_prepare(interp, sqlite_db, sqliteCode, &statement) != TCL_OK)
				return TCL_ERROR;

			nColumns = sqlite3_column_count(statement);
			totalTuples = 0;

			returnCode = TCL_ERROR;

			if(recommitInterval) {
				if(Pg_sqlite_begin(interp, sqlite_db) == TCL_ERROR)
					goto write_tabsep_cleanup_and_exit;
			}

			while (SQLITE_ROW == (sqliteStatus = sqlite3_step(statement))) {
				int i;
				for(i = 0; i < nColumns; i++) {
					char *value = (char *)sqlite3_column_text(statement, i);
					if(value == NULL) value = nullString;
					if (i > 0 && Tcl_WriteChars(channel, sepString, -1) == -1) {
						Tcl_AppendResult(interp, Tcl_ErrnoMsg(Tcl_GetErrno()), (char *)NULL);
						goto write_tabsep_cleanup_and_exit;
					}
					if (Tcl_WriteChars(channel, value, -1) == -1) {
						Tcl_AppendResult(interp, Tcl_ErrnoMsg(Tcl_GetErrno()), (char *)NULL);
						goto write_tabsep_cleanup_and_exit;
					}
				}
				if(Tcl_WriteChars(channel, "\n", -1) == -1) {
					Tcl_AppendResult(interp, Tcl_ErrnoMsg(Tcl_GetErrno()), (char *)NULL);
					goto write_tabsep_cleanup_and_exit;
				}
				totalTuples++;
				if(recommitInterval && (totalTuples % recommitInterval) == 0) {
					if(Pg_sqlite_recommit(interp, sqlite_db, sqliteCode, &statement) != TCL_OK)
						goto write_tabsep_cleanup_and_exit;
				}
				if(pollInterval && (totalTuples % pollInterval) == 0) {
					Tcl_DoOneEvent(0);
				}
			}
			if(sqliteStatus != SQLITE_DONE) {
				Tcl_AppendResult(interp, sqlite3_errmsg(sqlite_db), (char *)NULL);
				goto write_tabsep_cleanup_and_exit;
			}
			returnCode = TCL_OK;
		  write_tabsep_cleanup_and_exit:

			if(statement) {
				sqlite3_finalize(statement);
				statement = NULL;
			}

			if(checkStatement) {
				sqlite3_finalize(checkStatement);
				checkStatement = NULL;
			}

			if(recommitInterval) {
				if(Pg_sqlite_commit(interp, sqlite_db) != TCL_OK)
					returnCode = TCL_ERROR;
			}

			if(returnCode == TCL_ERROR)
				return TCL_ERROR;

			Tcl_SetObjResult(interp, Tcl_NewIntObj(totalTuples));

			return TCL_OK;
		}

		case CMD_READ_KEYVAL:
		case CMD_READ_TABSEP: {
			Tcl_Channel tabsepChannel = NULL;
			int channelMode;
			char *row = NULL;
			Tcl_Obj *unknownObj = NULL;
			Tcl_Obj *rowObj = NULL;

			if(cmdIndex == CMD_READ_KEYVAL)
				Tcl_IncrRefCount(unknownObj = Tcl_NewObj());

			Tcl_IncrRefCount(rowObj = Tcl_NewObj());

			if(tabsepFile) {
				tabsepChannel = Tcl_GetChannel(interp, tabsepFile, &channelMode);
				if(!tabsepChannel) {
					Tcl_AppendResult(interp, Tcl_ErrnoMsg(Tcl_GetErrno()), " converting ", tabsepFile, (char *)NULL);
					returnCode = TCL_ERROR;
					goto read_tabsep_cleanup_and_exit;
				}
				if (!(channelMode & TCL_READABLE)) {
					Tcl_AppendResult (interp, "File in -from argument must be readable", (char *)NULL);
					returnCode = TCL_ERROR;
					goto read_tabsep_cleanup_and_exit;
				}
				returnCode = Pg_sqlite_gets(interp, tabsepChannel, &rowObj);
				if(returnCode == TCL_OK) {
					row = Tcl_GetString(rowObj);
				} else {
					if (returnCode == TCL_BREAK)
						returnCode = TCL_OK;
					goto read_tabsep_cleanup_and_exit;
				}
			} else {
				row = tabsepRow;
			}

			if(recommitInterval) {
				if(Pg_sqlite_begin(interp, sqlite_db) == TCL_ERROR) {
					returnCode = TCL_ERROR;
					goto read_tabsep_cleanup_and_exit;
				}
			}

			if(Pg_sqlite_prepare(interp, sqlite_db, sqliteCode, &statement) != TCL_OK) {
				goto read_tabsep_cleanup_and_exit;
			}

			while(row) {
				if(cmdIndex == CMD_READ_KEYVAL) {
					int len;
					if (Pg_sqlite_split_keyval(interp, row, &columns, nColumns, sepString, columnNames, unknownObj) != TCL_OK) {
						returnCode = TCL_ERROR;
						break;
					}

					if(Tcl_ListObjLength(interp, unknownObj, &len) != TCL_OK) {
						returnCode = TCL_ERROR;
						break;
					}
					if(len && !unknownKey) {
						returnCode = TCL_ERROR;
						break;
					}
				} else {
					if (Pg_sqlite_split_tabsep(row, &columns, nColumns, sepString, nullString, &errorMessage) != TCL_OK) {
						returnCode = TCL_ERROR;
						break;
					}
					if(checkRow) {
						int check = Pg_sqlite_executeCheck(interp, sqlite_db, checkStatement, primaryKeyIndex, columnTypes, columns, nColumns);
						if(check == TCL_ERROR) {
							returnCode = TCL_ERROR;
							break;
						}
						if (check == TCL_CONTINUE) {
							goto next_row;
						}
					}
				}

				for(column = 0; column < nColumns; column++) {
					char *value = columns[column];
					if(!value)
						continue;

					int type = columnTypes ? columnTypes[column] : PG_SQLITE_TEXT;
					if (Pg_sqlite_bindValue(sqlite_db, statement, column, value, type, &errorMessage)) {
						returnCode = TCL_ERROR;
						break;
					}
				}

				if(cmdIndex == CMD_READ_KEYVAL && unknownKey) {
					char *value = Tcl_GetString(unknownObj);
					if(value[0]) {
						if (Pg_sqlite_bindValue(sqlite_db, statement, nColumns, value, PG_SQLITE_TEXT, &errorMessage) != TCL_OK) {
							returnCode = TCL_ERROR;
							break;
						}
					}
				}

				if (sqlite3_step(statement) != SQLITE_DONE) {
					errorMessage = sqlite3_errmsg(sqlite_db);
					returnCode = TCL_ERROR;
					break;
				}
				sqlite3_reset(statement);
				sqlite3_clear_bindings(statement);

				// Once we've imported any data, we'll keep the table.
				dropTable = NULL;

				totalTuples++;
				if(recommitInterval && (totalTuples % recommitInterval) == 0) {
					if(Pg_sqlite_recommit(interp, sqlite_db, sqliteCode, &statement) != TCL_OK) {
						returnCode = TCL_ERROR;
						goto read_tabsep_cleanup_and_exit;
					}
				}
				if(pollInterval && (totalTuples % pollInterval) == 0) {
					Tcl_DoOneEvent(0);
				}

			  next_row:
				if(tabsepFile) {
					row = NULL;
					returnCode = Pg_sqlite_gets(interp, tabsepChannel, &rowObj);
					if(returnCode == TCL_OK)
						row = Tcl_GetString(rowObj);
					else if(returnCode == TCL_BREAK)
						returnCode = TCL_OK;
				} else {
					row = NULL;
				}
			}

		  read_tabsep_cleanup_and_exit:

			if(statement) {
				sqlite3_finalize(statement);
				statement = NULL;
			}

			if(checkStatement) {
				sqlite3_finalize(checkStatement);
				checkStatement = NULL;
			}

			if(recommitInterval) {
				if(Pg_sqlite_commit(interp, sqlite_db) != TCL_OK)
					returnCode = TCL_ERROR;
			}

			if(columnTypes)
				ckfree((void *)columnTypes);

			if(columns)
				ckfree((void *)columns);

			if(rowObj)
				Tcl_DecrRefCount(rowObj);

			if(unknownObj)
				Tcl_DecrRefCount(unknownObj);

			if(sqliteCodeObj)
				Tcl_DecrRefCount(sqliteCodeObj);

			if(returnCode == TCL_ERROR) {
				if (errorMessage) {
					Tcl_AppendResult(interp, (char *)errorMessage, (char *)NULL);
				}

				if(dropTable) {
					if(Pg_sqlite_dropTable(interp, sqlite_db, dropTable) != TCL_OK)
						Tcl_AppendResult(interp, " while dropping table", (char *)NULL);
				}

				return TCL_ERROR;
			}

			Tcl_SetObjResult(interp, Tcl_NewIntObj(totalTuples));
			return returnCode;
		}

		case CMD_IMPORT_POSTGRES_RESULT: {
			char    *pghandle_name = Tcl_GetString(objv[3]);
			int      nTuples;
			int      tupleIndex;
			int      maxInt = 0;
			double   maxFloat = 0.0;
			char     maxString[BUFSIZ];
			int      maxValid = 0;
			PGconn   *conn = NULL;
			PGresult *result = NULL;

			if(rowbyrow) {
				conn = PgGetConnectionId(interp, pghandle_name, NULL);
				if(conn == NULL) {
					Tcl_AppendResult (interp, " while getting connection from ", pghandle_name, (char *)NULL);
					returnCode = TCL_ERROR;
					goto import_cleanup_and_exit;
				}
				PQsetSingleRowMode(conn);
				result = PQgetResult(conn);
			} else {
				result = PgGetResultId(interp, pghandle_name, NULL);
			}

			if(!result) {
				Tcl_AppendResult (interp, "Failed to get handle from ", pghandle_name, (char *)NULL);
				returnCode = TCL_ERROR;
				goto import_cleanup_and_exit;
			}

			if(Pg_sqlite_prepare(interp, sqlite_db, sqliteCode, &statement) != TCL_OK) {
				Tcl_AppendResult (interp, " while preparing ", sqliteCode, (char *)NULL);
				goto import_cleanup_and_exit;
			}

			if(recommitInterval) {
				if(Pg_sqlite_begin(interp, sqlite_db) == TCL_ERROR) {
					returnCode = TCL_ERROR;
					goto import_cleanup_and_exit;
				}
			}

			while(result) {
				status = PQresultStatus(result);

				if(status != PGRES_TUPLES_OK && status != PGRES_SINGLE_TUPLE) {
					errorMessage = PQresultErrorMessage(result);
					if (!*errorMessage)
						errorMessage = PQresStatus(status);
					returnCode = TCL_ERROR;
					break;
				}

				nTuples = PQntuples(result);

				for (tupleIndex = 0; tupleIndex < nTuples; tupleIndex++) {
					char **columns = (char **)ckalloc(nColumns * (sizeof *columns));
					int gotMax = 1;
					for(column = 0; column < nColumns; column++) {
						if(PQgetisnull(result, tupleIndex, column)) {
							columns[column] = NULL;
							if(maxColumn && column == maxColumnNumber) {
								gotMax = 0;
							}
						} else {
							columns[column] = PQgetvalue(result, tupleIndex, column);
							if(nullString && strcmp(columns[column], nullString) == 0)
								columns[column] = NULL;
						}
					}
					if(checkRow) {
						int check = Pg_sqlite_executeCheck(interp, sqlite_db, checkStatement, primaryKeyIndex, columnTypes, columns, nColumns);
						if(check == TCL_ERROR) {
							returnCode = TCL_ERROR;
							ckfree((void *)columns);
							goto import_cleanup_and_exit;
						}
						if (check == TCL_CONTINUE) {
							ckfree((void *)columns);
							continue;
						}
					}
					for(column = 0; column < nColumns; column++) {
						if (!columns[column])
							continue;

						int type = columnTypes ? columnTypes[column] : PG_SQLITE_TEXT;
						if (Pg_sqlite_bindValue(sqlite_db, statement, column, columns[column], type, &errorMessage) != TCL_OK) {
							returnCode = TCL_ERROR;
							ckfree((void *)columns);
							goto import_cleanup_and_exit;
						}
					}
					if(maxColumn && gotMax) {
						char *val = columns[maxColumnNumber];
						switch (maxColumnType) {
							case PG_SQLITE_TEXT: {
								if(!maxValid || strcmp(val, maxString) > 0) {
									strcpy(maxString, val);
									maxValid = 1;
								}
								break;
							}
							case PG_SQLITE_INT: {
								int valInt = atoi(val);
								if(!maxValid || valInt > maxInt) {
									maxInt = valInt;
									maxValid = 1;
								}
								break;
							}
							case PG_SQLITE_DOUBLE: {
								double valFloat = atof(val);
								if(!maxValid || valFloat > maxFloat) {
									maxFloat = valFloat;
									maxValid = 1;
								}
								break;
							}
						}
					}
					ckfree((void *)columns);
					columns = NULL;

					if (sqlite3_step(statement) != SQLITE_DONE) {
						errorMessage = sqlite3_errmsg(sqlite_db);
						returnCode = TCL_ERROR;
						goto import_cleanup_and_exit;
					}
					sqlite3_reset(statement);
					sqlite3_clear_bindings(statement);

					// Once we've imported any data, we'll keep the table.
					dropTable = NULL;

					totalTuples++;
					if(recommitInterval && (totalTuples % recommitInterval) == 0) {
						if(Pg_sqlite_recommit(interp, sqlite_db, sqliteCode, &statement) != TCL_OK) {
							returnCode = TCL_ERROR;
							goto import_cleanup_and_exit;
						}
					}
					if(pollInterval && (totalTuples % pollInterval) == 0) {
						Tcl_DoOneEvent(0);
					}
				}

				if(rowbyrow) {
					PQclear(result);
					result = PQgetResult(conn);
				} else {
					result = NULL;
				}
			}

		  import_cleanup_and_exit:

			if(rowbyrow) {
				while(result) {
					PQclear(result);
					if(!conn) break;
					result = PQgetResult(conn);
				}
			}

			if(statement) {
				sqlite3_finalize(statement);
				statement = NULL;
			}

			if(checkStatement) {
				sqlite3_finalize(checkStatement);
				checkStatement = NULL;
			}

			if(recommitInterval) {
				if(Pg_sqlite_commit(interp, sqlite_db) != TCL_OK)
					returnCode = TCL_ERROR;
			}

			if(columnTypes)
				ckfree((void *)columnTypes);

			if(sqliteCodeObj)
				Tcl_DecrRefCount(sqliteCodeObj);

			if(returnCode == TCL_ERROR) {
				if (errorMessage) {
					Tcl_AppendResult(interp, (char *)errorMessage, (char *)NULL);
				}

				if(dropTable) {
					if(Pg_sqlite_dropTable(interp, sqlite_db, dropTable) != TCL_OK)
						Tcl_AppendResult(interp, " while handling error", (char *)NULL);
				}

				return TCL_ERROR;
			}

			if(maxColumn) {
				if(maxValid) {
					Tcl_Obj *obj = NULL;

					switch (maxColumnType) {
						case PG_SQLITE_TEXT: {
							Tcl_IncrRefCount(obj = Tcl_NewStringObj(maxString, -1));
							break;
						}
						case PG_SQLITE_INT: {
							Tcl_IncrRefCount(obj = Tcl_NewIntObj(maxInt));
							break;
						}
						case PG_SQLITE_DOUBLE: {
							Tcl_IncrRefCount(obj = Tcl_NewDoubleObj(maxFloat));
							break;
						}
					}

					if(obj) {
						Tcl_SetVar2Ex(interp, maxVar, NULL, obj, 0);
						Tcl_DecrRefCount(obj);
						obj = NULL;
					}
				}
			}

			Tcl_SetObjResult(interp, Tcl_NewIntObj(totalTuples));
			return returnCode;
		}
	}

	return TCL_OK;
}