This file is indexed.

/usr/lib/python2.7/dist-packages/kinterbasdb/__init__.py is in python-kinterbasdb 3.3.0-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# KInterbasDB Python Package - Python Wrapper for Core
#
# Version 3.3
#
# The following contributors hold Copyright (C) over their respective
# portions of code (see license.txt for details):
#
# [Original Author (maintained through version 2.0-0.3.1):]
#   1998-2001 [alex]  Alexander Kuznetsov   <alexan@users.sourceforge.net>
# [Maintainers (after version 2.0-0.3.1):]
#   2001-2002 [maz]   Marek Isalski         <kinterbasdb@maz.nu>
#   2002-2006 [dsr]   David Rushby          <woodsplitter@rocketmail.com>
# [Contributors:]
#   2001      [eac]   Evgeny A. Cherkashin  <eugeneai@icc.ru>
#   2001-2002 [janez] Janez Jere            <janez.jere@void.si>

#   The doc strings throughout this module explain what API *guarantees*
# kinterbasdb makes.
#   Notably, the fact that users can only rely on the return values of certain
# functions/methods to be sequences or mappings, not instances of a specific
# class.  This policy is still compliant with the DB API spec, and is more
# future-proof than implying that all of the classes defined herein can be
# relied upon not to change.  Module members whose names begin with an
# underscore cannot be expected to have stable interfaces.

__version__ = (3, 3, 0, 'pre-alpha', 0)
__timestamp__ = '2012.01.28.15.07.11.UTC'

import os, struct, sys

_FS_ENCODING = sys.getfilesystemencoding()

if sys.platform.lower().startswith('win'):
    import os.path

    # Better out-of-box support for embedded DB engine on Windows:  if the
    # client library is detected in the same directory as kinterbasdb, or in
    # the 'embedded' subdirectory of kinterbasdb's directory, or in the same
    # directory as the Python executable, give that library instance precedence
    # over the location listed in the registry.
    #
    # 2007.03.19: Overhauled to support non-ASCII paths properly, in response
    # to:
    #   http://sourceforge.net/forum/forum.php?thread_id=1695175&forum_id=30917
    def _findAndLoadFBDLLDir():
        clientLibDir = None
        curWorkingDir = os.getcwdu()
        kinterbasdbDir = os.path.dirname(os.path.abspath(__file__)).decode(
            _FS_ENCODING
          )
        pythonDir = os.path.dirname(sys.executable).decode(_FS_ENCODING)
        for clientLibName in (
            u'firebird.dll', # Vulcan
            u'fbclient.dll', # FB 1.5, 2.x
          ):
            for location in (
                os.path.join(curWorkingDir, clientLibName),
                os.path.join(kinterbasdbDir, clientLibName),
                os.path.join(os.path.join(kinterbasdbDir, u'embedded'),
                    clientLibName
                  ),
                os.path.join(pythonDir, clientLibName),
              ):
                if os.path.isfile(location):
                    clientLibDir = os.path.dirname(location)
                    break

            if clientLibDir:
                break

        if clientLibDir:
            origOSPath = os.environ['PATH'].decode(_FS_ENCODING)
            os.environ['PATH'] = (
                origOSPath +  os.pathsep + clientLibDir
              ).encode(_FS_ENCODING)

            # At least with FB 1.5.2, the FIREBIRD environment variable must
            # also be set in order for all features to work properly.
            os.environ['FIREBIRD'] = clientLibDir.encode(_FS_ENCODING)
        else:
            # FB 1.5 RC7 and later, when installed via the packaged installer
            # or the "instreg.exe" command-line tool, record their installation
            # dir in the registry.  If no client library was detected earlier,
            # we'll add the "bin" subdirectory of the directory from the
            # registry to the *end* of the PATH, so it'll be used as a last
            # resort.
            import _winreg

            reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
            try:
                try:
                    dbInstPathsKey = _winreg.OpenKey(reg,
                        u'SOFTWARE\\Firebird Project\\Firebird Server'
                        u'\\Instances'
                      )
                    try:
                        instPath = _winreg.QueryValueEx(
                            dbInstPathsKey, u'DefaultInstance'
                          )[0]
                    finally:
                        dbInstPathsKey.Close()
                except WindowsError:
                    # Versions of IB/FB prior to FB 1.5 RC7 don't have this reg
                    # entry, but they install the client library into a system
                    # library directory, so there's no problem.
                    pass
                else:
                    origOSPath = os.environ['PATH'].decode(_FS_ENCODING)
                    fbBinPath = os.pathsep + os.path.join(instPath, u'bin')
                    os.environ['PATH'] = (origOSPath + fbBinPath).encode(
                        _FS_ENCODING
                      )
            finally:
                reg.Close()

    _findAndLoadFBDLLDir()

# The underlying C module:
import _kinterbasdb as _k

# Import database API constants into the namespace of this module as Python
# objects:
_k.init_kidb_basic_header_constants(globals())

# Export utility members:
FB_API_VER = _k.FB_API_VER

portable_int = _k.portable_int
raw_timestamp_to_tuple = _k.raw_timestamp_to_tuple

DEFAULT_CONCURRENCY_LEVEL = _k.DEFAULT_CONCURRENCY_LEVEL
get_concurrency_level = _k.concurrency_level_get

# Initialize the k_exceptions so that other Python modules in kinterbasdb can
# have access to kinterbasdb's exceptions without a circular import.
import k_exceptions

Warning               = k_exceptions.Warning            = _k.Warning
Error                 = k_exceptions.Error              = _k.Error
InterfaceError        = k_exceptions.InterfaceError     = _k.InterfaceError
DatabaseError         = k_exceptions.DatabaseError      = _k.DatabaseError
DataError             = k_exceptions.DataError          = _k.DataError
OperationalError      = k_exceptions.OperationalError   = _k.OperationalError
IntegrityError        = k_exceptions.IntegrityError     = _k.IntegrityError
InternalError         = k_exceptions.InternalError      = _k.InternalError

ProgrammingError      = k_exceptions.ProgrammingError   = _k.ProgrammingError
TransactionConflict \
  = k_exceptions.TransactionConflict = _k.TransactionConflict

NotSupportedError     = k_exceptions.NotSupportedError  = _k.NotSupportedError

_EVENT_HANDLING_SUPPORTED = hasattr(_k, 'ConduitWasClosed')
if _EVENT_HANDLING_SUPPORTED:
    ConduitWasClosed  = k_exceptions.ConduitWasClosed   = _k.ConduitWasClosed

_CONNECTION_TIMEOUT_SUPPORTED = hasattr(_k, 'ConnectionTimedOut')
if _CONNECTION_TIMEOUT_SUPPORTED:
    ConnectionTimedOut = k_exceptions.ConnectionTimedOut = \
      _k.ConnectionTimedOut
    import _connection_timeout

_ALL_EXCEPTION_CLASSES = [
    Warning,
    Error,
    InterfaceError,
    DatabaseError,
    DataError,
    OperationalError,
    IntegrityError,
    InternalError,
    ProgrammingError,
    NotSupportedError,
  ]

if _EVENT_HANDLING_SUPPORTED:
    _ALL_EXCEPTION_CLASSES.append(ConduitWasClosed)

if _CONNECTION_TIMEOUT_SUPPORTED:
    _ALL_EXCEPTION_CLASSES.append(ConnectionTimedOut)

_ALL_EXCEPTION_CLASSES = tuple(_ALL_EXCEPTION_CLASSES)

##########################################
##     PUBLIC CONSTANTS: BEGIN          ##
##########################################

# Note:  Numerous database API constants were imported into the global
# namespace of this module by an earlier call to
# _k.init_kidb_basic_header_constants.  See _kinterbasdb_constants.c for more
# info.

apilevel = '2.0'
threadsafety = 1
paramstyle = 'qmark'

# Named positional constants to be used as indices into the description
# attribute of a cursor (these positions are defined by the DB API spec).
# For example:
#   nameOfFirstField = cursor.description[0][kinterbasdb.DESCRIPTION_NAME]

DESCRIPTION_NAME            = 0
DESCRIPTION_TYPE_CODE       = 1
DESCRIPTION_DISPLAY_SIZE    = 2
DESCRIPTION_INTERNAL_SIZE   = 3
DESCRIPTION_PRECISION       = 4
DESCRIPTION_SCALE           = 5
DESCRIPTION_NULL_OK         = 6

# Default transaction parameter buffer:
default_tpb = (
      # isc_tpb_version3 is a *purely* infrastructural value.  kinterbasdb will
      # gracefully handle user-specified TPBs that don't start with
      # isc_tpb_version3 (as well as those that do start with it).
      isc_tpb_version3

    + isc_tpb_write                                 # Access mode
    + isc_tpb_read_committed + isc_tpb_rec_version  # Isolation level
    + isc_tpb_wait                                  # Lock resolution strategy
#    + isc_tpb_shared                                # Table reservation
                                                    # access method
  )

from _request_buffer_builder import RequestBufferBuilder as _RequestBufferBuilder
_request_buffer_builder.portable_int = portable_int

##########################################
##     PUBLIC CONSTANTS: END            ##
##########################################


###################################################
## DYNAMIC TYPE TRANSLATION CONFIGURATION: BEGIN ##
###################################################
# Added deferred loading of dynamic type converters to facilitate the
# elimination of all dependency on the mx package.  The implementation is quite
# ugly due to backward compatibility constraints.

BASELINE_TYPE_TRANSLATION_FACILITIES = (
    # Date and time translator names:
    'date_conv_in', 'date_conv_out',
    'time_conv_in', 'time_conv_out',
    'timestamp_conv_in', 'timestamp_conv_out',

    # Fixed point translator names:
    'fixed_conv_in_imprecise', 'fixed_conv_in_precise',
    'fixed_conv_out_imprecise', 'fixed_conv_out_precise',

    # Optional unicode converters:
    'OPT:unicode_conv_in', 'OPT:unicode_conv_out',

    # DB API 2.0 standard date and time type constructors:
    'Date', 'Time', 'Timestamp',
    'DateFromTicks', 'TimeFromTicks', 'TimestampFromTicks',
  )

# The next three will be modified by the init function as appropriate:
_MINIMAL_TYPE_TRANS_TYPES = ('DATE', 'TIME', 'TIMESTAMP', 'FIXED',)
_NORMAL_TYPE_TRANS_IN = None
_NORMAL_TYPE_TRANS_OUT = None


