tdbc::mysql

Artifact [47de19173a]
Login

Artifact 47de19173a3e0d14336734ee590630ec00f8df82:


     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
   100
   101
   102
   103
   104
   105
   106
   107
   108
   109
   110
   111
   112
   113
   114
   115
   116
   117
   118
   119
   120
   121
   122
   123
   124
   125
   126
   127
   128
   129
   130
   131
   132
   133
   134
   135
   136
   137
   138
   139
   140
   141
   142
   143
   144
   145
   146
   147
   148
   149
   150
   151
   152
   153
   154
   155
   156
   157
   158
   159
   160
   161
   162
   163
   164
   165
   166
   167
   168
   169
   170
   171
   172
   173
   174
   175
   176
   177
   178
   179
   180
   181
   182
   183
   184
   185
   186
   187
   188
   189
   190
   191
   192
   193
   194
   195
   196
   197
   198
   199
   200
   201
   202
   203
   204
   205
   206
   207
   208
   209
   210
   211
   212
   213
   214
   215
   216
   217
   218
   219
   220
   221
   222
   223
   224
   225
   226
   227
   228
   229
   230
   231
   232
   233
   234
   235
   236
   237
   238
   239
   240
   241
   242
   243
   244
   245
   246
   247
   248
   249
   250
   251
   252
   253
   254
   255
   256
   257
   258
   259
   260
   261
   262
   263
   264
   265
   266
   267
   268
   269
   270
   271
   272
   273
   274
   275
   276
   277
   278
   279
   280
   281
   282
   283
   284
   285
   286
   287
   288
   289
   290
   291
   292
   293
   294
   295
   296
   297
   298
   299
   300
   301
   302
   303
   304
   305
   306
   307
   308
   309
   310
   311
   312
   313
   314
   315
   316
   317
   318
   319
   320
   321
   322
   323
   324
   325
   326
   327
   328
   329
   330
   331
   332
   333
   334
   335
   336
   337
   338
   339
   340
   341
   342
   343
   344
   345
   346
   347
   348
   349
   350
   351
   352
   353
   354
   355
   356
   357
   358
   359
   360
   361
   362
   363
   364
   365
   366
   367
   368
   369
   370
   371
   372
   373
   374
   375
   376
   377
   378
   379
   380
   381
   382
   383
   384
   385
   386
   387
   388
   389
   390
   391
   392
   393
   394
   395
   396
   397
   398
   399
   400
   401
   402
   403
   404
   405
   406
   407
   408
   409
   410
   411
   412
   413
   414
   415
   416
   417
   418
   419
   420
   421
   422
   423
   424
   425
   426
   427
   428
   429
   430
   431
   432
   433
   434
   435
   436
   437
   438
   439
   440
   441
   442
   443
   444
   445
   446
   447
   448
   449
   450
   451
   452
   453
   454
   455
   456
   457
   458
   459
   460
   461
   462
   463
   464
   465
   466
   467
   468
   469
   470
   471
   472
   473
   474
   475
   476
   477
   478
   479
   480
   481
   482
   483
   484
   485
   486
   487
   488
   489
   490
   491
   492
   493
   494
   495
   496
   497
   498
   499
   500
   501
   502
   503
   504
   505
   506
   507
   508
   509
   510
   511
   512
   513
   514
   515
   516
   517
   518
   519
   520
   521
   522
   523
   524
   525
   526
   527
   528
   529
   530
   531
   532
   533
   534
   535
   536
   537
   538
   539
   540
   541
   542
   543
   544
   545
   546
   547
   548
   549
   550
   551
   552
   553
   554
   555
   556
   557
   558
   559
   560
   561
   562
   563
   564
   565
   566
   567
   568
   569
   570
   571
   572
   573
   574
   575
   576
   577
   578
   579
   580
   581
   582
   583
   584
   585
   586
   587
   588
   589
   590
   591
   592
   593
   594
   595
   596
   597
   598
   599
   600
   601
   602
   603
   604
   605
   606
   607
   608
   609
   610
   611
   612
   613
   614
   615
   616
   617
   618
   619
   620
   621
   622
   623
   624
   625
   626
   627
   628
   629
   630
   631
   632
   633
   634
   635
   636
   637
   638
   639
   640
   641
   642
   643
   644
   645
   646
   647
   648
   649
   650
   651
   652
   653
   654
   655
   656
   657
   658
   659
   660
   661
   662
   663
   664
   665
   666
   667
   668
   669
   670
   671
   672
   673
   674
   675
   676
   677
   678
   679
   680
   681
   682
   683
   684
   685
   686
   687
   688
   689
   690
   691
   692
   693
   694
   695
   696
   697
   698
   699
   700
   701
   702
   703
   704
   705
   706
   707
   708
   709
   710
   711
   712
   713
   714
   715
   716
   717
   718
   719
   720
   721
   722
   723
   724
   725
   726
   727
   728
   729
   730
   731
   732
   733
   734
   735
   736
   737
   738
   739
   740
   741
   742
   743
   744
   745
   746
   747
   748
   749
   750
   751
   752
   753
   754
   755
   756
   757
   758
   759
   760
   761
   762
   763
   764
   765
   766
   767
   768
   769
   770
   771
   772
   773
   774
   775
   776
   777
   778
   779
   780
   781
   782
   783
   784
   785
   786
   787
   788
   789
   790
   791
   792
   793
   794
   795
   796
   797
   798
   799
   800
   801
   802
   803
   804
   805
   806
   807
   808
   809
   810
   811
   812
   813
   814
   815
   816
   817
   818
   819
   820
   821
   822
   823
   824
   825
   826
   827
   828
   829
   830
   831
   832
   833
   834
   835
   836
   837
   838
   839
   840
   841
   842
   843
   844
   845
   846
   847
   848
   849
   850
   851
   852
   853
   854
   855
   856
   857
   858
   859
   860
   861
   862
   863
   864
   865
   866
   867
   868
   869
   870
   871
   872
   873
   874
   875
   876
   877
   878
   879
   880
   881
   882
   883
   884
   885
   886
   887
   888
   889
   890
   891
   892
   893
   894
   895
   896
   897
   898
   899
   900
   901
   902
   903
   904
   905
   906
   907
   908
   909
   910
   911
   912
   913
   914
   915
   916
   917
   918
   919
   920
   921
   922
   923
   924
   925
   926
   927
   928
   929
   930
   931
   932
   933
   934
   935
   936
   937
   938
   939
   940
   941
   942
   943
   944
   945
   946
   947
   948
   949
   950
   951
   952
   953
   954
   955
   956
   957
   958
   959
   960
   961
   962
   963
   964
   965
   966
   967
   968
   969
   970
   971
   972
   973
   974
   975
   976
   977
   978
   979
   980
   981
   982
   983
   984
   985
   986
   987
   988
   989
   990
   991
   992
   993
   994
   995
   996
   997
   998
   999
  1000
  1001
  1002
  1003
  1004
  1005
  1006
  1007
  1008
  1009
  1010
  1011
  1012
  1013
  1014
  1015
  1016
  1017
  1018
  1019
  1020
  1021
  1022
  1023
  1024
  1025
  1026
  1027
  1028
  1029
  1030
  1031
  1032
  1033
  1034
  1035
  1036
  1037
  1038
  1039
  1040
  1041
  1042
  1043
  1044
  1045
  1046
  1047
  1048
  1049
  1050
  1051
  1052
  1053
  1054
  1055
  1056
  1057
  1058
  1059
  1060
  1061
  1062
  1063
  1064
  1065
  1066
  1067
  1068
  1069
  1070
  1071
  1072
  1073
  1074
  1075
  1076
  1077
  1078
  1079
  1080
  1081
  1082
  1083
  1084
  1085
  1086
  1087
  1088
  1089
  1090
  1091
  1092
  1093
  1094
  1095
  1096
  1097
  1098
  1099
  1100
  1101
  1102
  1103
  1104
  1105
  1106
  1107
  1108
  1109
  1110
  1111
  1112
  1113
  1114
  1115
  1116
  1117
  1118
  1119
  1120
  1121
  1122
  1123
  1124
  1125
  1126
  1127
  1128
  1129
  1130
  1131
  1132
  1133
  1134
  1135
  1136
  1137
  1138
  1139
  1140
  1141
  1142
  1143
  1144
  1145
  1146
  1147
  1148
  1149
  1150
  1151
  1152
  1153
  1154
  1155
  1156
  1157
  1158
  1159
  1160
  1161
  1162
  1163
  1164
  1165
  1166
  1167
  1168
  1169
  1170
  1171
  1172
  1173
  1174
  1175
  1176
  1177
  1178
  1179
  1180
  1181
  1182
  1183
  1184
  1185
  1186
  1187
  1188
  1189
  1190
  1191
  1192
  1193
  1194
  1195
  1196
  1197
  1198
  1199
  1200
  1201
  1202
  1203
  1204
  1205
  1206
  1207
  1208
  1209
  1210
  1211
  1212
  1213
  1214
  1215
  1216
  1217
  1218
  1219
  1220
  1221
  1222
  1223
  1224
  1225
  1226
  1227
  1228
  1229
  1230
  1231
  1232
  1233
  1234
  1235
  1236
  1237
  1238
  1239
  1240
  1241
  1242
  1243
  1244
  1245
  1246
  1247
  1248
  1249
  1250
  1251
  1252
  1253
  1254
  1255
  1256
  1257
  1258
  1259
  1260
  1261
  1262
  1263
  1264
  1265
  1266
  1267
  1268
  1269
  1270
  1271
  1272
  1273
  1274
  1275
  1276
  1277
  1278
  1279
  1280
  1281
  1282
  1283
  1284
  1285
  1286
  1287
  1288
  1289
  1290
  1291
  1292
  1293
  1294
  1295
  1296
  1297
  1298
  1299
  1300
  1301
  1302
  1303
  1304
  1305
  1306
  1307
  1308
  1309
  1310
  1311
  1312
  1313
  1314
  1315
  1316
  1317
  1318
  1319
  1320
  1321
  1322
  1323
  1324
  1325
  1326
  1327
  1328
  1329
  1330
  1331
  1332
  1333
  1334
  1335
  1336
  1337
  1338
  1339
  1340
  1341
  1342
  1343
  1344
  1345
  1346
  1347
  1348
  1349
  1350
  1351
  1352
  1353
  1354
  1355
  1356
  1357
  1358
  1359
  1360
  1361
  1362
  1363
  1364
  1365
  1366
  1367
  1368
  1369
  1370
  1371
  1372
  1373
  1374
  1375
  1376
  1377
  1378
  1379
  1380
  1381
  1382
  1383
  1384
  1385
  1386
  1387
  1388
  1389
  1390
  1391
  1392
  1393
  1394
  1395
  1396
  1397
  1398
  1399
  1400
  1401
  1402
  1403
  1404
  1405
  1406
  1407
  1408
  1409
  1410
  1411
  1412
  1413
  1414
  1415
  1416
  1417
  1418
  1419
  1420
  1421
  1422
  1423
  1424
  1425
  1426
  1427
  1428
  1429
  1430
  1431
  1432
  1433
  1434
  1435
  1436
  1437
  1438
  1439
  1440
  1441
  1442
  1443
  1444
  1445
  1446
  1447
  1448
  1449
  1450
  1451
  1452
  1453
  1454
  1455
  1456
  1457
  1458
  1459
  1460
  1461
  1462
  1463
  1464
  1465
  1466
  1467
  1468
  1469
  1470
  1471
  1472
  1473
  1474
  1475
  1476
  1477
  1478
  1479
  1480
  1481
  1482
  1483
  1484
  1485
  1486
  1487
  1488
  1489
  1490
  1491
  1492
  1493
  1494
  1495
  1496
  1497
  1498
  1499
  1500
  1501
  1502
  1503
  1504
  1505
  1506
  1507
  1508
  1509
  1510
  1511
  1512
  1513
  1514
  1515
  1516
  1517
  1518
  1519
  1520
  1521
  1522
  1523
  1524
  1525
  1526
  1527
  1528
  1529
  1530
  1531
  1532
  1533
  1534
  1535
  1536
  1537
  1538
  1539
  1540
  1541
  1542
  1543
  1544
  1545
  1546
  1547
  1548
  1549
  1550
  1551
  1552
  1553
  1554
  1555
  1556
  1557
  1558
  1559
  1560
  1561
  1562
  1563
  1564
  1565
  1566
  1567
  1568
  1569
  1570
  1571
  1572
  1573
  1574
  1575
  1576
  1577
  1578
  1579
  1580
  1581
  1582
  1583
  1584
  1585
  1586
  1587
  1588
  1589
  1590
  1591
  1592
  1593
  1594
  1595
  1596
  1597
  1598
  1599
  1600
  1601
  1602
  1603
  1604
  1605
  1606
  1607
  1608
  1609
  1610
  1611
  1612
  1613
  1614
  1615
  1616
  1617
  1618
  1619
  1620
  1621
  1622
  1623
  1624
  1625
  1626
  1627
  1628
  1629
  1630
  1631
  1632
  1633
  1634
  1635
  1636
  1637
  1638
  1639
  1640
  1641
  1642
  1643
  1644
  1645
  1646
  1647
  1648
  1649
  1650
  1651
  1652
  1653
  1654
  1655
  1656
  1657
  1658
  1659
  1660
  1661
  1662
  1663
  1664
  1665
  1666
  1667
  1668
  1669
  1670
  1671
  1672
  1673
  1674
  1675
  1676
  1677
  1678
  1679
  1680
  1681
  1682
  1683
  1684
  1685
  1686
  1687
  1688
  1689
  1690
  1691
  1692
  1693
  1694
  1695
  1696
  1697
  1698
  1699
  1700
  1701
  1702
  1703
  1704
  1705
  1706
  1707
  1708
  1709
  1710
  1711
  1712
  1713
  1714
  1715
  1716
  1717
  1718
  1719
  1720
  1721
  1722
  1723
  1724
  1725
  1726
  1727
  1728
  1729
  1730
  1731
  1732
  1733
  1734
  1735
  1736
  1737
  1738
  1739
  1740
  1741
  1742
  1743
  1744
  1745
  1746
  1747
  1748
  1749
  1750
  1751
  1752
  1753
  1754
  1755
  1756
  1757
  1758
  1759
  1760
  1761
  1762
  1763
  1764
  1765
  1766
  1767
  1768
  1769
  1770
  1771
  1772
  1773
  1774
  1775
  1776
  1777
  1778
  1779
  1780
  1781
  1782
  1783
  1784
  1785
  1786
  1787
  1788
  1789
  1790
  1791
  1792
  1793
  1794
  1795
  1796
  1797
  1798
  1799
  1800
  1801
  1802
  1803
  1804
  1805
  1806
  1807
  1808
  1809
  1810
  1811
  1812
  1813
  1814
  1815
  1816
  1817
  1818
  1819
  1820
  1821
  1822
  1823
  1824
  1825
  1826
  1827
  1828
  1829
  1830
  1831
  1832
  1833
  1834
  1835
  1836
  1837
  1838
  1839
  1840
  1841
  1842
  1843
  1844
  1845
  1846
  1847
  1848
  1849
  1850
  1851
  1852
  1853
  1854
  1855
  1856
  1857
  1858
  1859
  1860
  1861
  1862
  1863
  1864
  1865
  1866
  1867
  1868
  1869
  1870
  1871
  1872
  1873
  1874
  1875
  1876
  1877
  1878
  1879
  1880
  1881
  1882
  1883
  1884
  1885
  1886
  1887
  1888
  1889
  1890
  1891
  1892
  1893
  1894
  1895
  1896
  1897
  1898
  1899
  1900
  1901
  1902
  1903
  1904
  1905
  1906
  1907
  1908
  1909
  1910
  1911
  1912
  1913
  1914
  1915
  1916
  1917
  1918
  1919
  1920
  1921
  1922
  1923
  1924
  1925
  1926
  1927
  1928
  1929
  1930
  1931
  1932
  1933
  1934
  1935
  1936
  1937
  1938
  1939
  1940
  1941
  1942
  1943
  1944
  1945
  1946
  1947
  1948
  1949
  1950
  1951
  1952
  1953
  1954
  1955
  1956
  1957
  1958
  1959
  1960
  1961
  1962
  1963
  1964
  1965
  1966
  1967
  1968
  1969
  1970
  1971
  1972
  1973
  1974
  1975
  1976
  1977
  1978
  1979
  1980
  1981
  1982
  1983
  1984
  1985
  1986
  1987
  1988
  1989
  1990
  1991
  1992
  1993
  1994
  1995
  1996
  1997
  1998
  1999
  2000
  2001
  2002
  2003
  2004
  2005
  2006
  2007
  2008
  2009
  2010
  2011
  2012
  2013
  2014
  2015
  2016
  2017
  2018
  2019
  2020
  2021
  2022
  2023
  2024
  2025
  2026
  2027
  2028
  2029
  2030
  2031
  2032
  2033
  2034
  2035
  2036
  2037
  2038
  2039
  2040
  2041
  2042
  2043
  2044
  2045
  2046
  2047
  2048
  2049
  2050
  2051
  2052
  2053
  2054
  2055
  2056
  2057
  2058
  2059
  2060
  2061
  2062
  2063
  2064
  2065
  2066
  2067
  2068
  2069
  2070
  2071
  2072
  2073
  2074
  2075
  2076
  2077
  2078
  2079
  2080
  2081
  2082
  2083
  2084
  2085
  2086
  2087
  2088
  2089
  2090
  2091
  2092
  2093
  2094
  2095
  2096
  2097
  2098
  2099
  2100
  2101
  2102
  2103
  2104
  2105
  2106
  2107
  2108
  2109
  2110
  2111
  2112
  2113
  2114
  2115
  2116
  2117
  2118
  2119
  2120
  2121
  2122
  2123
  2124
  2125
  2126
  2127
  2128
  2129
  2130
  2131
  2132
  2133
  2134
  2135
  2136
  2137
  2138
  2139
  2140
  2141
  2142
  2143
  2144
  2145
  2146
  2147
  2148
  2149
  2150
  2151
  2152
  2153
  2154
  2155
  2156
  2157
  2158
  2159
  2160
  2161
  2162
  2163
  2164
  2165
  2166
  2167
  2168
  2169
  2170
  2171
  2172
  2173
  2174
  2175
  2176
  2177
  2178
  2179
  2180
  2181
  2182
  2183
  2184
  2185
  2186
  2187
  2188
  2189
  2190
  2191
  2192
  2193
  2194
  2195
  2196
  2197
  2198
  2199
  2200
  2201
  2202
  2203
  2204
  2205
  2206
  2207
  2208
  2209
  2210
  2211
  2212
  2213
  2214
  2215
  2216
  2217
  2218
  2219
  2220
  2221
  2222
  2223
  2224
  2225
  2226
  2227
  2228
  2229
  2230
  2231
  2232
  2233
  2234
  2235
  2236
  2237
  2238
  2239
  2240
  2241
  2242
  2243
  2244
  2245
  2246
  2247
  2248
  2249
  2250
  2251
  2252
  2253
  2254
  2255
  2256
  2257
  2258
  2259
  2260
  2261
  2262
  2263
  2264
  2265
  2266
  2267
  2268
  2269
  2270
  2271
  2272
  2273
  2274
  2275
  2276
  2277
  2278
  2279
  2280
  2281
  2282
  2283
  2284
  2285
  2286
  2287
  2288
  2289
  2290
  2291
  2292
  2293
  2294
  2295
  2296
  2297
  2298
  2299
  2300
  2301
  2302
  2303
  2304
  2305
  2306
  2307
  2308
  2309
  2310
  2311
  2312
  2313
  2314
  2315
  2316
  2317
  2318
  2319
  2320
  2321
  2322
  2323
  2324
  2325
  2326
  2327
  2328
  2329
  2330
  2331
  2332
  2333
  2334
  2335
  2336
  2337
  2338
  2339
  2340
  2341
  2342
  2343
  2344
  2345
  2346
  2347
  2348
  2349
  2350
  2351
  2352
  2353
  2354
  2355
  2356
  2357
  2358
  2359
  2360
  2361
  2362
  2363
  2364
  2365
  2366
  2367
  2368
  2369
  2370
  2371
  2372
  2373
  2374
  2375
  2376
  2377
  2378
  2379
  2380
  2381
  2382
  2383
  2384
  2385
  2386
  2387
  2388
  2389
  2390
  2391
  2392
  2393
  2394
  2395
  2396
  2397
  2398
  2399
  2400
  2401
  2402
  2403
  2404
  2405
  2406
  2407
  2408
  2409
  2410
  2411
  2412
  2413
  2414
  2415
  2416
  2417
  2418
  2419
  2420
  2421
  2422
  2423
  2424
  2425
  2426
  2427
  2428
  2429
  2430
  2431
  2432
  2433
  2434
  2435
  2436
  2437
  2438
  2439
  2440
  2441
  2442
  2443
  2444
  2445
  2446
  2447
  2448
  2449
  2450
  2451
  2452
  2453
  2454
  2455
  2456
  2457
  2458
  2459
  2460
  2461
  2462
  2463
  2464
  2465
  2466
  2467
  2468
  2469
  2470
  2471
  2472
  2473
  2474
  2475
  2476
  2477
  2478
  2479
  2480
  2481
  2482
  2483
  2484
  2485
  2486
  2487
  2488
  2489
  2490
  2491
  2492
  2493
  2494
  2495
  2496
  2497
  2498
  2499
  2500
  2501
  2502
  2503
  2504
  2505
  2506
  2507
  2508
  2509
  2510
  2511
  2512
  2513
  2514
  2515
  2516
  2517
  2518
  2519
  2520
  2521
  2522
  2523
  2524
  2525
  2526
  2527
  2528
  2529
  2530
  2531
  2532
  2533
  2534
  2535
  2536
  2537
  2538
  2539
  2540
  2541
  2542
  2543
  2544
  2545
  2546
  2547
  2548
  2549
  2550
  2551
  2552
  2553
  2554
  2555
  2556
  2557
  2558
  2559
  2560
  2561
  2562
  2563
  2564
  2565
  2566
  2567
  2568
  2569
  2570
  2571
  2572
  2573
  2574
  2575
  2576
  2577
  2578
  2579
  2580
  2581
  2582
  2583
  2584
  2585
  2586
  2587
  2588
  2589
  2590
  2591
  2592
  2593
  2594
  2595
  2596
  2597
  2598
  2599
  2600
  2601
  2602
  2603
  2604
  2605
  2606
  2607
  2608
  2609
  2610
  2611
  2612
  2613
  2614
  2615
  2616
  2617
  2618
  2619
  2620
  2621
  2622
  2623
  2624
  2625
  2626
  2627
  2628
  2629
  2630
  2631
  2632
  2633
  2634
  2635
  2636
  2637
  2638
  2639
  2640
  2641
  2642
  2643
  2644
  2645
  2646
  2647
  2648
  2649
  2650
  2651
  2652
  2653
  2654
  2655
  2656
  2657
  2658
  2659
  2660
  2661
  2662
  2663
  2664
  2665
  2666
  2667
  2668
  2669
  2670
  2671
  2672
  2673
  2674
  2675
  2676
  2677
  2678
  2679
  2680
  2681
  2682
  2683
  2684
  2685
  2686
  2687
  2688
  2689
  2690
  2691
  2692
  2693
  2694
  2695
  2696
  2697
  2698
  2699
  2700
  2701
  2702
  2703
  2704
  2705
  2706
  2707
  2708
  2709
  2710
  2711
  2712
  2713
  2714
  2715
  2716
  2717
  2718
  2719
  2720
  2721
  2722
  2723
  2724
  2725
  2726
  2727
  2728
  2729
  2730
  2731
  2732
  2733
  2734
  2735
  2736
  2737
  2738
  2739
  2740
  2741
  2742
  2743
  2744
  2745
  2746
  2747
  2748
  2749
  2750
  2751
  2752
  2753
  2754
  2755
  2756
  2757
  2758
  2759
  2760
  2761
  2762
  2763
  2764
  2765
  2766
  2767
  2768
  2769
  2770
  2771
  2772
  2773
  2774
  2775
  2776
  2777
  2778
  2779
  2780
  2781
  2782
  2783
  2784
  2785
  2786
  2787
  2788
  2789
  2790
  2791
  2792
  2793
  2794
  2795
  2796
  2797
  2798
  2799
  2800
  2801
  2802
  2803
  2804
  2805
  2806
  2807
  2808
  2809
  2810
  2811
  2812
  2813
  2814
  2815
  2816
  2817
  2818
  2819
  2820
  2821
  2822
  2823
  2824
  2825
  2826
  2827
  2828
  2829
  2830
  2831
  2832
  2833
  2834
  2835
  2836
  2837
  2838
  2839
  2840
  2841
  2842
  2843
  2844
  2845
  2846
  2847
  2848
  2849
  2850
  2851
  2852
  2853
  2854
  2855
  2856
  2857
  2858
  2859
  2860
  2861
  2862
  2863
  2864
  2865
  2866
  2867
  2868
  2869
  2870
  2871
  2872
  2873
  2874
  2875
  2876
  2877
  2878
  2879
  2880
  2881
  2882
  2883
  2884
  2885
  2886
  2887
  2888
  2889
  2890
  2891
  2892
  2893
  2894
  2895
  2896
  2897
  2898
  2899
  2900
  2901
  2902
  2903
  2904
  2905
  2906
  2907
  2908
  2909
  2910
  2911
  2912
  2913
  2914
  2915
  2916
  2917
  2918
  2919
  2920
  2921
  2922
  2923
  2924
  2925
  2926
  2927
  2928
  2929
  2930
  2931
  2932
  2933
  2934
  2935
  2936
  2937
  2938
  2939
  2940
  2941
  2942
  2943
  2944
  2945
  2946
  2947
  2948
  2949
  2950
  2951
  2952
  2953
  2954
  2955
  2956
  2957
  2958
  2959
  2960
  2961
  2962
  2963
  2964
  2965
  2966
  2967
  2968
  2969
  2970
  2971
  2972
  2973
  2974
  2975
  2976
  2977
  2978
  2979
  2980
  2981
  2982
  2983
  2984
  2985
  2986
  2987
  2988
  2989
  2990
  2991
  2992
  2993
  2994
  2995
  2996
  2997
  2998
  2999
  3000
  3001
  3002
  3003
  3004
  3005
  3006
  3007
  3008
  3009
  3010
  3011
  3012
  3013
  3014
  3015
  3016
  3017
  3018
  3019
  3020
  3021
  3022
  3023
  3024
  3025
  3026
  3027
  3028
  3029
  3030
  3031
  3032
  3033
  3034
  3035
  3036
  3037
  3038
  3039
  3040
  3041
  3042
  3043
  3044
  3045
  3046
  3047
  3048
  3049
  3050
  3051
  3052
  3053
  3054
  3055
  3056
  3057
  3058
  3059
  3060
  3061
  3062
  3063
  3064
  3065
  3066
  3067
  3068
  3069
  3070
  3071
  3072
  3073
  3074
  3075
  3076
  3077
  3078
  3079
  3080
  3081
  3082
  3083
  3084
  3085
  3086
  3087
  3088
  3089
  3090
  3091
  3092
  3093
  3094
  3095
  3096
  3097
  3098
  3099
  3100
  3101
  3102
  3103
  3104
  3105
  3106
  3107
  3108
  3109
  3110
  3111
  3112
  3113
  3114
  3115
  3116
  3117
  3118
  3119
  3120
  3121
  3122
  3123
  3124
  3125
  3126
  3127
  3128
  3129
  3130
  3131
  3132
  3133
  3134
  3135
  3136
  3137
  3138
  3139
  3140
  3141
  3142
  3143
  3144
  3145
  3146
  3147
  3148
  3149
  3150
  3151
  3152
  3153
  3154
  3155
  3156
  3157
  3158
  3159
  3160
  3161
  3162
  3163
  3164
  3165
  3166
  3167
  3168
  3169
  3170
  3171
  3172
  3173
  3174
  3175
  3176
  3177
  3178
  3179
  3180
  3181
  3182
  3183
  3184
  3185
  3186
  3187
  3188
  3189
  3190
  3191
  3192
  3193
  3194
  3195
  3196
  3197
  3198
  3199
  3200
  3201
  3202
  3203
  3204
  3205
  3206
  3207
  3208
  3209
  3210
  3211
  3212
  3213
  3214
  3215
  3216
  3217
  3218
  3219
  3220
  3221
  3222
  3223
  3224
  3225
  3226
  3227
  3228
  3229
  3230
  3231
  3232
  3233
  3234
  3235
  3236
  3237
  3238
  3239
  3240
  3241
  3242
  3243
  3244
  3245
  3246
  3247
  3248
  3249
  3250
  3251
  3252
  3253
  3254
  3255
  3256
  3257
  3258
  3259
  3260
  3261
  3262
  3263
  3264
  3265
  3266
  3267
  3268
  3269
  3270
  3271
  3272
  3273
  3274
  3275
  3276
  3277
  3278
  3279
  3280
  3281
  3282
  3283
  3284
  3285
  3286
  3287
  3288
  3289
  3290
  3291
  3292
  3293
  3294
  3295
  3296
  3297
  3298
  3299
  3300
  3301
  3302
  3303
  3304
  3305
  3306
  3307
  3308
  3309
  3310
  3311
  3312
  3313
  3314
  3315
  3316
  3317
  3318
  3319
  3320
  3321
  3322
  3323
  3324
  3325
  3326
  3327
  3328
  3329
  3330
  3331
  3332
  3333
  3334
  3335
  3336
  3337
  3338
  3339
  3340
  3341
  3342
  3343
  3344
  3345
  3346
  3347
  3348
  3349
  3350
  3351
  3352
  3353
  3354
  3355
  3356
  3357
  3358
  3359
  3360
  3361
  3362
  3363
  3364
  3365
  3366
  3367
  3368
  3369
  3370
  3371
  3372
  3373
  3374
  3375
  3376
  3377
  3378
  3379
  3380
  3381
  3382
  3383
  3384
  3385
  3386
  3387
  3388
  3389
  3390
  3391
  3392
  3393
  3394
  3395
  3396
  3397
  3398
  3399
  3400
  3401
  3402
  3403
  3404
  3405
  3406
  3407
  3408
  3409
  3410
  3411
  3412
  3413
  3414
  3415
  3416
  3417
  3418
  3419
  3420
  3421
  3422
  3423
  3424
  3425
  3426
  3427
  3428
  3429
  3430
  3431
  3432
  3433
  3434
  3435
  3436
  3437
  3438
  3439
  3440
  3441
  3442
  3443
  3444
  3445
  3446
  3447
  3448
  3449
  3450
  3451
  3452
  3453
  3454
  3455
  3456
  3457
  3458
  3459
  3460
  3461
  3462
  3463
  3464
  3465
  3466
  3467
  3468
  3469
  3470
  3471
  3472
  3473
  3474
  3475
  3476
  3477
  3478
  3479
  3480
  3481
  3482
  3483
  3484
  3485
  3486
  3487
  3488
  3489
  3490
  3491
  3492
  3493
  3494
  3495
  3496
  3497
  3498
  3499
  3500
  3501
  3502
  3503
  3504
  3505
  3506
  3507
  3508
  3509
  3510
  3511
  3512
  3513
  3514
  3515
  3516
  3517
  3518
  3519
  3520
  3521
  3522
  3523
  3524
  3525
  3526
  3527
  3528
  3529
  3530
  3531
  3532
  3533
  3534
  3535
  3536
  3537
  3538
  3539
  3540
  3541
  3542
  3543
  3544
  3545
  3546
  3547
  3548
  3549
  3550
  3551
  3552
  3553
  3554
  3555
  3556
  3557
  3558
  3559
  3560
  3561
  3562
  3563
  3564
  3565
  3566
  3567
  3568
  3569
  3570
  3571
  3572
  3573
  3574
  3575
  3576
  3577
  3578
  3579
  3580
  3581
  3582
  3583
  3584
  3585
  3586
  3587
  3588
  3589
  3590
  3591
  3592
  3593
  3594
  3595
  3596
  3597
  3598
  3599
  3600
  3601
  3602
  3603
  3604
  3605
  3606
  3607
  3608
  3609
  3610
  3611
  3612
  3613
  3614
  3615
  3616
  3617
  3618
  3619
  3620
  3621
  3622
  3623
  3624
  3625
  3626
  3627
  3628
  3629
  3630
  3631
  3632
  3633
  3634
  3635
  3636
  3637
  3638
  3639
  3640
  3641
  3642
  3643
  3644
  3645
  3646
  3647
  3648
  3649
  3650
  3651
  3652
  3653
  3654
  3655
  3656
  3657
  3658
  3659
  3660
  3661
  3662
  3663
  3664
  3665
  3666
  3667
  3668
  3669
  3670
  3671
  3672
  3673
  3674
  3675
  3676
  3677
  3678
  3679
  3680
  3681
  3682
  3683
  3684
  3685
  3686
  3687
  3688
  3689
  3690
  3691
  3692
  3693
  3694
  3695
  3696
  3697
  3698
  3699
  3700
  3701
  3702
  3703
  3704
  3705
  3706
  3707
  3708
  3709
  3710
  3711
  3712
  3713
  3714
  3715
  3716
  3717
  3718
  3719
  3720
  3721
  3722
  3723
  3724
  3725
  3726
  3727
  3728
  3729
  3730
  3731
  3732
  3733
  3734
  3735
  3736
  3737
  3738
  3739
  3740
  3741
  3742
  3743
  3744
  3745
  3746
  3747
  3748
  3749
  3750
  3751
  3752
  3753
  3754
  3755
  3756
  3757
  3758
/*
 * tdbcmysql.c --
 *
 *	Bridge between TDBC (Tcl DataBase Connectivity) and MYSQL.
 *
 * Copyright (c) 2008, 2009 by Kevin B. Kenny.
 *
 * Please refer to the file, 'license.terms' for the conditions on
 * redistribution of this file and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * $Id: $
 *
 *-----------------------------------------------------------------------------
 */

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <tcl.h>
#include <tclOO.h>
#include <tdbc.h>

#include <stdio.h>
#include <string.h>

#include "fakemysql.h"

/* Static data contained in this file */

TCL_DECLARE_MUTEX(mysqlMutex);	/* Mutex protecting the global environment
				 * and its reference count */

static int mysqlRefCount = 0;	/* Reference count on the global environment */
Tcl_LoadHandle mysqlLoadHandle = NULL;
				/* Handle to the MySQL library */
unsigned long mysqlClientVersion;
				/* Version number of MySQL */

/*
 * Objects to create within the literal pool
 */

const char* LiteralValues[] = {
    "",
    "0",
    "1",
    "direction",
    "in",
    "inout",
    "name",
    "nullable",
    "out",
    "precision",
    "scale",
    "type",
    NULL
};
enum LiteralIndex {
    LIT_EMPTY,
    LIT_0,
    LIT_1,
    LIT_DIRECTION,
    LIT_IN,
    LIT_INOUT,
    LIT_NAME,
    LIT_NULLABLE,
    LIT_OUT,
    LIT_PRECISION,
    LIT_SCALE,
    LIT_TYPE,
    LIT__END
};

/*
 * Structure that holds per-interpreter data for the MYSQL package.
 */

typedef struct PerInterpData {
    int refCount;		/* Reference count */
    Tcl_Obj* literals[LIT__END];
				/* Literal pool */
    Tcl_HashTable typeNumHash;	/* Lookup table for type numbers */
} PerInterpData;
#define IncrPerInterpRefCount(x)  \
    do {			  \
	++((x)->refCount);	  \
    } while(0)
#define DecrPerInterpRefCount(x)		\
    do {					\
	PerInterpData* _pidata = x;		\
	if ((--(_pidata->refCount)) <= 0) {	\
	    DeletePerInterpData(_pidata);	\
	}					\
    } while(0)

/*
 * Structure that carries the data for an MYSQL connection
 *
 * 	The ConnectionData structure is refcounted to simplify the
 *	destruction of statements associated with a connection.
 *	When a connection is destroyed, the subordinate namespace that
 *	contains its statements is taken down, destroying them. It's
 *	not safe to take down the ConnectionData until nothing is
 *	referring to it, which avoids taking down the hDBC until the
 *	other objects that refer to it vanish.
 */

typedef struct ConnectionData {
    int refCount;		/* Reference count. */
    PerInterpData* pidata;	/* Per-interpreter data */
    MYSQL* mysqlPtr;		/* MySql connection handle */
    unsigned int nCollations;	/* Number of collations defined */
    int* collationSizes;	/* Character lengths indexed by collation ID */
    int flags;
} ConnectionData;

/*
 * Flags for the state of an MYSQL connection
 */

#define CONN_FLAG_AUTOCOMMIT	0x1	/* Autocommit is set */
#define CONN_FLAG_IN_XCN	0x2 	/* Transaction is in progress */
#define CONN_FLAG_INTERACTIVE	0x4	/* -interactive requested at connect */

#define IncrConnectionRefCount(x) \
    do {			  \
	++((x)->refCount);	  \
    } while(0)
#define DecrConnectionRefCount(x)		\
    do {					\
	ConnectionData* conn = x;		\
	if ((--(conn->refCount)) <= 0) {	\
	    DeleteConnection(conn);		\
	}					\
    } while(0)

/*
 * Structure that carries the data for a MySQL prepared statement.
 *
 *	Just as with connections, statements need to defer taking down
 *	their client data until other objects (i.e., result sets) that
 * 	refer to them have had a chance to clean up. Hence, this
 *	structure is reference counted as well.
 */

typedef struct StatementData {
    int refCount;		/* Reference count */
    ConnectionData* cdata;	/* Data for the connection to which this
				 * statement pertains. */
    Tcl_Obj* subVars;	        /* List of variables to be substituted, in the
				 * order in which they appear in the
				 * statement */
    struct ParamData *params;	/* Data types and attributes of parameters */
    Tcl_Obj* nativeSql;		/* Native SQL statement to pass into
				 * MySQL */
    MYSQL_STMT* stmtPtr;	/* MySQL statement handle */
    MYSQL_RES* metadataPtr;	/* MySQL result set metadata */
    Tcl_Obj* columnNames;	/* Column names in the result set */
    int flags;
} StatementData;
#define IncrStatementRefCount(x)		\
    do {					\
	++((x)->refCount);			\
    } while (0)
#define DecrStatementRefCount(x)		\
    do {					\
	StatementData* stmt = (x);		\
	if (--(stmt->refCount) <= 0) {		\
	    DeleteStatement(stmt);		\
	}					\
    } while(0)

/* Flags in the 'StatementData->flags' word */

#define STMT_FLAG_BUSY		0x1	/* Statement handle is in use */

/*
 * Structure describing the data types of substituted parameters in
 * a SQL statement.
 */

typedef struct ParamData {
    int flags;			/* Flags regarding the parameters - see below */
    int dataType;		/* Data type */
    int precision;		/* Size of the expected data */
    int scale;			/* Digits after decimal point of the
				 * expected data */
} ParamData;