initialized = False
_guessTextualBlobEncodingWhenUsingFB20AndEarlier = False
def init(type_conv=200, concurrency_level=_k.DEFAULT_CONCURRENCY_LEVEL):
    global initialized, _MINIMAL_TYPE_TRANS_TYPES, \
           _NORMAL_TYPE_TRANS_IN, _NORMAL_TYPE_TRANS_OUT, \
           _guessTextualBlobEncodingWhenUsingFB20AndEarlier

    if initialized:
        raise ProgrammingError('Cannot initialize module more than once.')

    if _k.DEFAULT_CONCURRENCY_LEVEL == 0:
        if concurrency_level != 0:
            raise ProgrammingError('Support for concurrency was disabled at'
                ' compile time, so only Level 0 is available.'
              )
        # Since only Level 0 is available and it's already active, there's no
        # need to do anything.
    else:
        if concurrency_level not in (1,2):
            raise ProgrammingError('Only Levels 1 and 2 are accessible at'
                ' runtime; Level 0 can only be activated at compile time.'
              )
        _k.concurrency_level_set(concurrency_level)

    _k.provide_refs_to_python_entities(
        _RowMapping,
        _make_output_translator_return_type_dict_from_trans_dict,
        _look_up_array_descriptor,
        _look_up_array_subtype,
        _Cursor_execute_exception_type_filter,
        _validateTPB,
        _trans_info,
      )

    globalz = globals()
    if not isinstance(type_conv, int):
        typeConvModule = type_conv
    else:
        typeConvOptions = {
              0: 'typeconv_naked',
              1: 'typeconv_backcompat', # the default
            100: 'typeconv_23plus',
            199: 'typeconv_23plus_lowmem',
            200: 'typeconv_24plus',     # considered "ideal" for KIDB 3.2

            # Code 300 is considered "ideal" for KIDB 3.3 and FB 2.1+.  It
            # causes textual blobs to be handled the same way as other textual
            # types, so unicode encoding/decoding is performed automagically.
            # When converting in the input direction, this doesn't work with
            # any version of FB prior to FB 2.1, because the API doesn't make
            # the blob's character set ID available.
            # Note that we use the same typeConvModule for code 300 as for
            # code 200; the textual-blob-related changes are implemented by
            # adding 'BLOB' entries to _NORMAL_TYPE_TRANS_*.
            300: 'typeconv_24plus',
          }
        chosenTypeConvModuleName = typeConvOptions[type_conv]
        typeConvModule = __import__('kinterbasdb.' + chosenTypeConvModuleName,
            globalz, locals(), (chosenTypeConvModuleName,)
          )

        extraMinTypeTransEntries = [] # 2007.02.10

        if type_conv > 1:
            extraMinTypeTransEntries.append('TEXT_UNICODE')
        if type_conv >= 300:
            _guessTextualBlobEncodingWhenUsingFB20AndEarlier = True
            extraMinTypeTransEntries.append('BLOB')

        if extraMinTypeTransEntries:
            _MINIMAL_TYPE_TRANS_TYPES = _MINIMAL_TYPE_TRANS_TYPES \
              + tuple(extraMinTypeTransEntries)


    for name in BASELINE_TYPE_TRANSLATION_FACILITIES:
        if not name.startswith('OPT:'):
            typeConvModuleMember = getattr(typeConvModule, name)
        else:
            # Members whose entries in BASELINE_TYPE_TRANSLATION_FACILITIES
            # begin with 'OPT:' are not required.
            name = name[4:]
            try:
                typeConvModuleMember = getattr(typeConvModule, name)
            except AttributeError:
                continue

        globalz[name] = typeConvModuleMember

    # Modify the initial, empty version of the DB API type singleton DATETIME,
    # transforming it into a fully functional version.
    # The fact that the object is *modifed* rather than replaced is crucial to
    # the preservation of compatibility with the 'from kinterbasdb import *'
    # form of importation.
    DATETIME.values = (
        # Date, Time, and Timestamp refer to functions just loaded from the
        # typeConvModule in the loop above.
        type(Date(2003,12,31)),
        type(Time(23,59,59)),
        type(Timestamp(2003,12,31,23,59,59))
      )

    _NORMAL_TYPE_TRANS_IN = {
        'DATE': date_conv_in,
        'TIME': time_conv_in,
        'TIMESTAMP': timestamp_conv_in,
        'FIXED': fixed_conv_in_imprecise,
      }
    _NORMAL_TYPE_TRANS_OUT = {
        'DATE': date_conv_out,
        'TIME': time_conv_out,
        'TIMESTAMP': timestamp_conv_out,
        'FIXED': fixed_conv_out_imprecise,
      }
    if type_conv > 1:
        _NORMAL_TYPE_TRANS_IN['TEXT_UNICODE'] = unicode_conv_in
        _NORMAL_TYPE_TRANS_OUT['TEXT_UNICODE'] = unicode_conv_out
    if type_conv >= 300: # 2007.02.10
        textBlobsAsTextConfig = {
            'mode': 'materialize',
            'treat_subtype_text_as_text': True
          }
        _NORMAL_TYPE_TRANS_IN['BLOB'] = textBlobsAsTextConfig
        _NORMAL_TYPE_TRANS_OUT['BLOB'] = textBlobsAsTextConfig

    initialized = True

def _ensureInitialized():
    if not initialized:
        init()

# The following constructors will be replaced when kinterbasdb.init is called,
# whether implicitly or explicitly.  If one of the constructors is called
# before kinterbasdb.init, it will trigger its own replacement by calling
# _ensureInitialized.
def Date(year, month, day):
    _ensureInitialized()
    return Date(year, month, day)

def Time(hour, minute, second):
    _ensureInitialized()
    return Time(hour, minute, second)

def Timestamp(year, month, day, hour, minute, second):
    _ensureInitialized()
    return Timestamp(year, month, day, hour, minute, second)

def DateFromTicks(ticks):
    _ensureInitialized()
    return DateFromTicks(ticks)

def TimeFromTicks(ticks):
    _ensureInitialized()
    return TimeFromTicks(ticks)

def TimestampFromTicks(ticks):
    _ensureInitialized()
    return TimestampFromTicks(ticks)


###################################################
## DYNAMIC TYPE TRANSLATION CONFIGURATION: END   ##
###################################################


############################################
## PUBLIC DB-API TYPE CONSTRUCTORS: BEGIN ##
############################################

# All date/time constructors are loaded dynamically by the init function.

# Changed from buffer to str in 3.1, with the possible addition of a lazy BLOB
# reader at some point in the future:
Binary = str


# DBAPITypeObject implementation is the DB API's suggested implementation.
class DBAPITypeObject: # Purposely remains a "classic class".
    def __init__(self, *values):
        self.values = values
    def __cmp__(self, other):
        if other in self.values:
            return 0
        if other < self.values:
            return 1
        else:
            return -1


STRING = DBAPITypeObject(str, unicode)

BINARY = DBAPITypeObject(str, buffer)

NUMBER = DBAPITypeObject(int, long, float)

# DATETIME is loaded in a deferred manner (in the init function); this initial
# version remains empty only temporarily.
DATETIME = DBAPITypeObject()

ROWID = DBAPITypeObject()

############################################
## PUBLIC DB-API TYPE CONSTRUCTORS: END   ##
############################################


##########################################
##     PUBLIC FUNCTIONS: BEGIN          ##
##########################################

def connect(*args, **keywords_args):
    """
      Minimal arguments: keyword args $dsn, $user, and $password.
      Establishes a kinterbasdb.Connection to a database.  See the docstring
    of kinterbasdb.Connection for details.
    """
    return Connection(*args, **keywords_args)


def create_database(*args):
    """
      Creates a new database with the supplied "CREATE DATABASE" statement.
      Returns an active kinterbasdb.Connection to the newly created database.

    Parameters:
    $sql: string containing the CREATE DATABASE statement.  Note that you may
       need to specify a username and password as part of this statement (see
       the Firebird SQL Reference for syntax).
    $dialect: (optional) the SQL dialect under which to execute the statement
    """
    _ensureInitialized()

    # For a more general-purpose immediate execution facility (the non-"CREATE
    # DATABASE" variant of isc_dsql_execute_immediate, for those who care), see
    # Connection.execute_immediate.

    # 2007.04.05: If the path specified in this CREATE DATABASE statement needs
    # to be Unicode, we should accept that.
    if len(args) >= 1 and isinstance(args[0], unicode):
        args = (args[0].encode(_FS_ENCODING),) + args[1:]

    C_con = _k.create_database(*args)
    return Connection(_CConnection=C_con)


def raw_byte_to_int(raw_byte):
    """
      Convert the byte in the single-character Python string $raw_byte into a
    Python integer.  This function is essentially equivalent to the built-in
    function ord, but is different in intent (see the database_info method).
    """
    _ensureInitialized()

    if len(raw_byte) != 1:
        raise ValueError('raw_byte must be exactly one byte, not %d bytes.'
            % len(raw_byte)
          )
    return struct.unpack('b', raw_byte)[0]


##########################################
##     PUBLIC FUNCTIONS: END            ##
##########################################


##########################################
##     PUBLIC CLASSES: BEGIN            ##
##########################################

# BlobReader, PreparedStatement and Cursor can't be instantiated from Python,
# but are exposed here to support isinstance(o, kinterbasdb.Class) and the
# like.
Transaction = _k.Transaction # 2007.01
BlobReader = _k.BlobReader
Cursor = _k.Cursor
PreparedStatement = _k.PreparedStatement

if _EVENT_HANDLING_SUPPORTED:
    EventConduit = _k.EventConduit