#define PARAM_KNOWN	1<<0	/* Something is known about the parameter */
#define PARAM_IN 	1<<1	/* Parameter is an input parameter */
#define PARAM_OUT 	1<<2	/* Parameter is an output parameter */
				/* (Both bits are set if parameter is
				 * an INOUT parameter) */
#define PARAM_BINARY	1<<3	/* Parameter is binary */

/*
 * Structure describing a MySQL result set.  The object that the Tcl
 * API terms a "result set" actually has to be represented by a MySQL
 * "statement", since a MySQL statement can have only one set of results
 * at any given time.
 */

typedef struct ResultSetData {
    int refCount;		/* Reference count */
    StatementData* sdata;	/* Statement that generated this result set */
    MYSQL_STMT* stmtPtr;	/* Handle to the MySQL statement object */
    Tcl_Obj* paramValues;	/* List of parameter values */
    MYSQL_BIND* paramBindings;	/* Parameter bindings */
    unsigned long* paramLengths;/* Parameter lengths */
    my_ulonglong rowCount;	/* Number of affected rows */
    my_bool* resultErrors;	/* Failure indicators for retrieving columns */
    my_bool* resultNulls;	/* NULL indicators for retrieving columns */
    unsigned long* resultLengths;
				/* Byte lengths of retrieved columns */
    MYSQL_BIND* resultBindings;	/* Bindings controlling column retrieval */
} ResultSetData;
#define IncrResultSetRefCount(x)		\
    do {					\
	++((x)->refCount);			\
    } while (0)
#define DecrResultSetRefCount(x)		\
    do {					\
	ResultSetData* rs = (x);		\
	if (--(rs->refCount) <= 0) {		\
	    DeleteResultSet(rs);		\
	}					\
    } while(0)

/* Table of MySQL type names */

#define IS_BINARY	(1<<16)	/* Flag to OR in if a param is binary */
typedef struct MysqlDataType {
    const char* name;		/* Type name */
    int num;			/* Type number */
} MysqlDataType;
static const MysqlDataType dataTypes[] = {
    { "tinyint",	MYSQL_TYPE_TINY },
    { "smallint",	MYSQL_TYPE_SHORT },
    { "integer",	MYSQL_TYPE_LONG },
    { "float",		MYSQL_TYPE_FLOAT },
    { "real",		MYSQL_TYPE_FLOAT },
    { "double",		MYSQL_TYPE_DOUBLE },
    { "NULL",		MYSQL_TYPE_NULL },
    { "timestamp",	MYSQL_TYPE_TIMESTAMP },
    { "bigint",		MYSQL_TYPE_LONGLONG },
    { "mediumint",	MYSQL_TYPE_INT24 },
    { "date",		MYSQL_TYPE_NEWDATE },
    { "date",		MYSQL_TYPE_DATE },
    { "time",		MYSQL_TYPE_TIME },
    { "datetime",	MYSQL_TYPE_DATETIME },
    { "year",		MYSQL_TYPE_YEAR },
    { "bit",		MYSQL_TYPE_BIT | IS_BINARY },
    { "numeric",	MYSQL_TYPE_NEWDECIMAL },
    { "decimal",	MYSQL_TYPE_NEWDECIMAL },
    { "numeric",	MYSQL_TYPE_DECIMAL },
    { "decimal",	MYSQL_TYPE_DECIMAL },
    { "enum",		MYSQL_TYPE_ENUM },
    { "set",		MYSQL_TYPE_SET },
    { "tinytext",	MYSQL_TYPE_TINY_BLOB },
    { "tinyblob",	MYSQL_TYPE_TINY_BLOB | IS_BINARY },
    { "mediumtext",	MYSQL_TYPE_MEDIUM_BLOB },
    { "mediumblob",	MYSQL_TYPE_MEDIUM_BLOB | IS_BINARY },
    { "longtext",	MYSQL_TYPE_LONG_BLOB },
    { "longblob",	MYSQL_TYPE_LONG_BLOB | IS_BINARY },
    { "text",		MYSQL_TYPE_BLOB },
    { "blob",		MYSQL_TYPE_BLOB | IS_BINARY },
    { "varbinary",	MYSQL_TYPE_VAR_STRING | IS_BINARY },
    { "varchar",	MYSQL_TYPE_VAR_STRING },
    { "varbinary",	MYSQL_TYPE_VARCHAR | IS_BINARY },
    { "varchar",	MYSQL_TYPE_VARCHAR },
    { "binary",		MYSQL_TYPE_STRING | IS_BINARY },
    { "char",		MYSQL_TYPE_STRING },
    { "geometry",	MYSQL_TYPE_GEOMETRY },
    { NULL, 		0 }
};

/* Configuration options for MySQL connections */

/* Data types of configuration options */

enum OptType {
    TYPE_STRING,		/* Arbitrary character string */
    TYPE_FLAG, 			/* Boolean flag */
    TYPE_ENCODING,		/* Encoding name */
    TYPE_ISOLATION,		/* Transaction isolation level */
    TYPE_PORT, 			/* Port number */
    TYPE_READONLY,		/* Read-only indicator */
    TYPE_TIMEOUT		/* Timeout value */
};

/* Locations of the string options in the string array */

enum OptStringIndex {
    INDX_DB, INDX_HOST, INDX_PASSWD, INDX_SOCKET,
    INDX_SSLCA, INDX_SSLCAPATH, INDX_SSLCERT, INDX_SSLCIPHER, INDX_SSLKEY,
    INDX_USER,
    INDX_MAX
};

/* Flags in the configuration table */

#define CONN_OPT_FLAG_MOD 0x1	/* Configuration value changable at runtime */
#define CONN_OPT_FLAG_SSL 0x2	/* Configuration change requires setting
				 * SSL options */
#define CONN_OPT_FLAG_ALIAS 0x4	/* Configuration option is an alias */

 /* Table of configuration options */

static const struct {
    const char * name;	/* Option name */
    enum OptType type;	/* Option data type */
    int info;		/* Option index or flag value */
    int flags;		/* Flags - modifiable; SSL related; is an alias */
    const char* query;	/* How to determine the option value? */
} ConnOptions [] = {
    { "-compress",    TYPE_FLAG,      CLIENT_COMPRESS,	  0,
      "SELECT '', @@SLAVE_COMPRESSED_PROTOCOL" },
    { "-database",    TYPE_STRING,    INDX_DB,		  CONN_OPT_FLAG_MOD,
      "SELECT '', DATABASE();"},
    { "-db",	      TYPE_STRING,    INDX_DB, 		  CONN_OPT_FLAG_MOD
                                                        | CONN_OPT_FLAG_ALIAS,
      "SELECT '', DATABASE()" },
    { "-encoding",    TYPE_ENCODING,  0,		  0,
      "SELECT '', 'utf-8'" },
    { "-host",	      TYPE_STRING,    INDX_HOST,	  0,
      "SHOW SESSION VARIABLES WHERE VARIABLE_NAME = 'hostname'" },
    { "-interactive", TYPE_FLAG,      CLIENT_INTERACTIVE, 0,
      "SELECT '', 0" },
    { "-isolation",   TYPE_ISOLATION, 0,		  CONN_OPT_FLAG_MOD,
      "SELECT '', LCASE(REPLACE(@@TX_ISOLATION, '-', ''))" },
    { "-passwd",      TYPE_STRING,    INDX_PASSWD,	  CONN_OPT_FLAG_MOD
                                                        | CONN_OPT_FLAG_ALIAS,
      "SELECT '', ''" },
    { "-password",    TYPE_STRING,    INDX_PASSWD,	  CONN_OPT_FLAG_MOD,
      "SELECT '', ''" },
    { "-port",	      TYPE_PORT,      0,		  0,
      "SHOW SESSION VARIABLES WHERE VARIABLE_NAME = 'port'" },
    { "-readonly",    TYPE_READONLY,  0,		  0,
      "SELECT '', 0" },
    { "-socket",      TYPE_STRING,    INDX_SOCKET,	  0,
      "SHOW SESSION VARIABLES WHERE VARIABLE_NAME = 'socket'" },
    { "-ssl_ca",      TYPE_STRING,    INDX_SSLCA,	  CONN_OPT_FLAG_SSL,
      "SELECT '', @@SSL_CA"},
    { "-ssl_capath",  TYPE_STRING,    INDX_SSLCAPATH,	  CONN_OPT_FLAG_SSL,
      "SELECT '', @@SSL_CAPATH" },
    { "-ssl_cert",    TYPE_STRING,    INDX_SSLCERT,	  CONN_OPT_FLAG_SSL,
      "SELECT '', @@SSL_CERT" },
    { "-ssl_cipher",  TYPE_STRING,    INDX_SSLCIPHER,	  CONN_OPT_FLAG_SSL,
      "SELECT '', @@SSL_CIPHER" },
    { "-ssl_cypher",  TYPE_STRING,    INDX_SSLCIPHER,	  CONN_OPT_FLAG_SSL
                                                        | CONN_OPT_FLAG_ALIAS,
      "SELECT '', @@SSL_CIPHER" },
    { "-ssl_key",     TYPE_STRING,    INDX_SSLKEY,	  CONN_OPT_FLAG_SSL,
      "SELECT '', @@SSL_KEY" },
    { "-timeout",     TYPE_TIMEOUT,   0,		  CONN_OPT_FLAG_MOD,
      "SELECT '', @@WAIT_TIMEOUT" },
    { "-user",	      TYPE_STRING,    INDX_USER,	  CONN_OPT_FLAG_MOD,
      "SELECT '', USER()" },
    { NULL,	      0,	      0,		  0 }
};

/* Tables of isolation levels: Tcl, SQL, and MySQL 'tx_isolation' */

static const char *const TclIsolationLevels[] = {
    "readuncommitted",
    "readcommitted",
    "repeatableread",
    "serializable",
    NULL
};
static const char *const SqlIsolationLevels[] = {
    "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED",
    "SET TRANSACTION ISOLATION LEVEL READ COMMITTED",
    "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ",
    "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",
    NULL
};
enum IsolationLevel {
    ISOL_READ_UNCOMMITTED,
    ISOL_READ_COMMITTED,
    ISOL_REPEATABLE_READ,
    ISOL_SERIALIZABLE,
    ISOL_NONE = -1
};

/* Declarations of static functions appearing in this file */

static MYSQL_BIND* MysqlBindAlloc(int nBindings);
static MYSQL_BIND* MysqlBindIndex(MYSQL_BIND* b, int i);
static void* MysqlBindAllocBuffer(MYSQL_BIND* b, int i, unsigned long len);
static void MysqlBindFreeBuffer(MYSQL_BIND* b, int i);
static void MysqlBindSetBufferType(MYSQL_BIND* b, int i,
				   enum enum_field_types t);
static void* MysqlBindGetBuffer(MYSQL_BIND* b, int i);
static unsigned long MysqlBindGetBufferLength(MYSQL_BIND* b, int i);
static void MysqlBindSetLength(MYSQL_BIND* b, int i, unsigned long* p);
static void MysqlBindSetIsNull(MYSQL_BIND* b, int i, my_bool* p);
static void MysqlBindSetError(MYSQL_BIND* b, int i, my_bool* p);

static MYSQL_FIELD* MysqlFieldIndex(MYSQL_FIELD* fields, int i);

static void TransferMysqlError(Tcl_Interp* interp, MYSQL* mysqlPtr);
static void TransferMysqlStmtError(Tcl_Interp* interp, MYSQL_STMT* mysqlPtr);

static Tcl_Obj* QueryConnectionOption(ConnectionData* cdata, Tcl_Interp* interp,
				      int optionNum);
static int ConfigureConnection(ConnectionData* cdata, Tcl_Interp* interp,
			       int objc, Tcl_Obj *const objv[], int skip);
static int ConnectionConstructor(ClientData clientData, Tcl_Interp* interp,
				 Tcl_ObjectContext context,
				 int objc, Tcl_Obj *const objv[]);
static int ConnectionBegintransactionMethod(ClientData clientData,
					    Tcl_Interp* interp,
					    Tcl_ObjectContext context,
					    int objc, Tcl_Obj *const objv[]);
static int ConnectionColumnsMethod(ClientData clientData, Tcl_Interp* interp,
				  Tcl_ObjectContext context,
				  int objc, Tcl_Obj *const objv[]);
static int ConnectionCommitMethod(ClientData clientData, Tcl_Interp* interp,
				  Tcl_ObjectContext context,
				  int objc, Tcl_Obj *const objv[]);
static int ConnectionConfigureMethod(ClientData clientData, Tcl_Interp* interp,
				     Tcl_ObjectContext context,
				     int objc, Tcl_Obj *const objv[]);
static int ConnectionEvaldirectMethod(ClientData clientData, Tcl_Interp* interp,
				      Tcl_ObjectContext context,
				      int objc, Tcl_Obj *const objv[]);
static int ConnectionNeedCollationInfoMethod(ClientData clientData,
					     Tcl_Interp* interp,
					     Tcl_ObjectContext context,
					     int objc, Tcl_Obj *const objv[]);
static int ConnectionRollbackMethod(ClientData clientData, Tcl_Interp* interp,
				    Tcl_ObjectContext context,
				    int objc, Tcl_Obj *const objv[]);
static int ConnectionSetCollationInfoMethod(ClientData clientData,
					    Tcl_Interp* interp,
					    Tcl_ObjectContext context,
					    int objc, Tcl_Obj *const objv[]);
static int ConnectionTablesMethod(ClientData clientData, Tcl_Interp* interp,
				  Tcl_ObjectContext context,
				  int objc, Tcl_Obj *const objv[]);

static void DeleteConnectionMetadata(ClientData clientData);
static void DeleteConnection(ConnectionData* cdata);
static int CloneConnection(Tcl_Interp* interp, ClientData oldClientData,
			   ClientData* newClientData);

static StatementData* NewStatement(ConnectionData* cdata);
static MYSQL_STMT* AllocAndPrepareStatement(Tcl_Interp* interp,
					    StatementData* sdata);
static Tcl_Obj* ResultDescToTcl(MYSQL_RES* resultDesc, int flags);

static int StatementConstructor(ClientData clientData, Tcl_Interp* interp,
				Tcl_ObjectContext context,
				int objc, Tcl_Obj *const objv[]);
static int StatementParamtypeMethod(ClientData clientData, Tcl_Interp* interp,
				    Tcl_ObjectContext context,
				    int objc, Tcl_Obj *const objv[]);
static int StatementParamsMethod(ClientData clientData, Tcl_Interp* interp,
				 Tcl_ObjectContext context,
				 int objc, Tcl_Obj *const objv[]);

static void DeleteStatementMetadata(ClientData clientData);
static void DeleteStatement(StatementData* sdata);
static int CloneStatement(Tcl_Interp* interp, ClientData oldClientData,
			  ClientData* newClientData);

static int ResultSetConstructor(ClientData clientData, Tcl_Interp* interp,
				Tcl_ObjectContext context,
				int objc, Tcl_Obj *const objv[]);
static int ResultSetColumnsMethod(ClientData clientData, Tcl_Interp* interp,
				  Tcl_ObjectContext context,
				  int objc, Tcl_Obj *const objv[]);
static int ResultSetNextrowMethod(ClientData clientData, Tcl_Interp* interp,
				  Tcl_ObjectContext context,
				  int objc, Tcl_Obj *const objv[]);
static int ResultSetRowcountMethod(ClientData clientData, Tcl_Interp* interp,
				   Tcl_ObjectContext context,
				   int objc, Tcl_Obj *const objv[]);

static void DeleteResultSetMetadata(ClientData clientData);
static void DeleteResultSet(ResultSetData* rdata);
static int CloneResultSet(Tcl_Interp* interp, ClientData oldClientData,
			  ClientData* newClientData);


static void DeleteCmd(ClientData clientData);
static int CloneCmd(Tcl_Interp* interp,
		    ClientData oldMetadata, ClientData* newMetadata);

static void DeletePerInterpData(PerInterpData* pidata);

/* Metadata type that holds connection data */

const static Tcl_ObjectMetadataType connectionDataType = {
    TCL_OO_METADATA_VERSION_CURRENT,
				/* version */
    "ConnectionData",		/* name */
    DeleteConnectionMetadata,	/* deleteProc */
    CloneConnection		/* cloneProc - should cause an error
				 * 'cuz connections aren't clonable */
};

/* Metadata type that holds statement data */

const static Tcl_ObjectMetadataType statementDataType = {
    TCL_OO_METADATA_VERSION_CURRENT,
				/* version */
    "StatementData",		/* name */
    DeleteStatementMetadata,	/* deleteProc */
    CloneStatement		/* cloneProc - should cause an error
				 * 'cuz statements aren't clonable */
};

/* Metadata type for result set data */

const static Tcl_ObjectMetadataType resultSetDataType = {
    TCL_OO_METADATA_VERSION_CURRENT,
				/* version */
    "ResultSetData",		/* name */
    DeleteResultSetMetadata,	/* deleteProc */
    CloneResultSet		/* cloneProc - should cause an error
				 * 'cuz result sets aren't clonable */
};

/* Method types of the connection methods that are implemented in C */

const static Tcl_MethodType ConnectionConstructorType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "CONSTRUCTOR",		/* name */
    ConnectionConstructor,	/* callProc */
    DeleteCmd,			/* deleteProc */
    CloneCmd			/* cloneProc */
};

const static Tcl_MethodType ConnectionBegintransactionMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "begintransaction",		/* name */
    ConnectionBegintransactionMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType ConnectionColumnsMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "Columns",			/* name */
    ConnectionColumnsMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType ConnectionCommitMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "commit",			/* name */
    ConnectionCommitMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType ConnectionConfigureMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "configure",		/* name */
    ConnectionConfigureMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType ConnectionEvaldirectMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "evaldirect",		/* name */
    ConnectionEvaldirectMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType ConnectionNeedCollationInfoMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "NeedCollationInfo",	/* name */
    ConnectionNeedCollationInfoMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType ConnectionRollbackMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "rollback",			/* name */
    ConnectionRollbackMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType ConnectionSetCollationInfoMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "SetCollationInfo",		/* name */
    ConnectionSetCollationInfoMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType ConnectionTablesMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "tables",			/* name */
    ConnectionTablesMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};

const static Tcl_MethodType* ConnectionMethods[] = {
    &ConnectionBegintransactionMethodType,
    &ConnectionColumnsMethodType,
    &ConnectionCommitMethodType,
    &ConnectionConfigureMethodType,
    &ConnectionEvaldirectMethodType,
    &ConnectionNeedCollationInfoMethodType,
    &ConnectionRollbackMethodType,
    &ConnectionSetCollationInfoMethodType,
    &ConnectionTablesMethodType,
    NULL
};

/* Method types of the statement methods that are implemented in C */

const static Tcl_MethodType StatementConstructorType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "CONSTRUCTOR",		/* name */
    StatementConstructor,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType StatementParamsMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "params",			/* name */
    StatementParamsMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType StatementParamtypeMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "paramtype",		/* name */
    StatementParamtypeMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};

/*
 * Methods to create on the statement class.
 */

const static Tcl_MethodType* StatementMethods[] = {
    &StatementParamsMethodType,
    &StatementParamtypeMethodType,
    NULL
};

/* Method types of the result set methods that are implemented in C */

const static Tcl_MethodType ResultSetConstructorType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "CONSTRUCTOR",		/* name */
    ResultSetConstructor,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType ResultSetColumnsMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */    "columns",			/* name */
    ResultSetColumnsMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType ResultSetNextrowMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "nextrow",			/* name */
    ResultSetNextrowMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};
const static Tcl_MethodType ResultSetRowcountMethodType = {
    TCL_OO_METHOD_VERSION_CURRENT,
				/* version */
    "rowcount",			/* name */
    ResultSetRowcountMethod,	/* callProc */
    NULL,			/* deleteProc */
    NULL			/* cloneProc */
};


/* Methods to create on the result set class */

const static Tcl_MethodType* ResultSetMethods[] = {
    &ResultSetColumnsMethodType,
    &ResultSetRowcountMethodType,
    NULL
};

/*
 *-----------------------------------------------------------------------------
 *
 * MysqlBindAlloc --
 *
 *	Allocate a number of MYSQL_BIND structures.
 *
 * Results:
 *	Returns a pointer to the array of structures, which will be zeroed out.
 *
 *-----------------------------------------------------------------------------
 */

static MYSQL_BIND*
MysqlBindAlloc(int nBindings)
{
    int size;
    void* retval = NULL;
    if (mysqlClientVersion >= 50100) {
	size = sizeof(struct st_mysql_bind_51);
    } else {
	size = sizeof(struct st_mysql_bind_50);
    }
    size *= nBindings;
    if (size != 0) {
	retval = ckalloc(size);
	memset(retval, 0, size);
    }
    return (MYSQL_BIND*) retval;
}

/*
 *-----------------------------------------------------------------------------
 *
 * MysqlBindIndex --
 *
 *	Returns a pointer to one of an array of MYSQL_BIND objects
 *
 *-----------------------------------------------------------------------------
 */

static MYSQL_BIND*
MysqlBindIndex(
    MYSQL_BIND* b, 		/* Binding array to alter */
    int i			/* Index in the binding array */
) {
    if (mysqlClientVersion >= 50100) {
	return (MYSQL_BIND*)(((struct st_mysql_bind_51*) b) + i);
    } else {
	return (MYSQL_BIND*)(((struct st_mysql_bind_50*) b) + i);
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * MysqlBindAllocBuffer --
 *
 *	Allocates the buffer in a MYSQL_BIND object
 *
 * Results:
 *	Returns a pointer to the allocated buffer
 *
 *-----------------------------------------------------------------------------
 */

static void*
MysqlBindAllocBuffer(
    MYSQL_BIND* b,		/* Pointer to a binding array */
    int i,			/* Index into the array */
    unsigned long len		/* Length of the buffer to allocate or 0 */
) {
    void* block = NULL;
    if (len != 0) {
	block = ckalloc(len);
    }
    if (mysqlClientVersion >= 50100) {
	((struct st_mysql_bind_51*) b)[i].buffer = block;
	((struct st_mysql_bind_51*) b)[i].buffer_length = len;
    } else {
	((struct st_mysql_bind_50*) b)[i].buffer = block;
	((struct st_mysql_bind_50*) b)[i].buffer_length = len;
    }
    return block;
}

/*
 *-----------------------------------------------------------------------------
 *
 * MysqlBindFreeBuffer --
 *
 *	Frees trhe buffer in a MYSQL_BIND object
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Buffer is returned to the system.
 *
 *-----------------------------------------------------------------------------
 */
static void
MysqlBindFreeBuffer(
    MYSQL_BIND* b,		/* Pointer to a binding array */
    int i			/* Index into the array */
) {
    if (mysqlClientVersion >= 50100) {
	struct st_mysql_bind_51* bindings = (struct st_mysql_bind_51*) b;
	if (bindings[i].buffer) {
	    ckfree(bindings[i].buffer);
	    bindings[i].buffer = NULL;
	}
	bindings[i].buffer_length = 0;
    } else {
	struct st_mysql_bind_50* bindings = (struct st_mysql_bind_50*) b;
	if (bindings[i].buffer) {
	    ckfree(bindings[i].buffer);
	    bindings[i].buffer = NULL;
	}
	bindings[i].buffer_length = 0;
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * MysqlBindGetBufferLength, MysqlBindSetBufferType, MysqlBindGetBufferType,
 * MysqlBindSetLength, MysqlBindSetIsNull,
 * MysqlBindSetError --
 *
 *	Access the fields of a MYSQL_BIND object
 *
 *-----------------------------------------------------------------------------
 */

static void*
MysqlBindGetBuffer(
    MYSQL_BIND* b, 		/* Binding array to alter */
    int i			/* Index in the binding array */
) {
    if (mysqlClientVersion >= 50100) {
	return ((struct st_mysql_bind_51*) b)[i].buffer;
    } else {
	return ((struct st_mysql_bind_50*) b)[i].buffer;
    }
}

static unsigned long
MysqlBindGetBufferLength(
    MYSQL_BIND* b, 		/* Binding array to alter */
    int i			/* Index in the binding array */
) {
    if (mysqlClientVersion >= 50100) {
	return ((struct st_mysql_bind_51*) b)[i].buffer_length;
    } else {
	return ((struct st_mysql_bind_50*) b)[i].buffer_length;
    }

}

static enum enum_field_types
MysqlBindGetBufferType(
    MYSQL_BIND* b, 		/* Binding array to alter */
    int i			/* Index in the binding array */
) {
    if (mysqlClientVersion >= 50100) {
	return ((struct st_mysql_bind_51*) b)[i].buffer_type;
    } else {
	return ((struct st_mysql_bind_50*) b)[i].buffer_type;
    }
}

static void
MysqlBindSetBufferType(
    MYSQL_BIND* b, 		/* Binding array to alter */
    int i,			/* Index in the binding array */
    enum enum_field_types t	/* Buffer type to assign */
) {
    if (mysqlClientVersion >= 50100) {
	((struct st_mysql_bind_51*) b)[i].buffer_type = t;
    } else {
	((struct st_mysql_bind_50*) b)[i].buffer_type = t;
    }
}

static void
MysqlBindSetLength(
    MYSQL_BIND* b, 		/* Binding array to alter */
    int i,			/* Index in the binding array */
    unsigned long* p		/* Length pointer to assign */
) {
    if (mysqlClientVersion >= 50100) {
	((struct st_mysql_bind_51*) b)[i].length = p;
    } else {
	((struct st_mysql_bind_50*) b)[i].length = p;
    }
}

static void
MysqlBindSetIsNull(
    MYSQL_BIND* b, 		/* Binding array to alter */
    int i,			/* Index in the binding array */
    my_bool* p			/* "Is null" indicator pointer to assign */
) {
    if (mysqlClientVersion >= 50100) {
	((struct st_mysql_bind_51*) b)[i].is_null = p;
    } else {
	((struct st_mysql_bind_50*) b)[i].is_null = p;
    }
}

static void
MysqlBindSetError(
    MYSQL_BIND* b, 		/* Binding array to alter */
    int i,			/* Index in the binding array */
    my_bool* p			/* Error indicator pointer to assign */
) {
    if (mysqlClientVersion >= 50100) {
	((struct st_mysql_bind_51*) b)[i].error = p;
    } else {
	((struct st_mysql_bind_50*) b)[i].error = p;
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * MysqlFieldIndex --
 *
 *	Return a pointer to a given MYSQL_FIELD structure in an array
 *
 * The MYSQL_FIELD structure grows by one pointer between 5.0 and 5.1.
 * Our code never creates a MYSQL_FIELD, nor does it try to access that
 * pointer, so we handle things simply by casting the types.
 *
 *-----------------------------------------------------------------------------
 */

static MYSQL_FIELD*
MysqlFieldIndex(MYSQL_FIELD* fields,
				/*  Pointer to the array*/
		int i)		/* Index in the array */
{
    MYSQL_FIELD* retval;
    if (mysqlClientVersion >= 50100) {
	retval = (MYSQL_FIELD*)(((struct st_mysql_field_51*) fields)+i);
    } else {
	retval = (MYSQL_FIELD*)(((struct st_mysql_field_50*) fields)+i);
    }
    return retval;
}

/*
 *-----------------------------------------------------------------------------
 *
 * TransferMysqlError --
 *
 *	Obtains the error message, SQL state, and error number from the
 *	MySQL client library and transfers them into the Tcl interpreter
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Sets the interpreter result and error code to describe the SQL error
 *
 *-----------------------------------------------------------------------------
 */

static void
TransferMysqlError(
    Tcl_Interp* interp,		/* Tcl interpreter */
    MYSQL* mysqlPtr		/* MySQL connection handle */
) {
    const char* sqlstate = mysql_sqlstate(mysqlPtr);
    Tcl_Obj* errorCode = Tcl_NewObj();
    Tcl_ListObjAppendElement(NULL, errorCode, Tcl_NewStringObj("TDBC", -1));
    Tcl_ListObjAppendElement(NULL, errorCode,
			     Tcl_NewStringObj(Tdbc_MapSqlState(sqlstate), -1));
    Tcl_ListObjAppendElement(NULL, errorCode,
			     Tcl_NewStringObj(sqlstate, -1));
    Tcl_ListObjAppendElement(NULL, errorCode, Tcl_NewStringObj("MYSQL", -1));
    Tcl_ListObjAppendElement(NULL, errorCode,
			     Tcl_NewIntObj(mysql_errno(mysqlPtr)));
    Tcl_SetObjErrorCode(interp, errorCode);
    Tcl_SetObjResult(interp, Tcl_NewStringObj(mysql_error(mysqlPtr), -1));
}

/*
 *-----------------------------------------------------------------------------
 *
 * TransferMysqlStmtError --
 *
 *	Obtains the error message, SQL state, and error number from the
 *	MySQL client library and transfers them into the Tcl interpreter
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Sets the interpreter result and error code to describe the SQL error
 *
 *-----------------------------------------------------------------------------
 */

static void
TransferMysqlStmtError(
    Tcl_Interp* interp,		/* Tcl interpreter */
    MYSQL_STMT* stmtPtr		/* MySQL statment handle */
) {
    const char* sqlstate = mysql_stmt_sqlstate(stmtPtr);
    Tcl_Obj* errorCode = Tcl_NewObj();
    Tcl_ListObjAppendElement(NULL, errorCode, Tcl_NewStringObj("TDBC", -1));
    Tcl_ListObjAppendElement(NULL, errorCode,
			     Tcl_NewStringObj(Tdbc_MapSqlState(sqlstate), -1));
    Tcl_ListObjAppendElement(NULL, errorCode,
			     Tcl_NewStringObj(sqlstate, -1));
    Tcl_ListObjAppendElement(NULL, errorCode, Tcl_NewStringObj("MYSQL", -1));
    Tcl_ListObjAppendElement(NULL, errorCode,
			     Tcl_NewIntObj(mysql_stmt_errno(stmtPtr)));
    Tcl_SetObjErrorCode(interp, errorCode);
    Tcl_SetObjResult(interp, Tcl_NewStringObj(mysql_stmt_error(stmtPtr), -1));
}

/*
 *-----------------------------------------------------------------------------
 *
 * QueryConnectionOption --
 *
 *	Determine the current value of a connection option.
 *
 * Results:
 *	Returns a Tcl object containing the value if successful, or NULL
 *	if unsuccessful. If unsuccessful, stores error information in the
 *	Tcl interpreter.
 *
 *-----------------------------------------------------------------------------
 */

static Tcl_Obj*
QueryConnectionOption (
    ConnectionData* cdata,	/* Connection data */
    Tcl_Interp* interp,		/* Tcl interpreter */
    int optionNum		/* Position of the option in the table */
) {
    MYSQL_RES* result;		/* Result of the MySQL query for the option */
    MYSQL_ROW row;		/* Row of the result set */
    int fieldCount;		/* Number of fields in a row */
    unsigned long* lengths;	/* Character lengths of the fields */
    Tcl_Obj* retval;		/* Return value */

    if (mysql_query(cdata->mysqlPtr, ConnOptions[optionNum].query)) {
	TransferMysqlError(interp, cdata->mysqlPtr);
	return NULL;
    }
    result = mysql_store_result(cdata->mysqlPtr);
    if (result == NULL) {
	TransferMysqlError(interp, cdata->mysqlPtr);
	return NULL;
    }
    fieldCount = mysql_num_fields(result);
    if (fieldCount < 2) {
	retval = cdata->pidata->literals[LIT_EMPTY];
    } else {
	if ((row = mysql_fetch_row(result)) == NULL) {
	    if (mysql_errno(cdata->mysqlPtr)) {
		TransferMysqlError(interp, cdata->mysqlPtr);
		mysql_free_result(result);
		return NULL;
	    } else {
		retval = cdata->pidata->literals[LIT_EMPTY];
	    }
	} else {
	    lengths = mysql_fetch_lengths(result);
	    retval = Tcl_NewStringObj(row[1], lengths[1]);
	}
    }
    mysql_free_result(result);
    return retval;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ConfigureConnection --
 *
 *	Applies configuration settings to a MySQL connection.
 *
 * Results:
 *	Returns a Tcl result. If the result is TCL_ERROR, error information
 *	is stored in the interpreter.
 *
 * Side effects:
 *	Updates configuration in the connection data. Opens a connection
 *	if none is yet open.
 *
 *-----------------------------------------------------------------------------
 */

static int
ConfigureConnection(
    ConnectionData* cdata,	/* Connection data */
    Tcl_Interp* interp,		/* Tcl interpreter */
    int objc,			/* Parameter count */
    Tcl_Obj* const objv[],	/* Parameter data */
    int skip			/* Number of parameters to skip */
) {

    const char* stringOpts[INDX_MAX];
				/* String-valued options */
    unsigned long mysqlFlags=0;	/* Connection flags */
    int sslFlag = 0;		/* Flag==1 if SSL configuration is needed */
    int optionIndex;		/* Index of the current option in ConnOptions */
    int optionValue;		/* Integer value of the current option */
    unsigned short port = 0;	/* Server port number */
    int isolation = ISOL_NONE;	/* Isolation level */
    int timeout = 0;		/* Timeout value */
    int i;
    Tcl_Obj* retval;
    Tcl_Obj* optval;

    if (cdata->mysqlPtr != NULL) {

	/* Query configuration options on an existing connection */

	if (objc == skip) {
	    retval = Tcl_NewObj();
	    for (i = 0; ConnOptions[i].name != NULL; ++i) {
		if (ConnOptions[i].flags & CONN_OPT_FLAG_ALIAS) continue;
		optval = QueryConnectionOption(cdata, interp, i);
		if (optval == NULL) {
		    return TCL_ERROR;
		}
		Tcl_DictObjPut(NULL, retval,
			       Tcl_NewStringObj(ConnOptions[i].name, -1),
			       optval);
	    }
	    Tcl_SetObjResult(interp, retval);
	    return TCL_OK;
	} else if (objc == skip+1) {

	    if (Tcl_GetIndexFromObjStruct(interp, objv[skip],
					  (void*) ConnOptions,
					  sizeof(ConnOptions[0]), "option",
					  0, &optionIndex) != TCL_OK) {
		return TCL_ERROR;
	    }
	    retval = QueryConnectionOption(cdata, interp, optionIndex);
	    if (retval == NULL) {
		return TCL_ERROR;
	    } else {
		Tcl_SetObjResult(interp, retval);
		return TCL_OK;
	    }
	}
    }

    if ((objc-skip) % 2 != 0) {
	Tcl_WrongNumArgs(interp, skip, objv, "?-option value?...");
	return TCL_ERROR;
    }

    /* Extract options from the command line */

    for (i = 0; i < INDX_MAX; ++i) {
	stringOpts[i] = NULL;
    }
    for (i = skip; i < objc; i += 2) {

	/* Unknown option */

	if (Tcl_GetIndexFromObjStruct(interp, objv[i], (void*) ConnOptions,
				      sizeof(ConnOptions[0]), "option",
				      0, &optionIndex) != TCL_OK) {
	    return TCL_ERROR;
	}

	/* Unmodifiable option */

	if (cdata->mysqlPtr != NULL && !(ConnOptions[optionIndex].flags
					 & CONN_OPT_FLAG_MOD)) {
	    Tcl_Obj* msg = Tcl_NewStringObj("\"", -1);
	    Tcl_AppendObjToObj(msg, objv[i]);
	    Tcl_AppendToObj(msg, "\" option cannot be changed dynamically", -1);
	    Tcl_SetObjResult(interp, msg);
	    Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY000",
			     "MYSQL", "-1", NULL);
	    return TCL_ERROR;
	}

	/* Record option value */

	switch (ConnOptions[optionIndex].type) {
	case TYPE_STRING:
	    stringOpts[ConnOptions[optionIndex].info] =
		Tcl_GetString(objv[i+1]);
	    break;
	case TYPE_FLAG:
	    if (Tcl_GetBooleanFromObj(interp, objv[i+1], &optionValue)
		!= TCL_OK) {
		return TCL_ERROR;
	    }
	    if (optionValue) {
		mysqlFlags |= ConnOptions[optionIndex].info;
	    }
	    break;
	case TYPE_ENCODING:
	    if (strcmp(Tcl_GetString(objv[i+1]), "utf-8")) {
		Tcl_SetObjResult(interp,
				 Tcl_NewStringObj("Only UTF-8 transfer "
						  "encoding is supported.\n",
						  -1));
		Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY000",
				 "MYSQL", "-1", NULL);
		return TCL_ERROR;
	    }
	    break;
	case TYPE_ISOLATION:
	    if (Tcl_GetIndexFromObj(interp, objv[i+1], TclIsolationLevels,
				    "isolation level", TCL_EXACT, &isolation)
		!= TCL_OK) {
		return TCL_ERROR;
	    }
	    break;
	case TYPE_PORT:
	    if (Tcl_GetIntFromObj(interp, objv[i+1], &optionValue) != TCL_OK) {
		return TCL_ERROR;
	    }
	    if (optionValue < 0 || optionValue > 0xffff) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("port number must "
							  "be in range "
							  "[0..65535]", -1));
		Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY000",
				 "MYSQL", "-1", NULL);
		return TCL_ERROR;
	    }
	    port = optionValue;
	    break;
	case TYPE_READONLY:
	    if (Tcl_GetBooleanFromObj(interp, objv[i+1], &optionValue)
		!= TCL_OK) {
		return TCL_ERROR;
	    }
	    if (optionValue != 0) {
		Tcl_SetObjResult(interp,
				 Tcl_NewStringObj("MySQL does not support "
						  "readonly connections", -1));
		Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY000",
				 "MYSQL", "-1", NULL);
		return TCL_ERROR;
	    }
	    break;
	case TYPE_TIMEOUT:
	    if (Tcl_GetIntFromObj(interp, objv[i+1], &timeout) != TCL_OK) {
		return TCL_ERROR;
	    }
	    break;
	}
	if (ConnOptions[optionIndex].flags & CONN_OPT_FLAG_SSL) {
	    sslFlag = 1;
	}
    }

    if (cdata->mysqlPtr == NULL) {

	/* Configuring a new connection. Open the database */

	cdata->mysqlPtr = mysql_init(NULL);
	if (cdata->mysqlPtr == NULL) {
	    Tcl_SetObjResult(interp,
			     Tcl_NewStringObj("mysql_init() failed.", -1));
	    Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY001",
			     "MYSQL", "NULL", NULL);
	    return TCL_ERROR;
	}

	/* Set character set for the connection */

	mysql_options(cdata->mysqlPtr, MYSQL_SET_CHARSET_NAME, "utf8");

	    /* Set SSL options if needed */

	if (sslFlag) {
	    mysql_ssl_set(cdata->mysqlPtr, stringOpts[INDX_SSLKEY],
			  stringOpts[INDX_SSLCERT], stringOpts[INDX_SSLCA],
			  stringOpts[INDX_SSLCAPATH],
			  stringOpts[INDX_SSLCIPHER]);
	}

	/* Establish the connection */

	/*
	 * TODO - mutex around this unless linked to libmysqlclient_r ?
	 */

	if (mysql_real_connect(cdata->mysqlPtr, stringOpts[INDX_HOST],
			       stringOpts[INDX_USER], stringOpts[INDX_PASSWD],
			       stringOpts[INDX_DB], port,
			       stringOpts[INDX_SOCKET], mysqlFlags) == NULL) {
	    TransferMysqlError(interp, cdata->mysqlPtr);
	    return TCL_ERROR;
	}

	cdata->flags |= CONN_FLAG_AUTOCOMMIT;

    } else {

	/* Already open connection */

	if (stringOpts[INDX_USER] != NULL) {

	    /* User name changed - log in again */

	    if (mysql_change_user(cdata->mysqlPtr,
				  stringOpts[INDX_USER],
				  stringOpts[INDX_PASSWD],
				  stringOpts[INDX_DB])) {
		TransferMysqlError(interp, cdata->mysqlPtr);
		return TCL_ERROR;
	    }
	} else if (stringOpts[INDX_DB] != NULL) {

	    /* Database name changed - use the new database */

	    if (mysql_select_db(cdata->mysqlPtr, stringOpts[INDX_DB])) {
		TransferMysqlError(interp, cdata->mysqlPtr);
		return TCL_ERROR;
	    }
	}
    }

    /* Transaction isolation level */

    if (isolation != ISOL_NONE) {
	if (mysql_query(cdata->mysqlPtr, SqlIsolationLevels[isolation])) {
	    TransferMysqlError(interp, cdata->mysqlPtr);
	    return TCL_ERROR;
	}
    }

    /* Timeout */

    if (timeout != 0) {
        int result;
	Tcl_Obj* query = Tcl_ObjPrintf("SET SESSION WAIT_TIMEOUT = %d\n",
				       timeout);
	Tcl_IncrRefCount(query);
	result = mysql_query(cdata->mysqlPtr, Tcl_GetString(query));
	Tcl_DecrRefCount(query);
	if (result) {
	    TransferMysqlError(interp, cdata->mysqlPtr);
	    return TCL_ERROR;
	}
    }

    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ConnectionConstructor --
 *
 *	Constructor for ::tdbc::mysql::connection, which represents a
 *	database connection.
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * The ConnectionInitMethod takes alternating keywords and values giving
 * the configuration parameters of the connection, and attempts to connect
 * to the database.
 *
 *-----------------------------------------------------------------------------
 */

static int
ConnectionConstructor(
    ClientData clientData,	/* Environment handle */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext context, /* Object context */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {
    PerInterpData* pidata = (PerInterpData*) clientData;
				/* Per-interp data for the MYSQL package */
    Tcl_Object thisObject = Tcl_ObjectContextObject(context);
				/* The current object */
    int skip = Tcl_ObjectContextSkippedArgs(context);
				/* The number of leading arguments to skip */
    ConnectionData* cdata;	/* Per-connection data */

    /* Hang client data on this connection */

    cdata = (ConnectionData*) ckalloc(sizeof(ConnectionData));
    cdata->refCount = 1;
    cdata->pidata = pidata;
    cdata->mysqlPtr = NULL;
    cdata->nCollations = 0;
    cdata->collationSizes = NULL;
    cdata->flags = 0;
    IncrPerInterpRefCount(pidata);
    Tcl_ObjectSetMetadata(thisObject, &connectionDataType, (ClientData) cdata);

    /* Configure the connection */

    if (ConfigureConnection(cdata, interp, objc, objv, skip) != TCL_OK) {
	return TCL_ERROR;
    }

    return TCL_OK;

}

/*
 *-----------------------------------------------------------------------------
 *
 * ConnectionBegintransactionMethod --
 *
 *	Method that requests that following operations on an OBBC connection
 *	be executed as an atomic transaction.
 *
 * Usage:
 *	$connection begintransaction
 *
 * Parameters:
 *	None.
 *
 * Results:
 *	Returns an empty result if successful, and throws an error otherwise.
 *
 *-----------------------------------------------------------------------------
*/

static int
ConnectionBegintransactionMethod(
    ClientData clientData,	/* Unused */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext objectContext, /* Object context */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {
    Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
				/* The current connection object */
    ConnectionData* cdata = (ConnectionData*)
	Tcl_ObjectGetMetadata(thisObject, &connectionDataType);

    /* Check parameters */

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 2, objv, "");
	return TCL_ERROR;
    }

    /* Reject attempts at nested transactions */

    if (cdata->flags & CONN_FLAG_IN_XCN) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj("MySQL does not support "
						  "nested transactions", -1));
	Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HYC00",
			 "MYSQL", "-1", NULL);
	return TCL_ERROR;
    }
    cdata->flags |= CONN_FLAG_IN_XCN;

    /* Turn off autocommit for the duration of the transaction */

    if (cdata->flags & CONN_FLAG_AUTOCOMMIT) {
	if (mysql_autocommit(cdata->mysqlPtr, 0)) {
	    TransferMysqlError(interp, cdata->mysqlPtr);
	    return TCL_ERROR;
	}
	cdata->flags &= ~CONN_FLAG_AUTOCOMMIT;
    }

    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ConnectionColumnsMethod --
 *
 *	Method that asks for the names of columns in a table
 *	in the database (optionally matching a given pattern)
 *
 * Usage:
 * 	$connection columns table ?pattern?
 *
 * Parameters:
 *	None.
 *
 * Results:
 *	Returns the list of tables
 *
 *-----------------------------------------------------------------------------
 */