class Connection(object):
    """
      Represents a connection between the database client (the Python process)
    and the database server.

      The basic functionality of this class is documented by the Python DB API
    Specification 2.0, while the large amount of additional functionality is
    documented by the KInterbasDB Usage Guide (docs/usage.html).
    """

    def __init__(self, *args, **keywords_args):
        # self._C_con is the instance of ConnectionType that represents this
        # connection in the underlying C module _k.

        _ensureInitialized()

        # Optional DB API Extension: Make the module's exception classes
        # available as connection attributes to ease cross-module portability:
        for exc_class in _ALL_EXCEPTION_CLASSES:
            setattr(self, exc_class.__name__, exc_class)

        # Inherit the module-level default TPB.
        self._default_tpb = default_tpb

        # Allow other code WITHIN THIS MODULE to obtain an instance of
        # ConnectionType some other way and provide it to us instead of us
        # creating one via Connection_connect.  (The create_database function
        # uses this facility, for example.)
        if '_CConnection' in keywords_args:
            C_con = self._C_con = keywords_args['_CConnection']
            assert C_con is not None
            # Since we were given a pre-existing CConnection instance rather
            # than creating it ourselves, we need to explicitly give it a
            # reference to its Python companion (self), and allow it to
            # establish a main_transaction:
            _k.Connection_python_wrapper_obj_set(C_con, self)

            # Nullify the private properties that we don't have in this case:
            self._charset = None
            self._C_con_params = None
        else:
            n_nonkeyword = len(args)
            n_keyword = len(keywords_args)

            if n_nonkeyword == 0 and n_keyword == 0:
                raise ProgrammingError(
                    'connect() requires at least 3 keyword arguments.'
                  )
            elif n_keyword > 0 and n_nonkeyword == 0:
                source_dict = keywords_args # The typical case.
            else:
                # This case is for backward compatibility ONLY:
                import warnings # Lazy import.
                warnings.warn('The non-keyword-argument form of the connect()'
                    ' function is deprecated.  Use'
                    ' connect(dsn=..., user=..., password=...) rather than'
                    ' connect(..., ..., ...)',
                    DeprecationWarning
                  )
                if n_keyword > 0:
                    raise ProgrammingError('Do not specify both non-keyword'
                        ' args and keyword args (keyword-only is preferred).'
                      )
                elif n_nonkeyword != 3:
                    raise ProgrammingError('If using non-keyword args, must'
                        ' provide exactly 3: dsn, user, password.'
                      )
                else:
                    # Transform the argument tuple into an argument dict.
                    source_dict = {'dsn': args[0], 'user': args[1],
                        'password': args[2]
                      }

            timeout = keywords_args.pop('timeout', None)

            if timeout is not None:
                if not _CONNECTION_TIMEOUT_SUPPORTED:
                    raise ProgrammingError("The connection timeout feature is"
                        " disabled in this build."
                      )

                _connection_timeout.startTimeoutThreadIfNecessary(
                    _k.ConnectionTimeoutThread_main, _k.CTM_halt
                  )

            # Pre-render the requisite buffers (plus the dialect), then send
            # them down to the C level.  _k.Connection_connect() will give us a
            # C-level connection structure (self._C_con, of type
            # ConnectionType) in return.  self will then serve as a proxy for
            # self._C_con.
            #
            # Notice that once rendered by _build_connect_structures, the
            # connection parameters are retained in self._C_con_params in case
            # kinterbasdb's internals need to clone this connection.
            b = _DPBBuilder()
            b.buildFromParamDict(source_dict)
            self._charset = b.charset
            self._C_con_params = (b.dsn, b.dpb, b.dialect)
            self._C_con = _k.Connection_connect(self,
                b.dsn, b.dpb, b.dialect, timeout
              )

        self._normalize_type_trans()
        # 2003.03.30: Moved precision_mode up to the Python level (it's
        # deprecated).
        self._precision_mode = 0


    def __del__(self):
        # This method should not call the Python implementation of close().
        self._close_physical_connection(raiseExceptionOnError=False)


    def drop_database(self):
        """
          Drops the database to which this connection is attached.

          Unlike plain file deletion, this method behaves responsibly, in that
        it removes shadow files and other ancillary files for this database.
        """
        self._ensure_group_membership(False, "Cannot drop database via"
            " connection that is part of a ConnectionGroup."
          )
        _k.Connection_drop_database(self._C_con)


    def begin(self, tpb=None):
        """
          Starts a transaction explicitly.  This is never *required*; a
        transaction will be started implicitly if necessary.

        Parameters:
        $tpb: Optional transaction parameter buffer (TPB) populated with
            kinterbasdb.isc_tpb_* constants.  See the Interbase API guide for
            these constants' meanings.
        """
        return self._main_trans.begin(tpb=tpb)


    def prepare(self):
        """
          Manually triggers the first phase of a two-phase commit (2PC).  Use
        of this method is optional; if preparation is not triggered manually,
        it will be performed implicitly by commit() in a 2PC.
          See also the method ConnectionGroup.prepare.
        """
        self._main_trans.prepare()

    def commit(self, retaining=False):
        """
          Commits (permanently applies the actions that have taken place as
        part of) the active transaction.

        Parameters:
          $retaining (optional boolean that defaults to False):
              If True, the transaction is immediately cloned after it has been
            committed.  This retains system resources associated with the
            transaction and leaves undisturbed the state of any cursors open on
            this connection.  In effect, retaining commit keeps the transaction
            "open" across commits.
              See IB 6 API Guide pages 75 and 291 for more info.
        """
        return self._main_trans.commit(retaining=retaining)


    def savepoint(self, name):
        """
          Establishes a SAVEPOINT named $name.
          To rollback to this SAVEPOINT, use rollback(savepoint=name).

          Example:
            con.savepoint('BEGINNING_OF_SOME_SUBTASK')
            ...
            con.rollback(savepoint='BEGINNING_OF_SOME_SUBTASK')
        """
        return self._main_trans.savepoint(name)


    def rollback(self, retaining=False, savepoint=None):
        """
          Rolls back (cancels the actions that have taken place as part of) the
        active transaction.

        Parameters:
          $retaining (optional boolean that defaults to False):
              If True, the transaction is immediately cloned after it has been
            rolled back.  This retains system resources associated with the
            transaction and leaves undisturbed the state of any cursors open on
            this connection.  In effect, retaining rollback keeps the
            transaction "open" across rollbacks.
              See IB 6 API Guide pages 75 and 373 for more info.
          $savepoint (string name of the SAVEPOINT):
              If a savepoint name is supplied, only rolls back as far as that
            savepoint, rather than rolling back the entire transaction.
        """
        return self._main_trans.rollback(
            retaining=retaining, savepoint=savepoint
          )


    def execute_immediate(self, sql):
        """
          Executes a statement without caching its prepared form.  The
        statement must NOT be of a type that returns a result set.

          In most cases (especially cases in which the same statement--perhaps
        a parameterized statement--is executed repeatedly), it is better to
        create a cursor using the connection's cursor() method, then execute
        the statement using one of the cursor's execute methods.
        """
        if isinstance(sql, unicode): # 2007.04.05
            if self._charset:
                from kinterbasdb import typeconv_text_unicode as ttu
                pyCS = ttu.DB_CHAR_SET_NAME_TO_PYTHON_ENCODING_MAP[
                    self._charset
                  ]
            else:
                pyCS = 'ascii'
            sql = sql.encode(pyCS)

        return self._main_trans._execute_immediate(sql)


    def database_info(self, request, result_type):
        """
          Wraps the Interbase C API function isc_database_info.

          For documentation, see the IB 6 API Guide section entitled
        "Requesting information about an attachment" (p. 51).

          Note that this method is a VERY THIN wrapper around the IB C API
        function isc_database_info.  This method does NOT attempt to interpret
        its results except with regard to whether they are a string or an
        integer.

          For example, requesting isc_info_user_names will return a string
        containing a raw succession of length-name pairs.  A thicker wrapper
        might interpret those raw results and return a Python tuple, but it
        would need to handle a multitude of special cases in order to cover
        all possible isc_info_* items.

          Note:  Some of the information available through this method would be
        more easily retrieved with the Services API (see submodule
        kinterbasdb.services).

        Parameters:
        $result_type must be either:
           's' if you expect a string result, or
           'i' if you expect an integer result
        """
        # Note:  Server-side implementation for most of isc_database_info is in
        # jrd/inf.cpp.
        res = _k.Connection_database_info(self._C_con, request, result_type)

        # 2004.12.12:
        # The result buffers for a few request codes don't follow the generic
        # conventions, so we need to return their full contents rather than
        # omitting the initial infrastructural bytes.
        if (    result_type == 's'
            and request not in _DATABASE_INFO__KNOWN_LOW_LEVEL_EXCEPTIONS
          ):
            res = res[3:]

        return res


    def db_info(self, request):
        # Contributed by Pavel Cisar; incorporated 2004.09.10; heavily modified
        # 2004.12.12.
        """
          Higher-level convenience wrapper around the database_info method that
        parses the output of database_info into Python-friendly objects instead
        of returning raw binary buffers in the case of complex result types.
        If an unrecognized code is requested, ValueError is raised.

        Parameters:
        $request must be either:
          - A single kinterbasdb.isc_info_* info request code.
            In this case, a single result is returned.
          - A sequence of such codes.
            In this case, a mapping of (info request code -> result) is
            returned.
        """
        # Notes:
        #
        # - IB 6 API Guide page 391:  "In InterBase, integer values...
        #   are returned in result buffers in a generic format where
        #   the least significant byte is first, and the most
        #   significant byte last."

        # We process request as a sequence of info codes, even if only one code
        # was supplied by the caller.
        requestIsSingleton = isinstance(request, int)
        if requestIsSingleton:
            request = (request,)

        results = {}
        for infoCode in request:
            if infoCode == isc_info_base_level:
                # (IB 6 API Guide page 52)
                buf = self.database_info(infoCode, 's')
                # Ignore the first byte.
                baseLevel = struct.unpack('B', buf[1])[0]
                results[infoCode] = baseLevel
            elif infoCode == isc_info_db_id:
                # (IB 6 API Guide page 52)
                buf = self.database_info(infoCode, 's')
                pos = 0

                conLocalityCode = struct.unpack('B', buf[pos])[0]
                pos += 1

                dbFilenameLen = struct.unpack('B', buf[1])[0]
                pos += 1

                dbFilename = buf[pos:pos+dbFilenameLen]
                pos += dbFilenameLen

                siteNameLen = struct.unpack('B', buf[pos])[0]
                pos += 1

                siteName = buf[pos:pos+siteNameLen]
                pos += siteNameLen

                results[infoCode] = (conLocalityCode, dbFilename, siteName)
            elif infoCode == isc_info_implementation:
                # (IB 6 API Guide page 52)
                buf = self.database_info(infoCode, 's')
                # Skip the first four bytes.
                pos = 1

                implNumber = struct.unpack('B', buf[pos])[0]
                pos += 1

                classNumber = struct.unpack('B', buf[pos])[0]
                pos += 1

                results[infoCode] = (implNumber, classNumber)
            elif infoCode in (isc_info_version, isc_info_firebird_version):
                # (IB 6 API Guide page 53)
                buf = self.database_info(infoCode, 's')
                # Skip the first byte.
                pos = 1

                versionStringLen = struct.unpack('B', buf[pos])[0]
                pos += 1

                versionString = buf[pos:pos+versionStringLen]

                results[infoCode] = versionString
            elif infoCode == isc_info_user_names:
                # (IB 6 API Guide page 54)
                #
                # The isc_info_user_names results buffer does not exactly match
                # the format declared on page 54 of the IB 6 API Guide.
                #   The buffer is formatted as a sequence of clusters, each of
                # which begins with the byte isc_info_user_names, followed by a
                # two-byte cluster length, followed by a one-byte username
                # length, followed by a single username.
                #   I don't understand why the lengths are represented
                # redundantly (the two-byte cluster length is always one
                # greater than the one-byte username length), but perhaps it's
                # an attempt to adhere to the general format of an information
                # cluster declared on page 51 while also [trying, but failing
                # to] adhere to the isc_info_user_names-specific format
                # declared on page 54.
                buf = self.database_info(infoCode, 's')

                usernames = []
                pos = 0
                while pos < len(buf):
                    if struct.unpack('B', buf[pos])[0] != isc_info_user_names:
                        raise OperationalError('While trying to service'
                            ' isc_info_user_names request, found unexpected'
                            ' results buffer contents at position %d of [%s]'
                            % (pos, buf)
                          )
                    pos += 1

                    # The two-byte cluster length:
                    nameClusterLen = struct.unpack('<H', buf[pos:pos+2])[0]
                    pos += 2

                    # The one-byte username length:
                    nameLen = struct.unpack('B', buf[pos])[0]
                    assert nameLen == nameClusterLen - 1
                    pos += 1

                    usernames.append(buf[pos:pos+nameLen])
                    pos += nameLen

                # The client-exposed return value is a dictionary mapping
                # username -> number of connections by that user.
                res = {}
                for un in usernames:
                    res[un] = res.get(un, 0) + 1

                results[infoCode] = res
            elif infoCode in _DATABASE_INFO_CODES_WITH_INT_RESULT:
                results[infoCode] = self.database_info(infoCode, 'i')
            elif infoCode in _DATABASE_INFO_CODES_WITH_COUNT_RESULTS:
                buf = self.database_info(infoCode, 's')
                countsByRelId = _extractDatabaseInfoCounts(buf)
                # Decided not to convert the relation IDs to relation names
                # for two reasons:
                #  1) Performance + Principle of Least Surprise
                #     If the client program is trying to do some delicate
                #     performance measurements, it's not helpful for
                #     kinterbasdb to be issuing unexpected queries behind the
                #     scenes.
                #  2) Field RDB$RELATIONS.RDB$RELATION_NAME is a CHAR field,
                #     which means its values emerge from the database with
                #     trailing whitespace, yet it's not safe in general to
                #     strip that whitespace because actual relation names can
                #     have trailing whitespace (think
                #     'create table "table1 " (f1 int)').
                results[infoCode] = countsByRelId
            elif infoCode in _DATABASE_INFO_CODES_WITH_TIMESTAMP_RESULT:
                buf = self.database_info(infoCode, 's')
                timestampTuple = raw_timestamp_to_tuple(buf)
                registeredConverter = self.get_type_trans_out()['TIMESTAMP']
                timestamp = registeredConverter(timestampTuple)
                results[infoCode] = timestamp
            else:
                raise ValueError('Unrecognized database info code %s'
                    % str(infoCode)
                  )

        if requestIsSingleton:
            return results[request[0]]
        else:
            return results


    def transaction_info(self, request, result_type):
        return self._main_trans.transaction_info(request, result_type)

    def trans_info(self, request):
        return self._main_trans.trans_info(request)


    def trans(self, tpb=None):
        "Creates a new Transaction that operates within the context of this"
        " connection.  Cursors can be created within that Transaction via its"
        " .cursor() method."
        return Transaction(con=self, tpb=tpb)


    def cursor(self):
        "Creates a new cursor that operates within the context of this"
        " connection's main_transaction."
        return self._main_trans.cursor()


    def close(self):
        "Closes the connection to the database server."
        self._ensure_group_membership(False, "Cannot close a connection that"
            " is a member of a ConnectionGroup."
          )
        self._close_physical_connection(raiseExceptionOnError=True)


    # closed read-only property:
    def _closed_get(self):
        return _k.Connection_closed_get(self._C_con)
    closed = property(_closed_get)


    def _close_physical_connection(self, raiseExceptionOnError=True):
        # Sever the physical connection to the database server and replace our
        # underyling _kinterbasdb.ConnectionType object with a null instance
        # of that type, so that post-close() method calls on this connection
        # will raise ProgrammingErrors, as required by the DB API Spec.
        try:
            if getattr(self, '_C_con', None) is not None:
                if (    _k
                    and self._C_con is not _k.null_connection
                    and not _k.Connection_closed_get(self._C_con)
                  ):
                    try:
                        _k.Connection_close(self._C_con)
                    except ProgrammingError:
                        if raiseExceptionOnError:
                            raise
                    self._C_con = _k.null_connection
                elif raiseExceptionOnError:
                    raise ProgrammingError('Connection is already closed.')
        except:
            if raiseExceptionOnError:
                raise


    def _has_db_handle(self):
        return self._C_con is not _k.null_connection


    def _has_transaction(self):
        # Does this connection currently have an active transaction (including
        # a distributed transaction)?
        return _k.Connection_has_active_transaction(self._C_con)

    def _normalize_type_trans(self):
        # Set the type translation dictionaries to their "normal" form--the
        # minumum required for standard kinterbasdb operation.
        self.set_type_trans_in(_NORMAL_TYPE_TRANS_IN)
        self.set_type_trans_out(_NORMAL_TYPE_TRANS_OUT)

    def _enforce_min_trans(self, trans_dict, translator_source):
        #   Any $trans_dict that the Python programmer supplies for a
        # Connection must have entries for at least the types listed in
        # _MINIMAL_TYPE_TRANS_TYPES, because kinterbasdb uses dynamic type
        # translation even if it is not explicitly configured by the Python
        # client programmer.
        #   The Cursor.set_type_trans* methods need not impose the same
        # requirement, because "translator resolution" will bubble upward from
        # the cursor to its connection.
        #   This method inserts the required translators into the incoming
        # $trans_dict if that $trans_dict does not already contain them.
        # Note that $translator_source will differ between in/out translators.
        for type_name in _MINIMAL_TYPE_TRANS_TYPES:
            if type_name not in trans_dict:
                trans_dict[type_name] = translator_source[type_name]

    def set_type_trans_out(self, trans_dict):
        """
          Changes the outbound type translation map.
          For more information, see the "Dynamic Type Translation" section of
        the KInterbasDB Usage Guide.
        """
        _trans_require_dict(trans_dict)
        self._enforce_min_trans(trans_dict, _NORMAL_TYPE_TRANS_OUT)
        return _k.set_Connection_type_trans_out(self._C_con, trans_dict)

    def get_type_trans_out(self):
        """
          Retrieves the outbound type translation map.
          For more information, see the "Dynamic Type Translation" section of
        the KInterbasDB Usage Guide.
        """
        return _k.get_Connection_type_trans_out(self._C_con)

    def set_type_trans_in(self, trans_dict):
        """
          Changes the inbound type translation map.
          For more information, see the "Dynamic Type Translation" section of
        the KInterbasDB Usage Guide.
        """
        _trans_require_dict(trans_dict)
        self._enforce_min_trans(trans_dict, _NORMAL_TYPE_TRANS_IN)
        return _k.set_Connection_type_trans_in(self._C_con, trans_dict)

    def get_type_trans_in(self):
        """
          Retrieves the inbound type translation map.
          For more information, see the "Dynamic Type Translation" section of
        the KInterbasDB Usage Guide.
        """
        return _k.get_Connection_type_trans_in(self._C_con)


    if not _EVENT_HANDLING_SUPPORTED:
        def event_conduit(self, event_names):
            raise NotSupportedError("Event handling was not enabled when"
                " kinterbasdb's C layer was compiled."
              )
    else:
        def event_conduit(self, event_names):
            return _k.EventConduit_create(self._C_con, self._C_con_params,
                event_names
              )


    # default_tpb read-write property:
    def _default_tpb_get(self):
        return self._default_tpb
    def _default_tpb_set(self, value):
        self._default_tpb = _validateTPB(value)
    default_tpb = property(_default_tpb_get, _default_tpb_set)

    # The C layer of KInterbasDB uses this read-only property when it needs a
    # TPB that's strictly a memory buffer, rather than potentially a TPB
    # instance.
    def __default_tpb_str_get_(self):
        defTPB = self.default_tpb
        if not isinstance(defTPB, str):
            defTPB = defTPB.render()
        return defTPB
    _default_tpb_str_ = property(__default_tpb_str_get_)


    # dialect read-write property:
    def _dialect_get(self):
        return _k.Connection_dialect_get(self._C_con)
    def _dialect_set(self, value):
        _k.Connection_dialect_set(self._C_con, value)
    dialect = property(_dialect_get, _dialect_set)


    # precision_mode read-write property (deprecated):
    def _precision_mode_get(self):
        # Postpone this warning until a later version:
        #import warnings # Lazy import.
        #warnings.warn(
        #    'precision_mode is deprecated in favor of dynamic type'
        #    ' translation (see the [set|get]_type_trans_[in|out] methods).',
        #    DeprecationWarning
        #  )
        return self._precision_mode
    def _precision_mode_set(self, value):
        # Postpone this warning until a later version:
        #import warnings # Lazy import.
        #warnings.warn(
        #    'precision_mode is deprecated in favor of dynamic type'
        #    ' translation (see the [set|get]_type_trans_[in|out] methods).',
        #    DeprecationWarning
        #  )
        value = bool(value)

        # Preserve the previous DTT settings that were in place before this
        # call to the greatest extent possible (although dynamic type
        # translation and the precision_mode attribute really aren't meant to
        # be used together).
        trans_in = self.get_type_trans_in()
        trans_out = self.get_type_trans_out()

        if value: # precise:
            trans_in['FIXED']  = fixed_conv_in_precise
            trans_out['FIXED'] = fixed_conv_out_precise
        else: # imprecise:
            trans_in['FIXED']  = fixed_conv_in_imprecise
            trans_out['FIXED'] = fixed_conv_out_imprecise

        self.set_type_trans_in(trans_in)
        self.set_type_trans_out(trans_out)

        self._precision_mode = value
    precision_mode = property(_precision_mode_get, _precision_mode_set)


    # server_version read-only property:
    def _server_version_get(self):
        return self.db_info(isc_info_version)
    server_version = property(_server_version_get)


    # charset read-only property:
    def _charset_get(self):
        return self._charset
    def _charset_set(self, value):
        # More informative error message:
        raise AttributeError("A connection's 'charset' property can be"
            " specified upon Connection creation as a keyword argument to"
            " kinterbasdb.connect, but it cannot be modified thereafter."
          )
    charset = property(_charset_get, _charset_set)


    def _guessBlobCharSetIDFromConnectionCharSet(self): # 2007.02.10: HACK
        if _guessTextualBlobEncodingWhenUsingFB20AndEarlier:
            from kinterbasdb.typeconv_text_unicode \
              import DB_CHAR_SET_NAME_TO_DB_CHAR_SET_ID_MAP
            return DB_CHAR_SET_NAME_TO_DB_CHAR_SET_ID_MAP.get(
                self._charset, None
              )
        else:
            return None

    # group read-only property:
    def _group_get(self):
        return self._main_trans._group
    group = property(_group_get)


    def _set_group(self, group):
        # This package-private method allows ConnectionGroup's membership
        # management functionality to bypass the conceptually read-only nature
        # of the Connection.group property.
        self._main_trans._group = group


    def _ensure_group_membership(self, must_be_member, err_msg):
        if must_be_member:
            if self.group is None:
                raise ProgrammingError(err_msg)
        else:
            if not hasattr(self, 'group'):
                return
            if self.group is not None:
                raise ProgrammingError(err_msg)


    def _timeout_enabled_get(self):
        return _k.Connection_timeout_enabled(self._C_con)
    _timeout_enabled = property(_timeout_enabled_get)

    def _main_trans_get(self):
        # NOTE:  We do not store a reference to the Transaction object within
        # this Python Connection class, because that would defeat the
        # Python-ref-cycle-free nature of the underlying C code.
        return _k.Connection_main_trans_get(self._C_con)
    _main_trans = property(_main_trans_get)

    def _main_transaction_get(self):
        # NOTE:  We do not store a reference to the
        # ExternallyVisibleMainTransaction object within this Python Connection
        # class, because that would defeat the Python-ref-cycle-free nature of
        # the underlying C code.
        return ExternallyVisibleMainTransaction(self._main_trans)
    main_transaction = property(_main_transaction_get)

    def _transactions_get(self):
        return _k.Connection_transactions_get(self._C_con)
    transactions = property(_transactions_get)


    def _activity_stamps(self):
        return _k.Connection__read_activity_stamps(self._C_con)


class ExternallyVisibleMainTransaction(Transaction):
    # Accept an internal (Transaction_is_main(t)) kinterbasdb.Transaction
    # instance and wrap it, impersonating it as closely as possible.  Since
    # the internal Transaction object does not own a reference to its
    # Connection (*unlike* Transaction objects explicitly created by client
    # code), this proxy ensures that the Connection remains alive at least as
    # long as externally held references to its internal Transaction.
    def __init__(self, rawMainTrans):
        Transaction.__setattr__(self, '_rawMainTrans', rawMainTrans)
        Transaction.__setattr__(self, '_rawMainTrans_con',
            rawMainTrans.connection
          )

    def __getattribute__(self, name):
        return getattr(
            Transaction.__getattribute__(self, '_rawMainTrans'), name
          )

    def __cmp__(self, other):
        return cmp(Transaction.__getattribute__(self, '_rawMainTrans'), other)

    def __hash__(self):
        return hash(Transaction.__getattribute__(self, '_rawMainTrans'))


class ConnectionGroup(object):
    # XXX: ConnectionGroup objects currently are not thread-safe.  Since
    # separate Connections can be manipulated simultaneously by different
    # threads in kinterbasdb, it would make sense for a container of multiple
    # connections to be safely manipulable simultaneously by multiple threads.

    # XXX: Adding two connections to the same database freezes the DB client
    # library.  However, I've no way to detect with certainty whether any given
    # con1 and con2 are connected to the same database, what with database
    # aliases, IP host name aliases, remote-vs-local protocols, etc.
    # Therefore, a warning must be added to the docs.

    def __init__(self, connections=()):
        _ensureInitialized()

        self._cons = []
        self._trans_handle = None

        for con in connections:
            self.add(con)


    def __del__(self):
        self.disband()


    def disband(self):
        # Notice that the ConnectionGroup rollback()s itself BEFORE releasing
        # its Connection references.
        if getattr(self, '_trans_handle', None) is not None:
            self.rollback()
        if hasattr(self, '_cons'):
            self.clear()


    # Membership methods:
    def add(self, con):
        ### CONTRAINTS ON $con: ###
        # con must be an instance of kinterbasdb.Connection:
        if not isinstance(con, Connection):
            raise TypeError('con must be an instance of'
                ' kinterbasdb.Connection'
              )
        # con cannot already be a member of this group:
        if con in self:
            raise ProgrammingError('con is already a member of this group.')
        # con cannot belong to more than one group at a time:
        if con.group:
            raise ProgrammingError('con is already a member of another group;'
                ' it cannot belong to more than one group at once.'
              )
        # con cannot be added if it has an active transaction:
        if con._has_transaction():
            raise ProgrammingError('con already has an active transaction;'
                ' that must be resolved before con can join this group.'
              )
        # con must be connected to a database; it must not have been closed.
        if not con._has_db_handle():
            raise ProgrammingError('con has been closed; it cannot join a'
                ' group.'
              )

        if con._timeout_enabled:
            raise ProgrammingError('Connections with timeout enabled cannot'
                ' participate in distributed transactions.'
              )

        ### CONTRAINTS ON $self: ###
        # self cannot accept new members while self has an unresolved
        # transaction:
        self._require_transaction_state(False,
            'Cannot add connection to group that has an unresolved'
            ' transaction.'
          )
        # self cannot have more than DIST_TRANS_MAX_DATABASES members:
        if self.count() >= DIST_TRANS_MAX_DATABASES:
            raise ProgrammingError('The database engine limits the number of'
                ' database handles that can participate in a single'
                ' distributed transaction to %d or fewer; this group already'
                ' has %d members.'
                % (DIST_TRANS_MAX_DATABASES, self.count())
              )

        ### CONTRAINTS FINISHED ###

        # Can't set con.group directly (read-only); must use package-private
        # method.
        con._set_group(self)
        self._cons.append(con)


    def remove(self, con):
        if con not in self:
            raise ProgrammingError('con is not a member of this group.')
        assert con.group is self
        self._require_transaction_state(False,
            'Cannot remove connection from group that has an unresolved'
            ' transaction.'
          )

        con._set_group(None)
        self._cons.remove(con)


    def clear(self):
        self._require_transaction_state(False,
            'Cannot clear group that has an unresolved transaction.'
          )
        for con in self.members():
            self.remove(con)
        assert self.count() == 0


    def members(self):
        return self._cons[:] # return a *copy* of the internal list


    def count(self):
        return len(self._cons)


    def contains(self, con):
        return con in self._cons
    __contains__ = contains # alias to support the 'in' operator


    def __iter__(self):
        return iter(self._cons)


    # Transactional methods:
    def _require_transaction_state(self, must_be_active, err_msg=''):
        trans_handle = self._trans_handle
        if (
               (must_be_active and trans_handle is None)
            or (not must_be_active and trans_handle is not None)
          ):
            raise ProgrammingError(err_msg)


    def _require_non_empty_group(self, operation_name):
        if self.count() == 0:
            raise ProgrammingError('Cannot %s distributed transaction with'
                ' an empty ConnectionGroup.' % operation_name
              )


    def begin(self):
        self._require_transaction_state(False,
            'Must resolve current transaction before starting another.'
          )
        self._require_non_empty_group('start')
        self._trans_handle = _k.distributed_begin(self, self._cons)


    def prepare(self):
        """
          Manually triggers the first phase of a two-phase commit (2PC).  Use
        of this method is optional; if preparation is not triggered manually,
        it will be performed implicitly by commit() in a 2PC.
        """
        self._require_non_empty_group('prepare')
        self._require_transaction_state(True,
            'This group has no transaction to prepare.'
          )

        _k.distributed_prepare(self._trans_handle)


    def commit(self, retaining=False):
        self._require_non_empty_group('commit')
        # The consensus among Python DB API experts is that transactions should
        # always be started implicitly, even if that means allowing a commit()
        # or rollback() without an actual transaction.
        if self._trans_handle is None:
            return

        _k.distributed_commit(self, self._trans_handle, self._cons, retaining)
        self._trans_handle = None


    def rollback(self, retaining=False):
        self._require_non_empty_group('roll back')
        # The consensus among Python DB API experts is that transactions should
        # always be started implicitly, even if that means allowing a commit()
        # or rollback() without an actual transaction.
        if self._trans_handle is None:
            return

        _k.distributed_rollback(self, self._trans_handle, self._cons, retaining)
        self._trans_handle = None