static int
ConnectionColumnsMethod(
    ClientData clientData,	/* Completion type */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext objectContext, /* Object context */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {
    Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
				/* The current connection object */
    ConnectionData* cdata = (ConnectionData*)
	Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
				/* Instance data */
    PerInterpData* pidata = cdata->pidata;
				/* Per-interpreter data */
    Tcl_Obj** literals = pidata->literals;
				/* Literal pool */
    const char* patternStr;	/* Pattern to match table names */
    MYSQL_RES* results;		/* Result set */
    Tcl_Obj* retval;		/* List of table names */
    Tcl_Obj* name;		/* Name of a column */
    Tcl_Obj* attrs;		/* Attributes of the column */
    Tcl_HashEntry* entry;	/* Hash entry for data type */

    /* Check parameters */

    if (objc == 3) {
	patternStr = NULL;
    } else if (objc == 4) {
	patternStr = Tcl_GetString(objv[3]);
    } else {
	Tcl_WrongNumArgs(interp, 2, objv, "table ?pattern?");
	return TCL_ERROR;
    }

    results = mysql_list_fields(cdata->mysqlPtr, Tcl_GetString(objv[2]),
				patternStr);
    if (results == NULL) {
	TransferMysqlError(interp, cdata->mysqlPtr);
	return TCL_ERROR;
    } else {
	unsigned int fieldCount = mysql_num_fields(results);
	MYSQL_FIELD* fields = mysql_fetch_fields(results);
	unsigned int i;
	retval = Tcl_NewObj();
	Tcl_IncrRefCount(retval);
	for (i = 0; i < fieldCount; ++i) {
	    MYSQL_FIELD* field = MysqlFieldIndex(fields, i);
	    attrs = Tcl_NewObj();
	    name = Tcl_NewStringObj(field->name, field->name_length);

	    Tcl_DictObjPut(NULL, attrs, literals[LIT_NAME], name);
	    /* TODO - Distinguish CHAR and BINARY */
	    entry = Tcl_FindHashEntry(&(pidata->typeNumHash),
				      (char*) field->type);
	    if (entry != NULL) {
		Tcl_DictObjPut(NULL, attrs, literals[LIT_TYPE],
			       (Tcl_Obj*) Tcl_GetHashValue(entry));
	    }
	    if (IS_NUM(field->type)) {
		Tcl_DictObjPut(NULL, attrs, literals[LIT_PRECISION],
			       Tcl_NewIntObj(field->length));
	    } else if (field->charsetnr < cdata->nCollations) {
		Tcl_DictObjPut(NULL, attrs, literals[LIT_PRECISION],
		    Tcl_NewIntObj(field->length
			/ cdata->collationSizes[field->charsetnr]));
	    }
	    Tcl_DictObjPut(NULL, attrs, literals[LIT_SCALE],
			   Tcl_NewIntObj(field->decimals));
	    Tcl_DictObjPut(NULL, attrs, literals[LIT_NULLABLE],
			   Tcl_NewIntObj(!(field->flags
					   & (NOT_NULL_FLAG))));
	    Tcl_DictObjPut(NULL, retval, name, attrs);
	}
	mysql_free_result(results);
	Tcl_SetObjResult(interp, retval);
	Tcl_DecrRefCount(retval);
	return TCL_OK;
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * ConnectionCommitMethod --
 *
 *	Method that requests that a pending transaction against a database
 * 	be committed.
 *
 * Usage:
 *	$connection commit
 *
 * Parameters:
 *	None.
 *
 * Results:
 *	Returns an empty Tcl result if successful, and throws an error
 *	otherwise.
 *
 *-----------------------------------------------------------------------------
 */

static int
ConnectionCommitMethod(
    ClientData clientData,	/* Completion type */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext objectContext, /* Object context */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {
    Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
				/* The current connection object */
    ConnectionData* cdata = (ConnectionData*)
	Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
				/* Instance data */
    my_bool rc;			/* MySQL status return */

    /* Check parameters */

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 2, objv, "");
	return TCL_ERROR;
    }

    /* Reject the request if no transaction is in progress */

    if (!(cdata->flags & CONN_FLAG_IN_XCN)) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj("no transaction is in "
						  "progress", -1));
	Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY010",
			 "MYSQL", "-1", NULL);
	return TCL_ERROR;
    }

    /* End transaction, turn off "transaction in progress", and report status */

    rc = mysql_commit(cdata->mysqlPtr);
    cdata->flags &= ~ CONN_FLAG_IN_XCN;
    if (rc) {
	TransferMysqlError(interp, cdata->mysqlPtr);
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ConnectionConfigureMethod --
 *
 *	Change configuration parameters on an open connection.
 *
 * Usage:
 *	$connection configure ?-keyword? ?value? ?-keyword value ...?
 *
 * Parameters:
 *	Keyword-value pairs (or a single keyword, or an empty set)
 *	of configuration options.
 *
 * Options:
 *	The following options are supported;
 *	    -database
 *		Name of the database to use by default in queries
 *	    -encoding
 *		Character encoding to use with the server. (Must be utf-8)
 *	    -isolation
 *		Transaction isolation level.
 *	    -readonly
 *		Read-only flag (must be a false Boolean value)
 *	    -timeout
 *		Timeout value (both wait_timeout and interactive_timeout)
 *
 *	Other options supported by the constructor are here in read-only
 *	mode; any attempt to change them will result in an error.
 *
 *-----------------------------------------------------------------------------
 */

static int ConnectionConfigureMethod(
     ClientData clientData,
     Tcl_Interp* interp,
     Tcl_ObjectContext objectContext,
     int objc,
     Tcl_Obj *const objv[]
) {
    Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
				/* The current connection object */
    int skip = Tcl_ObjectContextSkippedArgs(objectContext);
				/* Number of arguments to skip */
    ConnectionData* cdata = (ConnectionData*)
	Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
				/* Instance data */
    return ConfigureConnection(cdata, interp, objc, objv, skip);
}

/*
 *-----------------------------------------------------------------------------
 *
 * ConnectionEvaldirectMethod --
 *
 *	Evaluates a MySQL statement that is not supported by the prepared
 *	statement API.
 *
 * Usage:
 *	$connection evaldirect sql-statement
 *
 * Parameters:
 *	sql-statement -
 *		SQL statement to evaluate. The statement may not contain
 *		substitutions.
 *
 * Results:
 *	Returns a standard Tcl result. If the operation is successful,
 *	the result consists of a list of rows (in the same form as
 *	[$connection allrows -as dicts]). If the operation fails, the
 *	result is an error message.
 *
 * Side effects:
 *	Whatever the SQL statement does.
 *
 *-----------------------------------------------------------------------------
 */

static int
ConnectionEvaldirectMethod(
    ClientData clientData,	     /* Unused */
    Tcl_Interp* interp,		     /* Tcl interpreter */
    Tcl_ObjectContext objectContext, /* Object context */
    int objc,			     /* Parameter count */
    Tcl_Obj *const objv[])           /* Parameter vector */
{
    Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
				/* Current connection object */
    ConnectionData* cdata = (ConnectionData*)
	Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
				/* Instance data */
    int nColumns;		/* Number of columns in the result set */
    MYSQL_RES* resultPtr;	/* MySQL result set */
    MYSQL_ROW rowPtr;		/* One row of the result set */
    unsigned long* lengths;	/* Lengths of the fields in a row */
    Tcl_Obj* retObj;		/* Result set as a Tcl list */
    Tcl_Obj* rowObj;		/* One row of the result set as a Tcl list */
    Tcl_Obj* fieldObj;		/* One field of the row */
    int i;

    /* Check parameters */

    if (objc != 3) {
	Tcl_WrongNumArgs(interp, 2, objv, "");
	return TCL_ERROR;
    }

    /* Execute the given statement */

    if (mysql_query(cdata->mysqlPtr, Tcl_GetString(objv[2]))) {
	TransferMysqlError(interp, cdata->mysqlPtr);
	return TCL_ERROR;
    }

    /* Retrieve the result set */

    resultPtr = mysql_store_result(cdata->mysqlPtr);
    nColumns = mysql_field_count(cdata->mysqlPtr);
    if (resultPtr == NULL) {
	/*
	 * Can't retrieve result set. Distinguish result-less statements
	 * from MySQL errors.
	 */
	if (nColumns == 0) {
	    Tcl_SetObjResult
		(interp,
		 Tcl_NewWideIntObj(mysql_affected_rows(cdata->mysqlPtr)));
	    return TCL_OK;
	} else {
	    TransferMysqlError(interp, cdata->mysqlPtr);
	    return TCL_ERROR;
	}
    }

    /* Make a list-of-lists of the result */

    retObj = Tcl_NewObj();
    while ((rowPtr = mysql_fetch_row(resultPtr)) != NULL) {
	rowObj = Tcl_NewObj();
	lengths = mysql_fetch_lengths(resultPtr);
	for (i = 0; i < nColumns; ++i) {
	    if (rowPtr[i] != NULL) {
		fieldObj = Tcl_NewStringObj(rowPtr[i], lengths[i]);
	    } else {
		fieldObj = cdata->pidata->literals[LIT_EMPTY];
	    }
	    Tcl_ListObjAppendElement(NULL, rowObj, fieldObj);
	}
	Tcl_ListObjAppendElement(NULL, retObj, rowObj);
    }
    Tcl_SetObjResult(interp, retObj);

    /*
     * Free the result set.
     */
    mysql_free_result(resultPtr);

    return TCL_OK;
}


/*
 *-----------------------------------------------------------------------------
 *
 * ConnectionNeedCollationInfoMethod --
 *
 *	Internal method that determines whether the collation lengths
 *	are known yet.
 *
 * Usage:
 *	$connection NeedCollationInfo
 *
 * Parameters:
 *	None.
 *
 * Results:
 *	Returns a Boolean value.
 *
 *-----------------------------------------------------------------------------
 */

static int
ConnectionNeedCollationInfoMethod(
    ClientData clientData,	/* Completion type */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext objectContext, /* Object context */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {
    Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
				/* The current connection object */
    ConnectionData* cdata = (ConnectionData*)
	Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
				/* Instance data */

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 2, objv, "");
	return TCL_ERROR;
    }

    Tcl_SetObjResult(interp, Tcl_NewIntObj(cdata->collationSizes == NULL));
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ConnectionRollbackMethod --
 *
 *	Method that requests that a pending transaction against a database
 * 	be rolled back.
 *
 * Usage:
 * 	$connection rollback
 *
 * Parameters:
 *	None.
 *
 * Results:
 *	Returns an empty Tcl result if successful, and throws an error
 *	otherwise.
 *
 *-----------------------------------------------------------------------------
 */

static int
ConnectionRollbackMethod(
    ClientData clientData,	/* Completion type */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext objectContext, /* Object context */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {
    Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
				/* The current connection object */
    ConnectionData* cdata = (ConnectionData*)
	Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
				/* Instance data */
    my_bool rc;		/* Result code from MySQL operations */

    /* Check parameters */

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 2, objv, "");
	return TCL_ERROR;
    }

    /* Reject the request if no transaction is in progress */

    if (!(cdata->flags & CONN_FLAG_IN_XCN)) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj("no transaction is in "
						  "progress", -1));
	Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY010",
			 "MYSQL", "-1", NULL);
	return TCL_ERROR;
    }

    /* End transaction, turn off "transaction in progress", and report status */

    rc = mysql_rollback(cdata->mysqlPtr);
    cdata->flags &= ~CONN_FLAG_IN_XCN;
    if (rc) {
	TransferMysqlError(interp, cdata->mysqlPtr);
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ConnectionSetCollationInfoMethod --
 *
 *	Internal method that saves the character lengths of the collations
 *
 * Usage:
 *	$connection SetCollationInfo {collationNum size} ...
 *
 * Parameters:
 *	One or more pairs of collation number and character length,
 *	ordered in decreasing sequence by collation number.
 *
 * Results:
 *	None.
 *
 * The [$connection columns $table] method needs to know the sizes
 * of characters in a given column's collation and character set.
 * This information is available by querying INFORMATION_SCHEMA, which
 * is easier to do from Tcl than C. This method passes in the results.
 *
 *-----------------------------------------------------------------------------
 */

static int
ConnectionSetCollationInfoMethod(
    ClientData clientData,	/* Completion type */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext objectContext, /* Object context */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {
    Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
				/* The current connection object */
    ConnectionData* cdata = (ConnectionData*)
	Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
				/* Instance data */
    int listLen;
    Tcl_Obj* objPtr;
    unsigned int collationNum;
    int i;
    int t;

    if (objc <= 2) {
	Tcl_WrongNumArgs(interp, 2, objv, "{collationNum size}...");
	return TCL_ERROR;
    }
    if (Tcl_ListObjIndex(interp, objv[2], 0, &objPtr) != TCL_OK) {
	return TCL_ERROR;
    }
    if (Tcl_GetIntFromObj(interp, objPtr, &t) != TCL_OK) {
	return TCL_ERROR;
    }
    cdata->nCollations = (unsigned int)(t+1);
    if (cdata->collationSizes) {
	ckfree((char*) cdata->collationSizes);
    }
    cdata->collationSizes =
	(int*) ckalloc(cdata->nCollations * sizeof(int));
    memset(cdata->collationSizes, 0, cdata->nCollations * sizeof(int));
    for (i = 2; i < objc; ++i) {
	if (Tcl_ListObjLength(interp, objv[i], &listLen) != TCL_OK) {
	    return TCL_ERROR;
	}
	if (listLen != 2) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj("args must be 2-element "
						      "lists", -1));
	    return TCL_ERROR;
	}
	if (Tcl_ListObjIndex(interp, objv[i], 0, &objPtr) != TCL_OK
	    || Tcl_GetIntFromObj(interp, objPtr, &t) != TCL_OK) {
	    return TCL_ERROR;
	}
	collationNum = (unsigned int) t;
	if (collationNum > cdata->nCollations) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj("collations must be "
						      "in decreasing sequence",
						      -1));
	    return TCL_ERROR;
	}
	if ((Tcl_ListObjIndex(interp, objv[i], 1, &objPtr) != TCL_OK)
	    || (Tcl_GetIntFromObj(interp, objPtr,
				 cdata->collationSizes+collationNum)
		!= TCL_OK)) {
	    return TCL_ERROR;
	}
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ConnectionTablesMethod --
 *
 *	Method that asks for the names of tables in the database (optionally
 *	matching a given pattern
 *
 * Usage:
 * 	$connection tables ?pattern?
 *
 * Parameters:
 *	None.
 *
 * Results:
 *	Returns the list of tables
 *
 *-----------------------------------------------------------------------------
 */

static int
ConnectionTablesMethod(
    ClientData clientData,	/* Completion type */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext objectContext, /* Object context */
    int objc,			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {
    Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
				/* The current connection object */
    ConnectionData* cdata = (ConnectionData*)
	Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
				/* Instance data */
    Tcl_Obj** literals = cdata->pidata->literals;
				/* Literal pool */
    const char* patternStr = NULL;
				/* Pattern to match table names */
    MYSQL_RES* results = NULL;	/* Result set */
    MYSQL_ROW row = NULL;	/* Row in the result set */
    int status = TCL_OK;	/* Return status */
    Tcl_Obj* retval = NULL;	/* List of table names */

    /* Check parameters */

    if (objc == 2) {
	patternStr = NULL;
    } else if (objc == 3) {
	patternStr = Tcl_GetString(objv[2]);
    } else {
	Tcl_WrongNumArgs(interp, 2, objv, "");
	return TCL_ERROR;
    }

    results = mysql_list_tables(cdata->mysqlPtr, patternStr);
    if (results == NULL) {
	TransferMysqlError(interp, cdata->mysqlPtr);
	return TCL_ERROR;
    } else {
	retval = Tcl_NewObj();
	Tcl_IncrRefCount(retval);
	while ((row = mysql_fetch_row(results)) != NULL) {
	    unsigned long * lengths = mysql_fetch_lengths(results);
	    if (row[0]) {
		Tcl_ListObjAppendElement(NULL, retval,
					 Tcl_NewStringObj(row[0],
							  (int)lengths[0]));
		Tcl_ListObjAppendElement(NULL, retval, literals[LIT_EMPTY]);
	    }
	}
	if (mysql_errno(cdata->mysqlPtr)) {
	    TransferMysqlError(interp, cdata->mysqlPtr);
	    status = TCL_ERROR;
	}
	if (status == TCL_OK) {
	    Tcl_SetObjResult(interp, retval);
	}
	Tcl_DecrRefCount(retval);
	mysql_free_result(results);
	return status;
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * DeleteCmd --
 *
 *	Callback executed when the initialization method of the connection
 *	class is deleted.
 *
 * Side effects:
 *	Dismisses the environment, which has the effect of shutting
 *	down MYSQL when it is no longer required.
 *
 *-----------------------------------------------------------------------------
 */

static void
DeleteCmd (
    ClientData clientData	/* Environment handle */
) {
    PerInterpData* pidata = (PerInterpData*) clientData;
    DecrPerInterpRefCount(pidata);
}

/*
 *-----------------------------------------------------------------------------
 *
 * CloneCmd --
 *
 *	Callback executed when any of the MYSQL client methods is cloned.
 *
 * Results:
 *	Returns TCL_OK to allow the method to be copied.
 *
 * Side effects:
 *	Obtains a fresh copy of the environment handle, to keep the
 *	refcounts accurate
 *
 *-----------------------------------------------------------------------------
 */

static int
CloneCmd(
    Tcl_Interp* interp,		/* Tcl interpreter */
    ClientData oldClientData,	/* Environment handle to be discarded */
    ClientData* newClientData	/* New environment handle to be used */
) {
    *newClientData = oldClientData;
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * DeleteConnectionMetadata, DeleteConnection --
 *
 *	Cleans up when a database connection is deleted.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Terminates the connection and frees all system resources associated
 *	with it.
 *
 *-----------------------------------------------------------------------------
 */

static void
DeleteConnectionMetadata(
    ClientData clientData	/* Instance data for the connection */
) {
    DecrConnectionRefCount((ConnectionData*)clientData);
}

static void
DeleteConnection(
    ConnectionData* cdata	/* Instance data for the connection */
) {
    if (cdata->collationSizes != NULL) {
	ckfree((char*) cdata->collationSizes);
    }
    if (cdata->mysqlPtr != NULL) {
	mysql_close(cdata->mysqlPtr);
    }
    DecrPerInterpRefCount(cdata->pidata);
    ckfree((char*) cdata);
}

/*
 *-----------------------------------------------------------------------------
 *
 * CloneConnection --
 *
 *	Attempts to clone an MYSQL connection's metadata.
 *
 * Results:
 *	Returns the new metadata
 *
 * At present, we don't attempt to clone connections - it's not obvious
 * that such an action would ever even make sense.  Instead, we return NULL
 * to indicate that the metadata should not be cloned. (Note that this
 * action isn't right, either. What *is* right is to indicate that the object
 * is not clonable, but the API gives us no way to do that.
 *
 *-----------------------------------------------------------------------------
 */

static int
CloneConnection(
    Tcl_Interp* interp,		/* Tcl interpreter for error reporting */
    ClientData metadata,	/* Metadata to be cloned */
    ClientData* newMetaData	/* Where to put the cloned metadata */
) {
    Tcl_SetObjResult(interp,
		     Tcl_NewStringObj("MYSQL connections are not clonable", -1));
    return TCL_ERROR;
}

/*
 *-----------------------------------------------------------------------------
 *
 * NewStatement --
 *
 *	Creates an empty object to hold statement data.
 *
 * Results:
 *	Returns a pointer to the newly-created object.
 *
 *-----------------------------------------------------------------------------
 */

static StatementData*
NewStatement(
    ConnectionData* cdata	/* Instance data for the connection */
) {
    StatementData* sdata = (StatementData*) ckalloc(sizeof(StatementData));
    sdata->refCount = 1;
    sdata->cdata = cdata;
    IncrConnectionRefCount(cdata);
    sdata->subVars = Tcl_NewObj();
    Tcl_IncrRefCount(sdata->subVars);
    sdata->params = NULL;
    sdata->nativeSql = NULL;
    sdata->stmtPtr = NULL;
    sdata->metadataPtr = NULL;
    sdata->columnNames = NULL;
    sdata->flags = 0;
    return sdata;
}

/*
 *-----------------------------------------------------------------------------
 *
 * AllocAndPrepareStatement --
 *
 *	Allocate space for a MySQL prepared statement, and prepare the
 *	statement.
 *
 * Results:
 *	Returns the statement handle if successful, and NULL on failure.
 *
 * Side effects:
 *	Prepares the statement.
 *	Stores error message and error code in the interpreter on failure.
 *
 *-----------------------------------------------------------------------------
 */

static MYSQL_STMT*
AllocAndPrepareStatement(
    Tcl_Interp* interp,		/* Tcl interpreter for error reporting */
    StatementData* sdata	/* Statement data */
) {
    ConnectionData* cdata = sdata->cdata;
				/* Connection data */
    MYSQL_STMT* stmtPtr;	/* Statement handle */
    const char* nativeSqlStr;	/* Native SQL statement to prepare */
    int nativeSqlLen;		/* Length of the statement */

    /* Allocate space for the prepared statement */

    stmtPtr = mysql_stmt_init(cdata->mysqlPtr);
    /*
     * MySQL allows only one writable cursor open at a time, and
     * the default cursor type is writable. Make all our cursors
     * read-only to avoid 'Commands out of sync' errors.
     */

    if (stmtPtr == NULL) {
	TransferMysqlError(interp, cdata->mysqlPtr);
    } else {

	/* Prepare the statement */

	nativeSqlStr = Tcl_GetStringFromObj(sdata->nativeSql, &nativeSqlLen);
	if (mysql_stmt_prepare(stmtPtr, nativeSqlStr, nativeSqlLen)) {
	    TransferMysqlStmtError(interp, stmtPtr);
	    mysql_stmt_close(stmtPtr);
	    stmtPtr = NULL;
	}
    }
    return stmtPtr;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ResultDescToTcl --
 *
 *	Converts a MySQL result description for return as a Tcl list.
 *
 * Results:
 *	Returns a Tcl object holding the result description
 *
 * If any column names are duplicated, they are disambiguated by
 * appending '#n' where n increments once for each occurrence of the
 * column name.
 *
 *-----------------------------------------------------------------------------
 */

static Tcl_Obj*
ResultDescToTcl(
    MYSQL_RES* result,		/* Result set description */
    int flags			/* Flags governing the conversion */
) {
    Tcl_Obj* retval = Tcl_NewObj();
    Tcl_HashTable names;	/* Hash table to resolve name collisions */
    Tcl_Obj* nameObj;		/* Name of a result column */
    int new;			/* Flag == 1 if a result column is unique */
    Tcl_HashEntry* entry;	/* Hash table entry for a column name */
    int count;			/* Number used to disambiguate a column name */

    Tcl_InitHashTable(&names, TCL_STRING_KEYS);
    if (result != NULL) {
	unsigned int fieldCount = mysql_num_fields(result);
	MYSQL_FIELD* fields = mysql_fetch_fields(result);
	unsigned int i;
	char numbuf[16];
	for (i = 0; i < fieldCount; ++i) {
	    MYSQL_FIELD* field = MysqlFieldIndex(fields, i);
	    nameObj = Tcl_NewStringObj(field->name, field->name_length);
	    Tcl_IncrRefCount(nameObj);
	    entry = Tcl_CreateHashEntry(&names, field->name, &new);
	    count = 1;
	    while (!new) {
		count = (int) Tcl_GetHashValue(entry);
		++count;
		Tcl_SetHashValue(entry, (ClientData) count);
		sprintf(numbuf, "#%d", count);
		Tcl_AppendToObj(nameObj, numbuf, -1);
		entry = Tcl_CreateHashEntry(&names, Tcl_GetString(nameObj),
					    &new);
	    }
	    Tcl_SetHashValue(entry, (ClientData) count);
	    Tcl_ListObjAppendElement(NULL, retval, nameObj);
	    Tcl_DecrRefCount(nameObj);
	}
    }
    Tcl_DeleteHashTable(&names);
    return retval;
}

/*
 *-----------------------------------------------------------------------------
 *
 * StatementConstructor --
 *
 *	C-level initialization for the object representing an MySQL prepared
 *	statement.
 *
 * Usage:
 *	statement new connection statementText
 *	statement create name connection statementText
 *
 * Parameters:
 *      connection -- the MySQL connection object
 *	statementText -- text of the statement to prepare.
 *
 * Results:
 *	Returns a standard Tcl result
 *
 * Side effects:
 *	Prepares the statement, and stores it (plus a reference to the
 *	connection) in instance metadata.
 *
 *-----------------------------------------------------------------------------
 */

static int
StatementConstructor(
    ClientData clientData,	/* Not used */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext context,	/* Object context  */
    int objc, 			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {

    Tcl_Object thisObject = Tcl_ObjectContextObject(context);
				/* The current statement object */
    int skip = Tcl_ObjectContextSkippedArgs(context);
				/* Number of args to skip before the
				 * payload arguments */
    Tcl_Object connectionObject;
				/* The database connection as a Tcl_Object */
    ConnectionData* cdata;	/* The connection object's data */
    StatementData* sdata;	/* The statement's object data */
    Tcl_Obj* tokens;		/* The tokens of the statement to be prepared */
    int tokenc;			/* Length of the 'tokens' list */
    Tcl_Obj** tokenv;		/* Exploded tokens from the list */
    Tcl_Obj* nativeSql;		/* SQL statement mapped to native form */
    char* tokenStr;		/* Token string */
    int tokenLen;		/* Length of a token */
    int nParams;		/* Number of parameters of the statement */
    int i;

    /* Find the connection object, and get its data. */

    thisObject = Tcl_ObjectContextObject(context);
    if (objc != skip+2) {
	Tcl_WrongNumArgs(interp, skip, objv, "connection statementText");
	return TCL_ERROR;
    }

    connectionObject = Tcl_GetObjectFromObj(interp, objv[skip]);
    if (connectionObject == NULL) {
	return TCL_ERROR;
    }
    cdata = (ConnectionData*) Tcl_ObjectGetMetadata(connectionObject,
						    &connectionDataType);
    if (cdata == NULL) {
	Tcl_AppendResult(interp, Tcl_GetString(objv[skip]),
			 " does not refer to a MySQL connection", NULL);
	return TCL_ERROR;
    }

    /*
     * Allocate an object to hold data about this statement
     */

    sdata = NewStatement(cdata);

    /* Tokenize the statement */

    tokens = Tdbc_TokenizeSql(interp, Tcl_GetString(objv[skip+1]));
    if (tokens == NULL) {
	goto freeSData;
    }
    Tcl_IncrRefCount(tokens);

    /*
     * Rewrite the tokenized statement to MySQL syntax. Reject the
     * statement if it is actually multiple statements.
     */

    if (Tcl_ListObjGetElements(interp, tokens, &tokenc, &tokenv) != TCL_OK) {
	goto freeTokens;
    }
    nativeSql = Tcl_NewObj();
    Tcl_IncrRefCount(nativeSql);
    for (i = 0; i < tokenc; ++i) {
	tokenStr = Tcl_GetStringFromObj(tokenv[i], &tokenLen);

	switch (tokenStr[0]) {
	case '$':
	case ':':
	case '@':
	    Tcl_AppendToObj(nativeSql, "?", 1);
	    Tcl_ListObjAppendElement(NULL, sdata->subVars,
				     Tcl_NewStringObj(tokenStr+1, tokenLen-1));
	    break;

	case ';':
	    Tcl_SetObjResult(interp,
			     Tcl_NewStringObj("tdbc::mysql"
					      " does not support semicolons "
					      "in statements", -1));
	    goto freeNativeSql;
	    break;

	default:
	    Tcl_AppendToObj(nativeSql, tokenStr, tokenLen);
	    break;

	}
    }
    sdata->nativeSql = nativeSql;
    Tcl_DecrRefCount(tokens);

    /* Prepare the statement */

    sdata->stmtPtr = AllocAndPrepareStatement(interp, sdata);
    if (sdata->stmtPtr == NULL) {
	goto freeSData;
    }

    /* Get result set metadata */

    sdata->metadataPtr = mysql_stmt_result_metadata(sdata->stmtPtr);
    if (mysql_stmt_errno(sdata->stmtPtr)) {
	TransferMysqlStmtError(interp, sdata->stmtPtr);
	goto freeSData;
    }
    sdata->columnNames = ResultDescToTcl(sdata->metadataPtr, 0);
    Tcl_IncrRefCount(sdata->columnNames);

    Tcl_ListObjLength(NULL, sdata->subVars, &nParams);
    sdata->params = (ParamData*) ckalloc(nParams * sizeof(ParamData));
    for (i = 0; i < nParams; ++i) {
	sdata->params[i].flags = PARAM_IN;
	sdata->params[i].dataType = MYSQL_TYPE_VARCHAR;
	sdata->params[i].precision = 0;
	sdata->params[i].scale = 0;
    }

    /* Attach the current statement data as metadata to the current object */

    Tcl_ObjectSetMetadata(thisObject, &statementDataType, (ClientData) sdata);
    return TCL_OK;

    /* On error, unwind all the resource allocations */

 freeNativeSql:
    Tcl_DecrRefCount(nativeSql);
 freeTokens:
    Tcl_DecrRefCount(tokens);
 freeSData:
    DecrStatementRefCount(sdata);
    return TCL_ERROR;
}

/*
 *-----------------------------------------------------------------------------
 *
 * StatementParamsMethod --
 *
 *	Lists the parameters in a MySQL statement.
 *
 * Usage:
 *	$statement params
 *
 * Results:
 *	Returns a standard Tcl result containing a dictionary. The keys
 *	of the dictionary are parameter names, and the values are parameter
 *	types, themselves expressed as dictionaries containing the keys,
 *	'name', 'direction', 'type', 'precision', 'scale' and 'nullable'.
 *
 *
 *-----------------------------------------------------------------------------
 */

static int
StatementParamsMethod(
    ClientData clientData,	/* Not used */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext context,	/* Object context  */
    int objc, 			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {
    Tcl_Object thisObject = Tcl_ObjectContextObject(context);
				/* The current statement object */
    StatementData* sdata	/* The current statement */
	= (StatementData*) Tcl_ObjectGetMetadata(thisObject,
						 &statementDataType);
    ConnectionData* cdata = sdata->cdata;
    PerInterpData* pidata = cdata->pidata; /* Per-interp data */
    Tcl_Obj** literals = pidata->literals; /* Literal pool */
    int nParams;		/* Number of parameters to the statement */
    Tcl_Obj* paramName;		/* Name of a parameter */
    Tcl_Obj* paramDesc;		/* Description of one parameter */
    Tcl_Obj* dataTypeName;	/* Name of a parameter's data type */
    Tcl_Obj* retVal;		/* Return value from this command */
    Tcl_HashEntry* typeHashEntry;
    int i;

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 2, objv, "");
	return TCL_ERROR;
    }

    retVal = Tcl_NewObj();
    Tcl_ListObjLength(NULL, sdata->subVars, &nParams);
    for (i = 0; i < nParams; ++i) {
	paramDesc = Tcl_NewObj();
	Tcl_ListObjIndex(NULL, sdata->subVars, i, &paramName);
	Tcl_DictObjPut(NULL, paramDesc, literals[LIT_NAME], paramName);
	switch (sdata->params[i].flags & (PARAM_IN | PARAM_OUT)) {
	case PARAM_IN:
	    Tcl_DictObjPut(NULL, paramDesc, literals[LIT_DIRECTION],
			   literals[LIT_IN]);
	    break;
	case PARAM_OUT:
	    Tcl_DictObjPut(NULL, paramDesc, literals[LIT_DIRECTION],
			   literals[LIT_OUT]);
	    break;
	case PARAM_IN | PARAM_OUT:
	    Tcl_DictObjPut(NULL, paramDesc, literals[LIT_DIRECTION],
			   literals[LIT_INOUT]);
	    break;
	default:
	    break;
	}
	typeHashEntry =
	    Tcl_FindHashEntry(&(pidata->typeNumHash),
			      (const char*) (sdata->params[i].dataType));
	if (typeHashEntry != NULL) {
	    dataTypeName = (Tcl_Obj*) Tcl_GetHashValue(typeHashEntry);
	    Tcl_DictObjPut(NULL, paramDesc, literals[LIT_TYPE], dataTypeName);
	}
	Tcl_DictObjPut(NULL, paramDesc, literals[LIT_PRECISION],
		       Tcl_NewIntObj(sdata->params[i].precision));
	Tcl_DictObjPut(NULL, paramDesc, literals[LIT_SCALE],
		       Tcl_NewIntObj(sdata->params[i].scale));
	Tcl_DictObjPut(NULL, retVal, paramName, paramDesc);
    }

    Tcl_SetObjResult(interp, retVal);
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * StatementParamtypeMethod --
 *
 *	Defines a parameter type in a MySQL statement.
 *
 * Usage:
 *	$statement paramtype paramName ?direction? type ?precision ?scale??
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * Side effects:
 *	Updates the description of the given parameter.
 *
 *-----------------------------------------------------------------------------
 */

static int
StatementParamtypeMethod(
    ClientData clientData,	/* Not used */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext context,	/* Object context  */
    int objc, 			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {
    Tcl_Object thisObject = Tcl_ObjectContextObject(context);
				/* The current statement object */
    StatementData* sdata	/* The current statement */
	= (StatementData*) Tcl_ObjectGetMetadata(thisObject,
						 &statementDataType);
    static const struct {
	const char* name;
	int flags;
    } directions[] = {
	{ "in", 	PARAM_IN },
	{ "out",	PARAM_OUT },
	{ "inout",	PARAM_IN | PARAM_OUT },
	{ NULL,		0 }
    };
    int direction;
    int typeNum;		/* Data type number of a parameter */
    int precision;		/* Data precision */
    int scale;			/* Data scale */

    int nParams;		/* Number of parameters to the statement */
    const char* paramName;	/* Name of the parameter being set */
    Tcl_Obj* targetNameObj;	/* Name of the ith parameter in the statement */
    const char* targetName;	/* Name of a candidate parameter in the
				 * statement */
    int matchCount = 0;		/* Number of parameters matching the name */
    Tcl_Obj* errorObj;		/* Error message */

    int i;

    /* Check parameters */

    if (objc < 4) {
	goto wrongNumArgs;
    }

    i = 3;
    if (Tcl_GetIndexFromObjStruct(interp, objv[i], directions,
				  sizeof(directions[0]), "direction",
				  TCL_EXACT, &direction) != TCL_OK) {
	direction = PARAM_IN;
	Tcl_ResetResult(interp);
    } else {
	++i;
    }
    if (i >= objc) goto wrongNumArgs;
    if (Tcl_GetIndexFromObjStruct(interp, objv[i], dataTypes,
				  sizeof(dataTypes[0]), "SQL data type",
				  TCL_EXACT, &typeNum) == TCL_OK) {
	++i;
    } else {
	return TCL_ERROR;
    }
    if (i < objc) {
	if (Tcl_GetIntFromObj(interp, objv[i], &precision) == TCL_OK) {
	    ++i;
	} else {
	    return TCL_ERROR;
	}
    }
    if (i < objc) {
	if (Tcl_GetIntFromObj(interp, objv[i], &scale) == TCL_OK) {
	    ++i;
	} else {
	    return TCL_ERROR;
	}
    }
    if (i != objc) {
	goto wrongNumArgs;
    }

    /* Look up parameters by name. */

    Tcl_ListObjLength(NULL, sdata->subVars, &nParams);
    paramName = Tcl_GetString(objv[2]);
    for (i = 0; i < nParams; ++i) {
	Tcl_ListObjIndex(NULL, sdata->subVars, i, &targetNameObj);
	targetName = Tcl_GetString(targetNameObj);
	if (!strcmp(paramName, targetName)) {
	    ++matchCount;
	    sdata->params[i].flags = direction;
	    sdata->params[i].dataType = dataTypes[typeNum].num;
	    sdata->params[i].precision = precision;
	    sdata->params[i].scale = scale;
	}
    }
    if (matchCount == 0) {
	errorObj = Tcl_NewStringObj("unknown parameter \"", -1);
	Tcl_AppendToObj(errorObj, paramName, -1);
	Tcl_AppendToObj(errorObj, "\": must be ", -1);
	for (i = 0; i < nParams; ++i) {
	    Tcl_ListObjIndex(NULL, sdata->subVars, i, &targetNameObj);
	    Tcl_AppendObjToObj(errorObj, targetNameObj);
	    if (i < nParams-2) {
		Tcl_AppendToObj(errorObj, ", ", -1);
	    } else if (i == nParams-2) {
		Tcl_AppendToObj(errorObj, " or ", -1);
	    }
	}
	Tcl_SetObjResult(interp, errorObj);
	return TCL_ERROR;
    }

    return TCL_OK;

 wrongNumArgs:
    Tcl_WrongNumArgs(interp, 2, objv,
		     "name ?direction? type ?precision ?scale??");
    return TCL_ERROR;
}

/*
 *-----------------------------------------------------------------------------
 *
 * DeleteStatementMetadata, DeleteStatement --
 *
 *	Cleans up when a MySQL statement is no longer required.
 *
 * Side effects:
 *	Frees all resources associated with the statement.
 *
 *-----------------------------------------------------------------------------
 */

static void
DeleteStatementMetadata(
    ClientData clientData	/* Instance data for the connection */
) {
    DecrStatementRefCount((StatementData*)clientData);
}
static void
DeleteStatement(
    StatementData* sdata	/* Metadata for the statement */
) {
    if (sdata->columnNames != NULL) {
	Tcl_DecrRefCount(sdata->columnNames);
    }
    if (sdata->metadataPtr != NULL) {
	mysql_free_result(sdata->metadataPtr);
    }
    if (sdata->stmtPtr != NULL) {
	mysql_stmt_close(sdata->stmtPtr);
    }
    if (sdata->nativeSql != NULL) {
	Tcl_DecrRefCount(sdata->nativeSql);
    }
    if (sdata->params != NULL) {
	ckfree((char*)sdata->params);
    }
    Tcl_DecrRefCount(sdata->subVars);
    DecrConnectionRefCount(sdata->cdata);
    ckfree((char*)sdata);
}

/*
 *-----------------------------------------------------------------------------
 *
 * CloneStatement --
 *
 *	Attempts to clone a MySQL statement's metadata.
 *
 * Results:
 *	Returns the new metadata
 *
 * At present, we don't attempt to clone statements - it's not obvious
 * that such an action would ever even make sense.  Instead, we return NULL
 * to indicate that the metadata should not be cloned. (Note that this
 * action isn't right, either. What *is* right is to indicate that the object
 * is not clonable, but the API gives us no way to do that.
 *
 *-----------------------------------------------------------------------------
 */

static int
CloneStatement(
    Tcl_Interp* interp,		/* Tcl interpreter for error reporting */
    ClientData metadata,	/* Metadata to be cloned */
    ClientData* newMetaData	/* Where to put the cloned metadata */
) {
    Tcl_SetObjResult(interp,
		     Tcl_NewStringObj("MySQL statements are not clonable", -1));
    return TCL_ERROR;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ResultSetConstructor --
 *
 *	Constructs a new result set.
 *
 * Usage:
 *	$resultSet new statement ?dictionary?
 *	$resultSet create name statement ?dictionary?
 *
 * Parameters:
 *	statement -- Statement handle to which this resultset belongs
 *	dictionary -- Dictionary containing the substitutions for named
 *		      parameters in the given statement.
 *
 * Results:
 *	Returns a standard Tcl result.  On error, the interpreter result
 *	contains an appropriate message.
 *
 *-----------------------------------------------------------------------------
 */

static int
ResultSetConstructor(
    ClientData clientData,	/* Not used */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext context,	/* Object context  */
    int objc, 			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {

    Tcl_Object thisObject = Tcl_ObjectContextObject(context);
				/* The current result set object */
    int skip = Tcl_ObjectContextSkippedArgs(context);
				/* Number of args to skip */
    Tcl_Object statementObject;	/* The current statement object */
    ConnectionData* cdata;	/* The MySQL connection object's data */
    StatementData* sdata;	/* The statement object's data */
    ResultSetData* rdata;	/* THe result set object's data */
    int nParams;		/* The parameter count on the statement */
    int nBound;			/* Number of parameters bound so far */
    Tcl_Obj* paramNameObj;	/* Name of the current parameter */
    const char* paramName;	/* Name of the current parameter */
    Tcl_Obj* paramValObj;	/* Value of the current parameter */
    const char* paramValStr;	/* String value of the current parameter */
    char* bufPtr;		/* Pointer to the parameter buffer */
    int len;			/* Length of a bound parameter */
    int nColumns;		/* Number of columns in the result set */
    MYSQL_FIELD* fields = NULL;	/* Description of columns of the result set */
    MYSQL_BIND* resultBindings;	/* Bindings of the columns of the result set */
    unsigned long* resultLengths;
				/* Lengths of the columns of the result set */
    int i;

    /* Check parameter count */

    if (objc != skip+1 && objc != skip+2) {
	Tcl_WrongNumArgs(interp, skip, objv, "statement ?dictionary?");
	return TCL_ERROR;
    }

    /* Initialize the base classes */

    Tcl_ObjectContextInvokeNext(interp, context, skip, objv, skip);

    /* Find the statement object, and get the statement data */

    statementObject = Tcl_GetObjectFromObj(interp, objv[skip]);
    if (statementObject == NULL) {
	return TCL_ERROR;
    }
    sdata = (StatementData*) Tcl_ObjectGetMetadata(statementObject,
						   &statementDataType);
    if (sdata == NULL) {
	Tcl_AppendResult(interp, Tcl_GetString(objv[skip]),
			 " does not refer to a MySQL statement", NULL);
	return TCL_ERROR;
    }
    Tcl_ListObjLength(NULL, sdata->columnNames, &nColumns);
    cdata = sdata->cdata;

    /*
     * If there is no transaction in progress, turn on auto-commit so that
     * this statement will execute directly.
     */

    if ((cdata->flags & (CONN_FLAG_IN_XCN | CONN_FLAG_AUTOCOMMIT)) == 0) {
	if (mysql_autocommit(cdata->mysqlPtr, 1)) {
	    TransferMysqlError(interp, cdata->mysqlPtr);
	    return TCL_ERROR;
	}
	cdata->flags |= CONN_FLAG_AUTOCOMMIT;
    }

    /* Allocate an object to hold data about this result set */

    rdata = (ResultSetData*) ckalloc(sizeof(ResultSetData));
    rdata->refCount = 1;
    rdata->sdata = sdata;
    rdata->stmtPtr = NULL;
    rdata->paramValues = NULL;
    rdata->paramBindings = NULL;
    rdata->paramLengths = NULL;
    rdata->rowCount = 0;
    rdata->resultErrors = (my_bool*) ckalloc(nColumns * sizeof(my_bool));
    rdata->resultNulls = (my_bool*) ckalloc(nColumns * sizeof(my_bool));
    resultLengths = rdata->resultLengths = (unsigned long*)
	ckalloc(nColumns * sizeof(unsigned long));
    rdata->resultBindings = resultBindings = MysqlBindAlloc(nColumns);
    IncrStatementRefCount(sdata);
    Tcl_ObjectSetMetadata(thisObject, &resultSetDataType, (ClientData) rdata);

    /* Make bindings for all the result columns. Defer binding variable
     * length fields until first execution. */

    if (nColumns > 0) {
	fields = mysql_fetch_fields(sdata->metadataPtr);
    }
    for (i = 0; i < nColumns; ++i) {
	MYSQL_FIELD* field = MysqlFieldIndex(fields, i);
	switch (field->type) {

	case MYSQL_TYPE_FLOAT:
	case MYSQL_TYPE_DOUBLE:
	    MysqlBindSetBufferType(resultBindings, i,  MYSQL_TYPE_DOUBLE);
	    MysqlBindAllocBuffer(resultBindings, i, sizeof(double));
	    resultLengths[i] = sizeof(double);
	    break;

	case MYSQL_TYPE_BIT:
	    MysqlBindSetBufferType(resultBindings, i,  MYSQL_TYPE_BIT);
	    MysqlBindAllocBuffer(resultBindings, i, field->length);
	    resultLengths[i] = field->length;
	    break;

	case MYSQL_TYPE_LONGLONG:
	    MysqlBindSetBufferType(resultBindings, i,  MYSQL_TYPE_LONGLONG);
	    MysqlBindAllocBuffer(resultBindings, i, sizeof(Tcl_WideInt));
	    resultLengths[i] = sizeof(Tcl_WideInt);
	    break;

	case MYSQL_TYPE_TINY:
	case MYSQL_TYPE_SHORT:
	case MYSQL_TYPE_INT24:
	case MYSQL_TYPE_LONG:
	    MysqlBindSetBufferType(resultBindings, i,  MYSQL_TYPE_LONG);
	    MysqlBindAllocBuffer(resultBindings, i, sizeof(int));
	    resultLengths[i] = sizeof(int);
	    break;

	default:
	    MysqlBindSetBufferType(resultBindings, i,  MYSQL_TYPE_STRING);
	    MysqlBindAllocBuffer(resultBindings, i, 0);
	    resultLengths[i] = 0;
	    break;
	}
	MysqlBindSetLength(resultBindings, i, rdata->resultLengths + i);
	rdata->resultNulls[i] = 0;
	MysqlBindSetIsNull(resultBindings, i, rdata->resultNulls + i);
	rdata->resultErrors[i] = 0;
	MysqlBindSetError(resultBindings, i, rdata->resultErrors + i);
    }

    /*
     * Find a statement handle that we can use to execute the SQL code.
     * If the main statement handle associated with the statement
     * is idle, we can use it.  Otherwise, we have to allocate and
     * prepare a fresh one.
     */

    if (sdata->flags & STMT_FLAG_BUSY) {
	rdata->stmtPtr = AllocAndPrepareStatement(interp, sdata);
	if (rdata->stmtPtr == NULL) {
	    return TCL_ERROR;
	}
    } else {
	rdata->stmtPtr = sdata->stmtPtr;
	sdata->flags |= STMT_FLAG_BUSY;
    }

    /* Allocate the parameter bindings */

    Tcl_ListObjLength(NULL, sdata->subVars, &nParams);
    rdata->paramValues = Tcl_NewObj();
    Tcl_IncrRefCount(rdata->paramValues);
    rdata->paramBindings = MysqlBindAlloc(nParams);
    rdata->paramLengths = (unsigned long*) ckalloc(nParams
						   * sizeof(unsigned long));
    for (nBound = 0; nBound < nParams; ++nBound) {
	MysqlBindSetBufferType(rdata->paramBindings, nBound, MYSQL_TYPE_NULL);
    }

    /* Bind the substituted parameters */

    for (nBound = 0; nBound < nParams; ++nBound) {
	Tcl_ListObjIndex(NULL, sdata->subVars, nBound, &paramNameObj);
	paramName = Tcl_GetString(paramNameObj);
	if (objc == skip+2) {

	    /* Param from a dictionary */

	    if (Tcl_DictObjGet(interp, objv[skip+1],
			       paramNameObj, &paramValObj) != TCL_OK) {
		return TCL_ERROR;
	    }
	} else {

	    /* Param from a variable */

	    paramValObj = Tcl_GetVar2Ex(interp, paramName, NULL,
					TCL_LEAVE_ERR_MSG);
	}

	/*
	 * At this point, paramValObj contains the parameter to bind.
	 * Convert the parameters to the appropriate data types for
	 * MySQL's prepared statement interface, and bind them.
	 */

	if (paramValObj != NULL) {
	    switch (sdata->params[nBound].dataType & 0xffff) {

	    case MYSQL_TYPE_NEWDECIMAL:
	    case MYSQL_TYPE_DECIMAL:
		if (sdata->params[nBound].scale == 0) {
		    if (sdata->params[nBound].precision < 10) {
			goto smallinteger;
		    } else if (sdata->params[nBound].precision < 19) {
			goto biginteger;
		    } else {
			goto charstring;
		    }
		} else if (sdata->params[nBound].precision < 17) {
		    goto real;
		} else {
		    goto charstring;
		}

	    case MYSQL_TYPE_FLOAT:
	    case MYSQL_TYPE_DOUBLE:
	    real:
		MysqlBindSetBufferType(rdata->paramBindings, nBound,
				       MYSQL_TYPE_DOUBLE);
		bufPtr = MysqlBindAllocBuffer(rdata->paramBindings,
					      nBound, sizeof(double));
		rdata->paramLengths[nBound] = sizeof(double);
		MysqlBindSetLength(rdata->paramBindings, nBound,
				   &(rdata->paramLengths[nBound]));
		if (Tcl_GetDoubleFromObj(interp, paramValObj,
					 (double*) bufPtr) != TCL_OK) {
		    return TCL_ERROR;
		}
		break;

	    case MYSQL_TYPE_BIT:
	    case MYSQL_TYPE_LONGLONG:
	    biginteger:
		MysqlBindSetBufferType(rdata->paramBindings, nBound,
				       MYSQL_TYPE_LONGLONG);
		bufPtr = MysqlBindAllocBuffer(rdata->paramBindings, nBound,
					      sizeof(Tcl_WideInt));
		rdata->paramLengths[nBound] = sizeof(Tcl_WideInt);
		MysqlBindSetLength(rdata->paramBindings, nBound,
				   &(rdata->paramLengths[nBound]));
		if (Tcl_GetWideIntFromObj(interp, paramValObj,
					  (Tcl_WideInt*) bufPtr) != TCL_OK) {
		    return TCL_ERROR;
		}
		break;

	    case MYSQL_TYPE_TINY:
	    case MYSQL_TYPE_SHORT:
	    case MYSQL_TYPE_INT24:
	    case MYSQL_TYPE_LONG:
	    smallinteger:
		MysqlBindSetBufferType(rdata->paramBindings, nBound,
				       MYSQL_TYPE_LONG);
		bufPtr = MysqlBindAllocBuffer(rdata->paramBindings, nBound,
					      sizeof(int));
		rdata->paramLengths[nBound] = sizeof(int);
		MysqlBindSetLength(rdata->paramBindings, nBound,
				   &(rdata->paramLengths[nBound]));
		if (Tcl_GetIntFromObj(interp, paramValObj,
				      (int*) bufPtr) != TCL_OK) {
		    return TCL_ERROR;
		}
		break;

	    default:
	    charstring:
		Tcl_ListObjAppendElement(NULL, rdata->paramValues, paramValObj);
		if (sdata->params[nBound].dataType & IS_BINARY) {
		    MysqlBindSetBufferType(rdata->paramBindings, nBound,
					   MYSQL_TYPE_BLOB);
		    paramValStr = (char*)
			Tcl_GetByteArrayFromObj(paramValObj, &len);
		} else {
		    MysqlBindSetBufferType(rdata->paramBindings, nBound,
					   MYSQL_TYPE_STRING);
		    paramValStr = Tcl_GetStringFromObj(paramValObj, &len);
		}
		bufPtr = MysqlBindAllocBuffer(rdata->paramBindings, nBound,
					      len+1);
		memcpy(bufPtr, paramValStr, len);
		rdata->paramLengths[nBound] = len;
		MysqlBindSetLength(rdata->paramBindings, nBound,
				   &(rdata->paramLengths[nBound]));
		break;

	    }
	} else {
	    MysqlBindSetBufferType(rdata->paramBindings, nBound,
				   MYSQL_TYPE_NULL);
	}
    }

    /* Execute the statement */

    /*
     * It is tempting to conserve client memory here by omitting
     * the call to 'mysql_stmt_store_result', but doing so causes
     * 'calls out of sync' errors when attempting to prepare a
     * statement while a result set is open. Certain of these errors
     * can, in turn, be avoided by using mysql_stmt_set_attr
     * and turning on "CURSOR_MODE_READONLY", but that, in turn
     * causes the server summarily to disconnect the client in
     * some tests.
     */

    if (mysql_stmt_bind_param(rdata->stmtPtr, rdata->paramBindings)
	|| ((nColumns > 0) && mysql_stmt_bind_result(rdata->stmtPtr,
						     resultBindings))
	|| mysql_stmt_execute(rdata->stmtPtr)
	|| mysql_stmt_store_result(rdata->stmtPtr) ) {
	TransferMysqlStmtError(interp, sdata->stmtPtr);
	return TCL_ERROR;
    }

    /* Determine and store the row count */

    rdata->rowCount = mysql_stmt_affected_rows(sdata->stmtPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ResultSetColumnsMethod --
 *
 *	Retrieves the list of columns from a result set.
 *
 * Usage:
 *	$resultSet columns
 *
 * Results:
 *	Returns the count of columns
 *
 *-----------------------------------------------------------------------------
 */

static int
ResultSetColumnsMethod(
    ClientData clientData,	/* Not used */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext context,	/* Object context  */
    int objc, 			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {

    Tcl_Object thisObject = Tcl_ObjectContextObject(context);
				/* The current result set object */
    ResultSetData* rdata = (ResultSetData*)
	Tcl_ObjectGetMetadata(thisObject, &resultSetDataType);
    StatementData* sdata = (StatementData*) rdata->sdata;

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 2, objv, "?pattern?");
	return TCL_ERROR;
    }

    Tcl_SetObjResult(interp, sdata->columnNames);

    return TCL_OK;

}

/*
 *-----------------------------------------------------------------------------
 *
 * ResultSetNextrowMethod --
 *
 *	Retrieves the next row from a result set.
 *
 * Usage:
 *	$resultSet nextrow ?-as lists|dicts? ?--? variableName
 *
 * Options:
 *	-as	Selects the desired form for returning the results.
 *
 * Parameters:
 *	variableName -- Variable in which the results are to be returned
 *
 * Results:
 *	Returns a standard Tcl result.  The interpreter result is 1 if there
 *	are more rows remaining, and 0 if no more rows remain.
 *
 * Side effects:
 *	Stores in the given variable either a list or a dictionary
 *	containing one row of the result set.
 *
 *-----------------------------------------------------------------------------
 */

static int
ResultSetNextrowMethod(
    ClientData clientData,	/* Not used */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext context,	/* Object context  */
    int objc, 			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {

    int lists = (int) clientData;
				/* Flag == 1 if lists are to be returned,
				 * 0 if dicts are to be returned */

    Tcl_Object thisObject = Tcl_ObjectContextObject(context);
				/* The current result set object */
    ResultSetData* rdata = (ResultSetData*)
	Tcl_ObjectGetMetadata(thisObject, &resultSetDataType);
				/* Data pertaining to the current result set */
    StatementData* sdata = (StatementData*) rdata->sdata;
				/* Statement that yielded the result set */
    ConnectionData* cdata = (ConnectionData*) sdata->cdata;
				/* Connection that opened the statement */
    PerInterpData* pidata = (PerInterpData*) cdata->pidata;
				/* Per interpreter data */
    Tcl_Obj** literals = pidata->literals;
				/* Literal pool */

    int nColumns = 0;		/* Number of columns in the result set */
    Tcl_Obj* colName;		/* Name of the current column */
    Tcl_Obj* resultRow;		/* Row of the result set under construction */

    Tcl_Obj* colObj;		/* Column obtained from the row */
    int status = TCL_ERROR;	/* Status return from this command */
    MYSQL_FIELD* fields;	/* Fields of the result set */
    MYSQL_BIND* resultBindings = rdata->resultBindings;
				/* Descriptions of the results */
    unsigned long* resultLengths = rdata->resultLengths;
				/* String lengths of the results */
    my_bool* resultNulls = rdata->resultNulls;
				/* Indicators that the results are null */
    void* bufPtr;		/* Pointer to a result's buffer */
    unsigned char byte;		/* One byte extracted from a bit field */
    Tcl_WideInt bitVal;		/* Value of a bit field */
    int mysqlStatus;		/* Status return from MySQL */
    int i;
    unsigned int j;

    if (objc != 3) {
	Tcl_WrongNumArgs(interp, 2, objv, "varName");
	return TCL_ERROR;
    }


    /* Get the column names in the result set. */

    Tcl_ListObjLength(NULL, sdata->columnNames, &nColumns);
    if (nColumns == 0) {
	Tcl_SetObjResult(interp, literals[LIT_0]);
	return TCL_OK;
    }

    resultRow = Tcl_NewObj();
    Tcl_IncrRefCount(resultRow);

    /*
     * Try to rebind the result set before doing the next fetch
     */

    fields = mysql_fetch_fields(sdata->metadataPtr);
    if (mysql_stmt_bind_result(rdata->stmtPtr, resultBindings)) {
	goto cleanup;
    }

    /* Fetch the row to determine sizes. */

    mysqlStatus = mysql_stmt_fetch(rdata->stmtPtr);
    if (mysqlStatus != 0 && mysqlStatus != MYSQL_DATA_TRUNCATED) {
	if (mysqlStatus == MYSQL_NO_DATA) {
	    Tcl_SetObjResult(interp, literals[LIT_0]);
	    status = TCL_OK;
	}
	goto cleanup;
    }

    /* Retrieve one column at a time. */

    for (i = 0; i < nColumns; ++i) {
	MYSQL_FIELD* field = MysqlFieldIndex(fields, i);
	colObj = NULL;
	if (!resultNulls[i]) {
	    if (resultLengths[i]
		> MysqlBindGetBufferLength(resultBindings, i)) {
		MysqlBindFreeBuffer(resultBindings, i);
		MysqlBindAllocBuffer(resultBindings, i, resultLengths[i] + 1);
		if (mysql_stmt_fetch_column(rdata->stmtPtr,
					    MysqlBindIndex(resultBindings, i),
					    i, 0)) {
		    goto cleanup;
		}
	    }
	    bufPtr = MysqlBindGetBuffer(resultBindings, i);
	    switch (MysqlBindGetBufferType(resultBindings, i)) {

	    case MYSQL_TYPE_BIT:
		bitVal = 0;
		for (j = 0; j < resultLengths[i]; ++j) {
		    byte = ((unsigned char*) bufPtr)[resultLengths[i]-1-j];
		    bitVal |= (byte << (8*j));
		}
		colObj = Tcl_NewWideIntObj(bitVal);
		break;

	    case MYSQL_TYPE_DOUBLE:
		colObj = Tcl_NewDoubleObj(*(double*) bufPtr);
		break;

	    case MYSQL_TYPE_LONG:
		colObj = Tcl_NewIntObj(*(int*) bufPtr);
		break;

	    case MYSQL_TYPE_LONGLONG:
		colObj = Tcl_NewWideIntObj(*(Tcl_WideInt*) bufPtr);
		break;

	    default:
		if (field->charsetnr == 63) {
		    colObj = Tcl_NewByteArrayObj((unsigned char*) bufPtr,
						 resultLengths[i]);
		} else {
		    colObj = Tcl_NewStringObj((char*) bufPtr,
					      resultLengths[i]);
		}
		break;
	    }
	}

	if (lists) {
	    if (colObj == NULL) {
		colObj = literals[LIT_EMPTY];
	    }
	    Tcl_ListObjAppendElement(NULL, resultRow, colObj);
	} else {
	    if (colObj != NULL) {
		Tcl_ListObjIndex(NULL, sdata->columnNames, i, &colName);
		Tcl_DictObjPut(NULL, resultRow, colName, colObj);
	    }
	}
    }

    /* Save the row in the given variable */

    if (Tcl_SetVar2Ex(interp, Tcl_GetString(objv[2]), NULL,
		      resultRow, TCL_LEAVE_ERR_MSG) == NULL) {
	goto cleanup;
    }

    Tcl_SetObjResult(interp, literals[LIT_1]);
    status = TCL_OK;

 cleanup:
    if (status != TCL_OK) {
	TransferMysqlStmtError(interp, rdata->stmtPtr);
    }
    Tcl_DecrRefCount(resultRow);
    return status;

}

/*
 *-----------------------------------------------------------------------------
 *
 * ResultSetRowcountMethod --
 *
 *	Returns (if known) the number of rows affected by a MySQL statement.
 *
 * Usage:
 *	$resultSet rowcount
 *
 * Results:
 *	Returns a standard Tcl result giving the number of affected rows.
 *
 *-----------------------------------------------------------------------------
 */

static int
ResultSetRowcountMethod(
    ClientData clientData,	/* Not used */
    Tcl_Interp* interp,		/* Tcl interpreter */
    Tcl_ObjectContext context,	/* Object context  */
    int objc, 			/* Parameter count */
    Tcl_Obj *const objv[]	/* Parameter vector */
) {

    Tcl_Object thisObject = Tcl_ObjectContextObject(context);
				/* The current result set object */
    ResultSetData* rdata = (ResultSetData*)
	Tcl_ObjectGetMetadata(thisObject, &resultSetDataType);
				/* Data pertaining to the current result set */

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 2, objv, "");
	return TCL_ERROR;
    }
    Tcl_SetObjResult(interp,
		     Tcl_NewWideIntObj((Tcl_WideInt)(rdata->rowCount)));
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * DeleteResultSetMetadata, DeleteResultSet --
 *
 *	Cleans up when a MySQL result set is no longer required.
 *
 * Side effects:
 *	Frees all resources associated with the result set.
 *
 *-----------------------------------------------------------------------------
 */

static void
DeleteResultSetMetadata(
    ClientData clientData	/* Instance data for the connection */
) {
    DecrResultSetRefCount((ResultSetData*)clientData);
}
static void
DeleteResultSet(
    ResultSetData* rdata	/* Metadata for the result set */
) {
    StatementData* sdata = rdata->sdata;
    int i;
    int nParams;
    int nColumns;
    Tcl_ListObjLength(NULL, sdata->subVars, &nParams);
    Tcl_ListObjLength(NULL, sdata->columnNames, &nColumns);
    for (i = 0; i < nColumns; ++i) {
	MysqlBindFreeBuffer(rdata->resultBindings, i);
    }
    ckfree((char*)(rdata->resultBindings));
    ckfree((char*)(rdata->resultLengths));
    ckfree((char*)(rdata->resultNulls));
    ckfree((char*)(rdata->resultErrors));
    ckfree((char*)(rdata->paramLengths));
    if (rdata->paramBindings != NULL) {
	for (i = 0; i < nParams; ++i) {
	    if (MysqlBindGetBufferType(rdata->paramBindings, i)
		!= MYSQL_TYPE_NULL) {
		MysqlBindFreeBuffer(rdata->paramBindings, i);
	    }
	}
	ckfree((char*)(rdata->paramBindings));
    }
    if (rdata->paramValues != NULL) {
	Tcl_DecrRefCount(rdata->paramValues);
    }
    if (rdata->stmtPtr != NULL) {
	if (rdata->stmtPtr != sdata->stmtPtr) {
	    mysql_stmt_close(rdata->stmtPtr);
	} else {
	    sdata->flags &= ~ STMT_FLAG_BUSY;
	}
    }
    DecrStatementRefCount(rdata->sdata);
    ckfree((char*)rdata);
}

/*
 *-----------------------------------------------------------------------------
 *
 * CloneResultSet --
 *
 *	Attempts to clone a MySQL result set's metadata.
 *
 * Results:
 *	Returns the new metadata
 *
 * At present, we don't attempt to clone result sets - it's not obvious
 * that such an action would ever even make sense.  Instead, we throw an
 * error.
 *
 *-----------------------------------------------------------------------------
 */

static int
CloneResultSet(
    Tcl_Interp* interp,		/* Tcl interpreter for error reporting */
    ClientData metadata,	/* Metadata to be cloned */
    ClientData* newMetaData	/* Where to put the cloned metadata */
) {
    Tcl_SetObjResult(interp,
		     Tcl_NewStringObj("MySQL result sets are not clonable",
				      -1));
    return TCL_ERROR;
}

/*
 *-----------------------------------------------------------------------------
 *
 * Tdbcmysql_Init --
 *
 *	Initializes the TDBC-MYSQL bridge when this library is loaded.
 *
 * Side effects:
 *	Creates the ::tdbc::mysql namespace and the commands that reside in it.
 *	Initializes the MYSQL environment.
 *
 *-----------------------------------------------------------------------------
 */

extern DLLEXPORT int
Tdbcmysql_Init(
    Tcl_Interp* interp		/* Tcl interpreter */
) {
    PerInterpData* pidata;	/* Per-interpreter data for this package */
    Tcl_Obj* nameObj;		/* Name of a class or method being looked up */
    Tcl_Object curClassObject;  /* Tcl_Object representing the current class */
    Tcl_Class curClass;		/* Tcl_Class representing the current class */
    int i;

    /* Require all package dependencies */

    if (Tcl_InitStubs(interp, TCL_VERSION, 0) == NULL) {
	return TCL_ERROR;
    }
    if (TclOOInitializeStubs(interp, "1.0") == NULL) {
	return TCL_ERROR;
    }
    if (Tdbc_InitStubs(interp) == NULL) {
	return TCL_ERROR;
    }

    /* Provide the current package */

    if (Tcl_PkgProvide(interp, "tdbc::mysql", PACKAGE_VERSION) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Create per-interpreter data for the package
     */

    pidata = (PerInterpData*) ckalloc(sizeof(PerInterpData));
    pidata->refCount = 1;
    for (i = 0; i < LIT__END; ++i) {
	pidata->literals[i] = Tcl_NewStringObj(LiteralValues[i], -1);
	Tcl_IncrRefCount(pidata->literals[i]);
    }
    Tcl_InitHashTable(&(pidata->typeNumHash), TCL_ONE_WORD_KEYS);
    for (i = 0; dataTypes[i].name != NULL; ++i) {
	int new;
	Tcl_HashEntry* entry =
	    Tcl_CreateHashEntry(&(pidata->typeNumHash),
				(const char*) (int) (dataTypes[i].num),
				&new);
	Tcl_Obj* nameObj = Tcl_NewStringObj(dataTypes[i].name, -1);
	Tcl_IncrRefCount(nameObj);
	Tcl_SetHashValue(entry, (ClientData) nameObj);
    }

    /*
     * Find the connection class, and attach an 'init' method to it.
     */

    nameObj = Tcl_NewStringObj("::tdbc::mysql::connection", -1);
    Tcl_IncrRefCount(nameObj);
    if ((curClassObject = Tcl_GetObjectFromObj(interp, nameObj)) == NULL) {
	Tcl_DecrRefCount(nameObj);
	return TCL_ERROR;
    }
    Tcl_DecrRefCount(nameObj);
    curClass = Tcl_GetObjectAsClass(curClassObject);

    /* Attach the constructor to the 'connection' class */

    Tcl_ClassSetConstructor(interp, curClass,
			    Tcl_NewMethod(interp, curClass, NULL, 1,
					  &ConnectionConstructorType,
					  (ClientData) pidata));

    /* Attach the methods to the 'connection' class */

    for (i = 0; ConnectionMethods[i] != NULL; ++i) {
	nameObj = Tcl_NewStringObj(ConnectionMethods[i]->name, -1);
	Tcl_IncrRefCount(nameObj);
	Tcl_NewMethod(interp, curClass, nameObj, 1, ConnectionMethods[i],
			   (ClientData) NULL);
	Tcl_DecrRefCount(nameObj);
    }

    /* Look up the 'statement' class */

    nameObj = Tcl_NewStringObj("::tdbc::mysql::statement", -1);
    Tcl_IncrRefCount(nameObj);
    if ((curClassObject = Tcl_GetObjectFromObj(interp, nameObj)) == NULL) {
	Tcl_DecrRefCount(nameObj);
	return TCL_ERROR;
    }
    Tcl_DecrRefCount(nameObj);
    curClass = Tcl_GetObjectAsClass(curClassObject);

    /* Attach the constructor to the 'statement' class */

    Tcl_ClassSetConstructor(interp, curClass,
			    Tcl_NewMethod(interp, curClass, NULL, 1,
					  &StatementConstructorType,
					  (ClientData) NULL));

    /* Attach the methods to the 'statement' class */

    for (i = 0; StatementMethods[i] != NULL; ++i) {
	nameObj = Tcl_NewStringObj(StatementMethods[i]->name, -1);
	Tcl_IncrRefCount(nameObj);
	Tcl_NewMethod(interp, curClass, nameObj, 1, StatementMethods[i],
			   (ClientData) NULL);
	Tcl_DecrRefCount(nameObj);
    }

    /* Look up the 'resultSet' class */

    nameObj = Tcl_NewStringObj("::tdbc::mysql::resultset", -1);
    Tcl_IncrRefCount(nameObj);
    if ((curClassObject = Tcl_GetObjectFromObj(interp, nameObj)) == NULL) {
	Tcl_DecrRefCount(nameObj);
	return TCL_ERROR;
    }
    Tcl_DecrRefCount(nameObj);
    curClass = Tcl_GetObjectAsClass(curClassObject);

    /* Attach the constructor to the 'resultSet' class */

    Tcl_ClassSetConstructor(interp, curClass,
			    Tcl_NewMethod(interp, curClass, NULL, 1,
					  &ResultSetConstructorType,
					  (ClientData) NULL));

    /* Attach the methods to the 'resultSet' class */

    for (i = 0; ResultSetMethods[i] != NULL; ++i) {
	nameObj = Tcl_NewStringObj(ResultSetMethods[i]->name, -1);
	Tcl_IncrRefCount(nameObj);
	Tcl_NewMethod(interp, curClass, nameObj, 1, ResultSetMethods[i],
			   (ClientData) NULL);
	Tcl_DecrRefCount(nameObj);
    }
    nameObj = Tcl_NewStringObj("nextlist", -1);
    Tcl_IncrRefCount(nameObj);
    Tcl_NewMethod(interp, curClass, nameObj, 1, &ResultSetNextrowMethodType,
		  (ClientData) 1);
    Tcl_DecrRefCount(nameObj);
    nameObj = Tcl_NewStringObj("nextdict", -1);
    Tcl_IncrRefCount(nameObj);
    Tcl_NewMethod(interp, curClass, nameObj, 1, &ResultSetNextrowMethodType,
		  (ClientData) 0);
    Tcl_DecrRefCount(nameObj);

    /*
     * Initialize the MySQL library if this is the first interp using it
     */

    Tcl_MutexLock(&mysqlMutex);
    if (mysqlRefCount == 0) {
	if ((mysqlLoadHandle = MysqlInitStubs(interp)) == NULL) {
	    Tcl_MutexUnlock(&mysqlMutex);
	    return TCL_ERROR;
	}
	mysql_library_init(0, NULL, NULL);
	mysqlClientVersion = mysql_get_client_version();
    }
    ++mysqlRefCount;
    Tcl_MutexUnlock(&mysqlMutex);

    /*
     * TODO: mysql_thread_init, and keep a TSD reference count of users.
     */

    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * DeletePerInterpData --
 *
 *	Delete per-interpreter data when the MYSQL package is finalized
 *
 * Side effects:
 *	Releases the (presumably last) reference on the environment handle,
 *	cleans up the literal pool, and deletes the per-interp data structure.
 *
 *-----------------------------------------------------------------------------
 */

static void
DeletePerInterpData(
    PerInterpData* pidata	/* Data structure to clean up */
) {
    int i;

    Tcl_HashSearch search;
    Tcl_HashEntry *entry;
    for (entry = Tcl_FirstHashEntry(&(pidata->typeNumHash), &search);
	 entry != NULL;
	 entry = Tcl_NextHashEntry(&search)) {
	Tcl_Obj* nameObj = (Tcl_Obj*) Tcl_GetHashValue(entry);
	Tcl_DecrRefCount(nameObj);
    }
    Tcl_DeleteHashTable(&(pidata->typeNumHash));

    for (i = 0; i < LIT__END; ++i) {
	Tcl_DecrRefCount(pidata->literals[i]);
    }
    ckfree((char *) pidata);

    /*
     * TODO: decrease thread refcount and mysql_thread_end if need be
     */

    Tcl_MutexLock(&mysqlMutex);
    if (--mysqlRefCount == 0) {
	mysql_library_end();
	Tcl_FSUnloadFile(NULL, mysqlLoadHandle);
    }
    Tcl_MutexUnlock(&mysqlMutex);
}