##########################################
##     PUBLIC CLASSES: END              ##
##########################################

class _RowMapping(object):
    """
      An internal kinterbasdb class that wraps a row of results in order to map
    field name to field value.

      kinterbasdb makes ABSOLUTELY NO GUARANTEES about the return value of the
    fetch(one|many|all) methods except that it is a sequence indexed by field
    position, and no guarantees about the return value of the
    fetch(one|many|all)map methods except that it is a mapping of field name
    to field value.
      Therefore, client programmers should NOT rely on the return value being
    an instance of a particular class or type.
    """

    def __init__(self, description, row):
        self._description = description
        fields = self._fields = {}
        pos = 0
        for fieldSpec in description:
            # It's possible for a result set from the database engine to return
            # multiple fields with the same name, but kinterbasdb's key-based
            # row interface only honors the first (thus setdefault, which won't
            # store the position if it's already present in self._fields).
            fields.setdefault(fieldSpec[DESCRIPTION_NAME], row[pos])
            pos += 1


    def __len__(self):
        return len(self._fields)


    def __getitem__(self, fieldName):
        fields = self._fields
        # Straightforward, unnormalized lookup will work if the fieldName is
        # already uppercase and/or if it refers to a database field whose
        # name is case-sensitive.
        if fieldName in fields:
            return fields[fieldName]
        else:
            fieldNameNormalized = _normalizeDatabaseIdentifier(fieldName)
            try:
                return fields[fieldNameNormalized]
            except KeyError:
                raise KeyError('Result set has no field named "%s".  The field'
                    ' name must be one of: (%s)'
                    % (fieldName, ', '.join(fields.keys()))
                  )


    def get(self, fieldName, defaultValue=None):
        try:
            return self[fieldName]
        except KeyError:
            return defaultValue


    def __contains__(self, fieldName):
        try:
            self[fieldName]
        except KeyError:
            return False
        else:
            return True


    def __str__(self):
        # Return an easily readable dump of this row's field names and their
        # corresponding values.
        return '<result set row with %s>' % ', '.join([
            '%s = %s' % (fieldName, self[fieldName])
            for fieldName in self._fields.keys()
          ])


    def keys(self):
        # Note that this is an *ordered* list of keys.
        return [fieldSpec[DESCRIPTION_NAME] for fieldSpec in self._description]


    def values(self):
        # Note that this is an *ordered* list of values.
        return [self[fieldName] for fieldName in self.keys()]


    def items(self):
        return [(fieldName, self[fieldName]) for fieldName in self.keys()]


    def iterkeys(self):
        for fieldDesc in self._description:
            yield fieldDesc[DESCRIPTION_NAME]

    __iter__ = iterkeys


    def itervalues(self):
        for fieldName in self:
            yield self[fieldName]


    def iteritems(self):
        for fieldName in self:
            yield fieldName, self[fieldName]


class _DPBBuilder(object):
    def buildFromParamDict(self, d):
        dsn = d.get('dsn', None)
        host = d.get('host', None)
        database = d.get('database', None)

        user = d.get('user', os.environ.get('ISC_USER', None))
        password = d.get('password', os.environ.get('ISC_PASSWORD', None))
        role = d.get('role', None)
        charset = d.get('charset', None)
        dialect = d.get('dialect', 0)
        dpbEntries = d.get('dpb_entries', ())

        self.dsn = self.buildDSNFrom(dsn, host, database)
        del dsn, host, database

        # Build <<DPB>>:begin:
        # Build the database parameter buffer.  self._dpb is a list of binary
        # strings that will be rolled up into a single binary string and
        # passed, ultimately, to the C function isc_att4ch_database as the
        # 'dpb' argument.

        self.initializeDPB()

        self.addStringIfProvided(isc_dpb_user_name, user)
        self.addStringIfProvided(isc_dpb_password, password)
        self.addStringIfProvided(isc_dpb_sql_role_name, role)

        self.charset = (charset and charset.upper()) or None
        if self.charset:
            self.addString(isc_dpb_lc_ctype, charset)

        self.processUserSuppliedDPBEntries(dpbEntries)

        self.renderDPB()

        # Leave dialect alone; the C code will validate it.
        self.dialect = dialect

        assert self.dsn is not None
        assert self.dpb is not None
        assert self.dialect is not None
        assert hasattr(self, 'charset')


    def buildDSNFrom(self, dsn, host, database):
        if (   (not dsn and not host and not database)
            or (dsn and (host or database))
            or (host and not database)
          ):
            raise ProgrammingError(
                "Must supply one of:\n"
                " 1. keyword argument dsn='host:/path/to/database'\n"
                " 2. both keyword arguments host='host' and"
                   " database='/path/to/database'\n"
                " 3. only keyword argument database='/path/to/database'"
              )

        if not dsn:
            if host and host.endswith(':'):
                raise ProgrammingError('Host must not end with a colon.'
                    ' You should specify host="%s" rather than host="%s".'
                    % (host[:-1], host)
                  )
            elif host:
                dsn = '%s:%s' % (host, database)
            else:
                dsn = database

        if _FS_ENCODING: # 2007.03.19
            dsn = dsn.encode(_FS_ENCODING)

        assert dsn, 'Internal error in _build_connect_structures DSN prep.'
        return dsn


    def initializeDPB(self):
        # Start with requisite DPB boilerplate, a single byte that informs the
        # database API what version of DPB it's dealing with:
        self._dpb = [ struct.pack('c', isc_dpb_version1) ]


    def renderDPB(self):
        self.dpb = ''.join(self._dpb)


    def addString(self, codeAsByte, s):
        # Append a string parameter to the end of the DPB.  A string parameter
        # is represented in the DPB by the following binary sequence:
        #  - a 1-byte byte code telling the purpose of the upcoming string
        #  - 1 byte telling the length of the upcoming string
        #  - the string itself
        # See IB 6 API guide page 44 for documentation of what's is going on
        # here.
        self._validateCode(codeAsByte)

        sLen = len(s)
        if sLen >= 256:
            # Because the length is denoted in the DPB by a single byte.
            raise ProgrammingError('Individual component of database'
                ' parameter buffer is too large.  Components must be less'
                ' than 256 bytes.'
              )
        format = 'cc%ds' % sLen # like 'cc50s' for a 50-byte string
        newEntry = struct.pack(format, codeAsByte, chr(sLen), s)

        self._dpb.append(newEntry)


    def addStringIfProvided(self, codeAsByte, value):
        if value:
            self.addString(codeAsByte, value)


    def addInt(self, codeAsByte, value):
        self._validateCode(codeAsByte)

        if not isinstance(value, (int, long)) or value < 0 or value > 255:
            raise ProgrammingError('The value for an integer DPB code must be'
                ' an int or long with a value between 0 and 255.'
              )

        newEntry = struct.pack('ccc', codeAsByte, '\x01', chr(value))

        self._dpb.append(newEntry)


    def processUserSuppliedDPBEntries(self, dpbEntries):
        # 'dpb_entries' is supposed to be a sequence of 2- or 3-tuples,
        # containing:
        #   (code, value[, type])
        # kinterbasdb doesn't need the type specified for codes that it already
        # recognizes, but for future codes, the user can specify the type,
        # which controls how the code is inserted into the DPB.
        for i, entry in enumerate(dpbEntries):
            codeAsByte = entry[0]
            value = entry[1]
            if len(entry) > 2:
                typeCode = entry[2]
            else:
                typeCode = None

            if typeCode is None:
                if codeAsByte in _DPB_CODES_WITH_STRING_VALUE:
                    typeCode = 's'
                elif codeAsByte in _DPB_CODE_WITH_INT_VALUE:
                    typeCode = 'i'
                else:
                    raise ProgrammingError('kinterbasdb cannot automatically'
                        ' recognize DPB code %s.  You need to supply a type'
                        ' code (either \'s\' or \'i\') as the third element of'
                        ' user-supplied DPB entry #%d.'
                        % (repr(codeAsByte), i + 1)
                      )

            if typeCode == 's':
                self.addString(codeAsByte, value)
            elif typeCode == 'i':
                self.addInt(codeAsByte, value)
            else:
                raise ProgrammingError('The supplied DPB type code must be'
                    ' either \'s\' or \'i\'.'
                  )


    def _validateCode(self, code):
        if not isinstance(code, str) or len(code) != 1:
            raise ProgrammingError('DPB code must be single-character str.')


# All DPB codes as of FB 2.0.0b1:
  # Note:  Many of these codes duplicate the functionality provided by the
  # Services API, so I've only attempted to add automatic recognition support
  # for the most useful parameters.

  # isc_dpb_version1
  # isc_dpb_cdd_pathname
  # isc_dpb_allocation
  # isc_dpb_journal
  # isc_dpb_page_size
  # isc_dpb_num_buffers
  # isc_dpb_buffer_length
  # isc_dpb_debug
  # isc_dpb_garbage_collect
  # isc_dpb_verify
  # isc_dpb_sweep
  # isc_dpb_enable_journal
  # isc_dpb_disable_journal
  # isc_dpb_dbkey_scope
  # isc_dpb_number_of_users
  # isc_dpb_trace
  # isc_dpb_no_garbage_collect
  # isc_dpb_damaged
  # isc_dpb_license
  # isc_dpb_sys_user_name : s
  # isc_dpb_encrypt_key
  # isc_dpb_activate_shadow
  # isc_dpb_sweep_interval
  # isc_dpb_delete_shadow
  # isc_dpb_force_write
  # isc_dpb_begin_log
  # isc_dpb_quit_log
  # isc_dpb_no_reserve
  # isc_dpb_user_name
  # isc_dpb_password : s
  # isc_dpb_password_enc
  # isc_dpb_sys_user_name_enc
  # isc_dpb_interp
  # isc_dpb_online_dump
  # isc_dpb_old_file_size
  # isc_dpb_old_num_files
  # isc_dpb_old_file
  # isc_dpb_old_start_page
  # isc_dpb_old_start_seqno
  # isc_dpb_old_start_file
  # isc_dpb_drop_walfile
  # isc_dpb_old_dump_id
  # isc_dpb_wal_backup_dir
  # isc_dpb_wal_chkptlen
  # isc_dpb_wal_numbufs
  # isc_dpb_wal_bufsize
  # isc_dpb_wal_grp_cmt_wait
  # isc_dpb_lc_messages : s
  # isc_dpb_lc_ctype
  # isc_dpb_cache_manager
  # isc_dpb_shutdown
  # isc_dpb_online
  # isc_dpb_shutdown_delay
  # isc_dpb_reserved
  # isc_dpb_overwrite
  # isc_dpb_sec_attach
  # isc_dpb_disable_wal
  # isc_dpb_connect_timeout : i
  # isc_dpb_dummy_packet_interval : i
  # isc_dpb_gbak_attach
  # isc_dpb_sql_role_name
  # isc_dpb_set_page_buffers
  # isc_dpb_working_directory
  # isc_dpb_sql_dialect : i
  # isc_dpb_set_db_readonly
  # isc_dpb_set_db_sql_dialect : i
  # isc_dpb_gfix_attach
  # isc_dpb_gstat_attach
  # isc_dpb_set_db_charset : s


_DPB_CODES_WITH_STRING_VALUE = [
    isc_dpb_user_name,
    isc_dpb_password,
    isc_dpb_lc_messages,
  ]
if 'isc_dpb_set_db_charset' in globals():
    _DPB_CODES_WITH_STRING_VALUE.append(isc_dpb_set_db_charset)


_DPB_CODE_WITH_INT_VALUE = [
    isc_dpb_connect_timeout,
    isc_dpb_dummy_packet_interval,
    isc_dpb_sql_dialect,
    isc_dpb_set_db_sql_dialect,
  ]


def _trans_require_dict(obj):
    if not isinstance(obj, dict):
        raise TypeError(
            "The dynamic type translation table must be a dictionary, not a %s"
            % ( (hasattr(obj, '__class__') and obj.__class__.__name__)
                or str(type(obj))
              )
          )


_OUT_TRANS_FUNC_SAMPLE_ARGS = {
    'TEXT':             'sample',
    'TEXT_UNICODE':     ('sample', 3),
    'BLOB':             'sample',
    'INTEGER':          1,
    'FLOATING':         1.0,
    'FIXED':            (10, -1),
    'DATE':             (2003,12,31),
    'TIME':             (23,59,59),
    'TIMESTAMP':        (2003,12,31,23,59,59),
  }

def _make_output_translator_return_type_dict_from_trans_dict(trans_dict):
    # This Python function is called from the C level; don't remove it.
    #
    # Calls each output translator in trans_dict, passing the translator sample
    # arguments and recording its return type.
    # Returns a mapping of translator key -> return type.
    trans_return_types = {}
    for (trans_key, translator) in trans_dict.items():
        if isinstance(trans_key, int):
            # The type entry in Cursor.description is not updated properly to
            # reflect *positional* DTT settings, and I can think of no
            # reasonable way to correct that.
            continue

        # Follow this path for any 'BLOB' DTT with a dict translator--the
        # contents of the dict will be validated later, at the C level.
        if trans_key == 'BLOB' and isinstance(translator, dict):
            if translator.get('mode', None) == 'stream':
                trans_return_types[trans_key] = BlobReader
            continue

        if translator is None:
            # Don't make an entry for "naked" translators; the
            # Cursor.description creation code will fall back on the default
            # type.
            continue

        try:
            sample_arg = _OUT_TRANS_FUNC_SAMPLE_ARGS[trans_key]
        except KeyError:
            raise ProgrammingError(
                "Cannot translate type '%s'. Type must be one of %s."
                % (trans_key, _OUT_TRANS_FUNC_SAMPLE_ARGS.keys())
              )
        return_val = translator(sample_arg)
        return_type = type(return_val)
        trans_return_types[trans_key] = return_type
    return trans_return_types


class TPB(_RequestBufferBuilder):
    def __init__(self):
        _RequestBufferBuilder.__init__(self)

        self._access_mode = isc_tpb_write

        self._isolation_level = isc_tpb_concurrency

        self._lock_resolution = isc_tpb_wait
        self._lock_timeout = None

        self._table_reservation = None

    def copy(self):
        # A shallow copy of self would be entirely safe except that
        # .table_reservation is a complex object that needs to be copied
        # separately.
        import copy

        other = copy.copy(self)
        if self._table_reservation is not None:
            other._table_reservation = copy.copy(self._table_reservation)
        return other

    def render(self):
        # YYY: Optimization:  Could memoize the rendered TPB str.
        self.clear()

        self._addCode(isc_tpb_version3)

        self._addCode(self._access_mode)

        il = self._isolation_level
        if not isinstance(il, tuple):
            il = (il,)
        for code in il:
            self._addCode(code)

        self._addCode(self._lock_resolution)
        if self._lock_timeout is not None:
            self._addCode(isc_tpb_lock_timeout)
            self._addRaw(struct.pack(
                # One bytes tells the size of the following value; an unsigned
                # int tells the number of seconds to wait before timing out.
                '<bI', struct.calcsize('I'), self._lock_timeout
              ))

        if self._table_reservation is not None:
            self._addRaw(self._table_reservation.render())

        return _RequestBufferBuilder.render(self)

    # access_mode property:
    def _get_access_mode(self):
        return self._access_mode
    def _set_access_mode(self, access_mode):
        if access_mode not in (isc_tpb_read, isc_tpb_write):
            raise ProgrammingError('Access mode must be one of'
                ' (isc_tpb_read, isc_tpb_write).'
              )
        self._access_mode = access_mode
    access_mode = property(_get_access_mode, _set_access_mode)

    # isolation_level property:
    def _get_isolation_level(self):
        return self._isolation_level
    def _set_isolation_level(self, isolation_level):
        if isinstance(isolation_level, tuple):
            if len(isolation_level) != 2:
                raise ProgrammingError('The tuple variant of isolation level'
                    ' must have two elements:  isc_tpb_read_committed in the'
                    ' first element and one of (isc_tpb_rec_version,'
                    ' isc_tpb_no_rec_version) in the second.'
                  )
            isolation_level, suboption = isolation_level
        elif isolation_level == isc_tpb_read_committed:
            suboption = isc_tpb_rec_version

        if isolation_level not in (
            isc_tpb_concurrency, isc_tpb_consistency, isc_tpb_read_committed
          ):
            raise ProgrammingError('Isolation level must be one of'
                ' (isc_tpb_concurrency, isc_tpb_consistency,'
                ' isc_tpb_read_committed).'
              )

        if isolation_level == isc_tpb_read_committed:
            if suboption not in (isc_tpb_rec_version, isc_tpb_no_rec_version):
                raise ProgrammingError('With isolation level'
                    ' isc_tpb_read_committed, suboption must be one of'
                    ' (isc_tpb_rec_version, isc_tpb_no_rec_version).'
                  )
            isolation_level = isolation_level, suboption

        self._isolation_level = isolation_level
    isolation_level = property(_get_isolation_level, _set_isolation_level)

    # lock_resolution property:
    def _get_lock_resolution(self):
        return self._lock_resolution
    def _set_lock_resolution(self, lock_resolution):
        if lock_resolution not in (isc_tpb_wait, isc_tpb_nowait):
            raise ProgrammingError('Lock resolution must be one of'
                ' (isc_tpb_wait, isc_tpb_nowait).'
              )
        self._lock_resolution = lock_resolution
    lock_resolution = property(_get_lock_resolution, _set_lock_resolution)

    # lock_timeout property:
    def _get_lock_timeout(self):
        return self._lock_timeout
    def _set_lock_timeout(self, lock_timeout):
        if lock_timeout is not None:
            UINT_MAX = 2 ** (struct.calcsize('I') * 8) - 1
            if (not isinstance(lock_timeout, (int, long))) or (
                lock_timeout < 0 or lock_timeout > UINT_MAX
              ):
                raise ProgrammingError('Lock resolution must be either None'
                    ' or a non-negative int number of seconds between 0 and'
                    ' %d.' % UINT_MAX
                  )

        self._lock_timeout = lock_timeout
    lock_timeout = property(_get_lock_timeout, _set_lock_timeout)

    # table_reservation property (an instance of TableReservation):
    def _get_table_reservation(self):
        if self._table_reservation is None:
            self._table_reservation = TableReservation()
        return self._table_reservation
    def _set_table_reservation_access(self, _):
        raise ProgrammingError('Instead of changing the value of the'
            ' .table_reservation object itself, you must change its *elements*'
            ' by manipulating it as though it were a dictionary that mapped'
            '\n  "TABLE_NAME": (sharingMode, accessMode)'
            '\nFor example:'
            '\n  tpbBuilder.table_reservation["MY_TABLE"] ='
            ' (kinterbasdb.isc_tpb_protected, kinterbasdb.isc_tpb_lock_write)'
          )
    table_reservation = property(
        _get_table_reservation, _set_table_reservation_access
      )


class TableReservation(object):
    _MISSING = object()
    _SHARING_MODE_STRS = {
        isc_tpb_shared:    'isc_tpb_shared',
        isc_tpb_protected: 'isc_tpb_protected',
        isc_tpb_exclusive: 'isc_tpb_exclusive',
      }
    _ACCESS_MODE_STRS = {
        isc_tpb_lock_read:  'isc_tpb_lock_read',
        isc_tpb_lock_write: 'isc_tpb_lock_write',
      }

    def __init__(self):
        self._res = {}

    def copy(self):
        # A shallow copy is fine.
        import copy
        return copy.copy(self)

    def render(self):
        if not self:
            return ''

        frags = []
        _ = frags.append
        for tableName, resDefs in self.iteritems():
            tableNameLenWithTerm = len(tableName) + 1
            for (sharingMode, accessMode) in resDefs:
                _(accessMode)
                _(struct.pack('<b%ds' % tableNameLenWithTerm,
                    tableNameLenWithTerm, tableName
                  ))
                _(sharingMode)

        return ''.join(frags)

    def __len__(self):
        return sum([len(item) for item in self._res.items()])

    def __nonzero__(self):
        return len(self) != 0

    def __getitem__(self, key):
        key = self._validateKey(key)

        if key in self._res:
            return self._res[key]
        else:
            nonNormalizedKey = key
            key = _normalizeDatabaseIdentifier(key)
            try:
                return self._res[key]
            except KeyError:
                raise KeyError('No table named "%s" is present.'
                    % nonNormalizedKey
                  )

    def get(self, key, default=None):
        try:
            return self[key]
        except (KeyError, TypeError):
            return default

    def __contains__(self, key):
        return (
            self.get(key, TableReservation._MISSING)
            is not TableReservation._MISSING
          )

    def __str__(self):
        if not self:
            return '<TableReservation with no entries>'

        frags = ['<TableReservation with entries:\n']
        _ = frags.append
        for tableName, resDefs in self.iteritems():
            _('  "%s":\n' % tableName)
            for rd in resDefs:
                sharingModeStr = TableReservation._SHARING_MODE_STRS[rd[0]]
                accessModeStr = TableReservation._ACCESS_MODE_STRS[rd[1]]
                _('    (%s, %s)\n' % (sharingModeStr, accessModeStr))
        _('>')
        return ''.join(frags)

    def keys(self):
        return self._res.keys()

    def values(self):
        return self._res.values()

    def items(self):
        return self._res.items()

    def iterkeys(self):
        return self._res.iterkeys()

    def itervalues(self):
        return self._res.itervalues()

    def iteritems(self):
        return self._res.iteritems()

    def __setitem__(self, key, value):
        key = self._validateKey(key)
        key = _normalizeDatabaseIdentifier(key)

        # If the += operator is being applied, the form of value will be like:
        #   [(sharingMode0, accessMode0), ..., newSharingMode, newAccessMode]
        # For the sake of convenience, we detect this situation and handle it
        # "naturally".
        if isinstance(value, list) and len(value) >= 3:
            otherValues = value[:-2]
            value = tuple(value[-2:])
        else:
            otherValues = None

        if (
               (not isinstance(value, tuple))
            or len(value) != 2
            or value[0] not in
                 (isc_tpb_shared, isc_tpb_protected, isc_tpb_exclusive)
            or value[1] not in (isc_tpb_lock_read, isc_tpb_lock_write)
          ):
            raise ValueError('Table reservation entry must be a 2-tuple of'
                ' the following form:\n'
                'element 0: sharing mode (one of (isc_tpb_shared,'
                  ' isc_tpb_protected, isc_tpb_exclusive))\n'
                'element 1: access mode (one of (isc_tpb_lock_read,'
                  ' isc_tpb_lock_write))\n'
                '%s is not acceptable.' % str(value)
              )

        if otherValues is None:
            value = [value]
        else:
            otherValues.append(value)
            value = otherValues

        self._res[key] = value

    def _validateKey(self, key):
        keyMightBeAcceptable = isinstance(key, basestring)
        if keyMightBeAcceptable and isinstance(key, unicode):
            try:
                key = key.encode('ASCII')
            except UnicodeEncodeError:
                keyMightBeAcceptable = False

        if not keyMightBeAcceptable:
            raise TypeError('Only str keys are allowed.')

        return key


def _validateTPB(tpb):
    if isinstance(tpb, TPB):
        # TPB's accessor methods perform their own validation, and its
        # render method takes care of infrastructural trivia.
        return tpb
    elif not (isinstance(tpb, str) and len(tpb) > 0):
        raise ProgrammingError('TPB must be non-unicode string of length > 0')
    # The kinterbasdb documentation promises (or at least strongly implies)
    # that if the user tries to set a TPB that does not begin with
    # isc_tpb_version3, kinterbasdb will automatically supply that
    # infrastructural value.  This promise might cause problems in the future,
    # when isc_tpb_version3 is superseded.  A possible solution would be to
    # check the first byte against all known isc_tpb_versionX version flags,
    # like this:
    #   if tpb[0] not in (isc_tpb_version3, ..., isc_tpb_versionN):
    #      tpb = isc_tpb_version3 + tpb
    # That way, compatibility with old versions of the DB server would be
    # maintained, but client code could optionally specify a newer TPB version.
    if tpb[0] != isc_tpb_version3:
        tpb = isc_tpb_version3 + tpb
    return tpb

def _normalizeDatabaseIdentifier(ident):
    if ident.startswith('"') and ident.endswith('"'):
        # Quoted name; leave the case of the field name untouched, but
        # strip the quotes.
        return ident[1:-1]
    else:
        # Everything else is normalized to uppercase to support case-
        # insensitive lookup.
        return ident.upper()

# Contributed by Pavel Cisar; incorporated 2004.09.10:
# Connection.db_info support:

# Conditionally add codes that aren't supported by all modern versions of the
# database engine:
def _addDatabaseInfoCodeIfPresent(name, addToList):
    globalz = globals()
    if name in globalz:
        addToList.append(globalz[name])

# Int codes:
_DATABASE_INFO_CODES_WITH_INT_RESULT = [
    isc_info_allocation, isc_info_no_reserve, isc_info_db_sql_dialect,
    isc_info_ods_minor_version, isc_info_ods_version, isc_info_page_size,
    isc_info_current_memory, isc_info_forced_writes, isc_info_max_memory,
    isc_info_num_buffers, isc_info_sweep_interval, isc_info_limbo,
    isc_info_attachment_id, isc_info_fetches, isc_info_marks, isc_info_reads,
    isc_info_writes, isc_info_set_page_buffers, isc_info_db_read_only,
    isc_info_db_size_in_pages, isc_info_page_errors, isc_info_record_errors,
    isc_info_bpage_errors, isc_info_dpage_errors, isc_info_ipage_errors,
    isc_info_ppage_errors, isc_info_tpage_errors,
  ]

def _addIntDatabaseInfoCodeIfPresent(name):
    _addDatabaseInfoCodeIfPresent(name, _DATABASE_INFO_CODES_WITH_INT_RESULT)

_addIntDatabaseInfoCodeIfPresent('isc_info_oldest_transaction')
_addIntDatabaseInfoCodeIfPresent('isc_info_oldest_active')
_addIntDatabaseInfoCodeIfPresent('isc_info_oldest_snapshot')
_addIntDatabaseInfoCodeIfPresent('isc_info_next_transaction')

_addIntDatabaseInfoCodeIfPresent('isc_info_active_tran_count')

del _addIntDatabaseInfoCodeIfPresent

_DATABASE_INFO_CODES_WITH_INT_RESULT = tuple(
    _DATABASE_INFO_CODES_WITH_INT_RESULT
  )

_DATABASE_INFO_CODES_WITH_COUNT_RESULTS = (
    isc_info_backout_count, isc_info_delete_count, isc_info_expunge_count,
    isc_info_insert_count, isc_info_purge_count, isc_info_read_idx_count,
    isc_info_read_seq_count, isc_info_update_count
  )

# Timestamp codes:
_DATABASE_INFO_CODES_WITH_TIMESTAMP_RESULT = []

def _addTimestampDatabaseInfoCodeIfPresent(name):
    _addDatabaseInfoCodeIfPresent(name,
        _DATABASE_INFO_CODES_WITH_TIMESTAMP_RESULT
      )

_addTimestampDatabaseInfoCodeIfPresent('isc_info_creation_date')

del _addTimestampDatabaseInfoCodeIfPresent

_DATABASE_INFO_CODES_WITH_TIMESTAMP_RESULT = tuple(
    _DATABASE_INFO_CODES_WITH_TIMESTAMP_RESULT
  )


_DATABASE_INFO__KNOWN_LOW_LEVEL_EXCEPTIONS = (
    isc_info_user_names,
  )

def _extractDatabaseInfoCounts(buf):
    # Extract a raw binary sequence of (unsigned short, signed int) pairs into
    # a corresponding Python dictionary.
    uShortSize = struct.calcsize('<H')
    intSize = struct.calcsize('<i')
    pairSize = uShortSize + intSize
    pairCount = len(buf) / pairSize

    counts = {}
    for i in range(pairCount):
        bufForThisPair = buf[i*pairSize:(i+1)*pairSize]
        relationId = struct.unpack('<H', bufForThisPair[:uShortSize])[0]
        count      = struct.unpack('<i', bufForThisPair[uShortSize:])[0]
        counts[relationId] = count
    return counts

def _look_up_array_descriptor(con, relName, fieldName): # 2006.01.30
    # This function is just a "lazy import proxy" for the
    # _array_descriptor.look_up_array_descriptor function.
    import _array_descriptor
    return _array_descriptor.look_up_array_descriptor(con, relName, fieldName)

def _look_up_array_subtype(con, relName, fieldName): # 2006.01.30
    # This function is just a "lazy import proxy" for the
    # _array_descriptor.look_up_array_subtype function.
    import _array_descriptor
    return _array_descriptor.look_up_array_subtype(con, relName, fieldName)

def _Cursor_execute_exception_type_filter(rawCode, sqlCode, msgSegments):
    # Reactivate this code if msgSegments is used in the future:
    # if not isinstance(msgSegments, list):
        # msgSegments = [msgSegments]

    if rawCode in _TRANSACTION_CONFLICT_RAW_CODES:
        return TransactionConflict

_TRANSACTION_CONFLICT_RAW_CODES = (
    # Transaction conflict table (drawn from the error table at
    # http://firebird.sourceforge.net/doc/contrib/fb_1_5_errorcodes.pdf):
    # SQLCode, Raw Code,  Description
    #--------------------------------------------------------------------------
    # -913
      335544336,
    # deadlock:  Deadlock
    #
    # -901
      335544345,
    # lock_conflict:  Lock conflict on no wait transaction
    #
    # -901
      335544383,
    # fatal_conflict:  Unrecoverable conflict with limbo transaction <number>
    #
    # -904
      335544451,
    # update_conflict:  Update conflicts with concurrent update
    #
    # -615
      335544475,
    # relation_lock:  Lock on table <string> conflicts with existing lock
    #
    # -615
      335544476,
    # record_lock:  Requested record lock conflicts with existing lock
    #
    # -901
      335544510,
    # lock_timeout:  lock time-out on wait transaction
    #--------------------------------------------------------------------------
  )

def _trans_info(trans, request):
    # We process request as a sequence of info codes, even if only one code
    # was supplied by the caller.
    requestIsSingleton = isinstance(request, int)
    if requestIsSingleton:
        request = (request,)

    results = {}
    for infoCode in request:
        # The global().get(...) workaround is here because only recent versions
        # of FB expose constant isc_info_tra_isolation:
        if infoCode == globals().get('isc_info_tra_isolation', -1):
            buf = trans.transaction_info(infoCode, 's')
            buf = buf[1 + struct.calcsize('h'):]
            if len(buf) == 1:
                results[infoCode] = portable_int(buf)
            else:
                # For isolation level isc_info_tra_read_committed, the
                # first byte indicates the isolation level
                # (isc_info_tra_read_committed), while the second indicates
                # the record version flag (isc_info_tra_rec_version or
                # isc_info_tra_no_rec_version).
                isolationLevelByte, recordVersionByte = struct.unpack('cc', buf)
                isolationLevel = portable_int(isolationLevelByte)
                recordVersion = portable_int(recordVersionByte)
                results[infoCode] = (isolationLevel, recordVersion)
        else:
            # At the time of this writing (2006.02.09),
            # isc_info_tra_isolation is the only known return value of
            # isc_transaction_info that's not a simple integer.
            results[infoCode] = trans.transaction_info(infoCode, 'i')

    if requestIsSingleton:
        return results[request[0]]
    else:
        return results