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
|
# KInterbasDB Python Package - Python Wrapper for Core
#
# Version 3.1
#
# 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-2004 [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. Now, only module contents in "PUBLIC ..."
# sections AND with names that do not begin with an underscore can be expected
# to have stable interfaces.
from __future__ import nested_scopes # Maintain compatibility with Python 2.1
__version__ = (3, 1, 0, 'final', 0)
import struct, sys, types, warnings, weakref
try:
True, False
except NameError:
# Maintain compatibility with Python 2.1 and 2.2.0:
True = (1==1)
False = (1==0)
# 2003.12.25: For FB 1.5 RC7 and later:
# Add the directory indicated in the registry as the default installation of
# Firebird to the *end* of the PATH.
if sys.platform.lower().startswith('win'):
import _winreg, os, os.path
reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
try:
try:
dbInstPathsKey = _winreg.OpenKey(
reg, r'SOFTWARE\Firebird Project\Firebird Server\Instances'
)
try:
instPath = _winreg.QueryValueEx(dbInstPathsKey, '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:
os.environ['PATH'] += os.pathsep + os.path.join(instPath, 'bin')
finally:
reg.Close()
# The underlying C module:
import _kinterbasdb as _k
# 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
NotSupportedError = k_exceptions.NotSupportedError = _k.NotSupportedError
_ALL_EXCEPTION_CLASSES = (
Warning,
Error,
InterfaceError,
DatabaseError,
DataError,
OperationalError,
IntegrityError,
InternalError,
ProgrammingError,
NotSupportedError,
)
try:
import thread
_threads_supported = True
except ImportError:
_threads_supported = False
# Exclude event handling if support for it is not compiled into the underlying
# C module:
_EVENT_HANDLING_SUPPORTED = hasattr(_k, 'event_conduit_new')
##########################################
## PUBLIC CONSTANTS: BEGIN ##
##########################################
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
# Header constants defined by the C API of the database:
# (This implementation draws the constants' values from the database header
# files rather than relying on brittle literals.)
# Transaction parameter constants:
isc_tpb_consistency = _k.isc_tpb_consistency
isc_tpb_concurrency = _k.isc_tpb_concurrency
isc_tpb_shared = _k.isc_tpb_shared
isc_tpb_protected = _k.isc_tpb_protected
isc_tpb_exclusive = _k.isc_tpb_exclusive
isc_tpb_wait = _k.isc_tpb_wait
isc_tpb_nowait = _k.isc_tpb_nowait
isc_tpb_read = _k.isc_tpb_read
isc_tpb_write = _k.isc_tpb_write
isc_tpb_lock_read = _k.isc_tpb_lock_read
isc_tpb_lock_write = _k.isc_tpb_lock_write
isc_tpb_verb_time = _k.isc_tpb_verb_time
isc_tpb_commit_time = _k.isc_tpb_commit_time
isc_tpb_ignore_limbo = _k.isc_tpb_ignore_limbo
isc_tpb_read_committed = _k.isc_tpb_read_committed
isc_tpb_autocommit = _k.isc_tpb_autocommit
isc_tpb_rec_version = _k.isc_tpb_rec_version
isc_tpb_no_rec_version = _k.isc_tpb_no_rec_version
isc_tpb_restart_requests = _k.isc_tpb_restart_requests
isc_tpb_no_auto_undo = _k.isc_tpb_no_auto_undo
# 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).
_k.isc_tpb_version3
+ isc_tpb_concurrency
+ isc_tpb_shared
+ isc_tpb_wait
+ isc_tpb_write
+ isc_tpb_read_committed
+ isc_tpb_rec_version
)
# Database information constants:
isc_info_db_id = _k.isc_info_db_id
isc_info_reads = _k.isc_info_reads
isc_info_writes = _k.isc_info_writes
isc_info_fetches = _k.isc_info_fetches
isc_info_marks = _k.isc_info_marks
isc_info_implementation = _k.isc_info_implementation
isc_info_version = _k.isc_info_version
isc_info_base_level = _k.isc_info_base_level
isc_info_page_size = _k.isc_info_page_size
isc_info_num_buffers = _k.isc_info_num_buffers
isc_info_limbo = _k.isc_info_limbo
isc_info_current_memory = _k.isc_info_current_memory
isc_info_max_memory = _k.isc_info_max_memory
isc_info_window_turns = _k.isc_info_window_turns
isc_info_license = _k.isc_info_license
isc_info_allocation = _k.isc_info_allocation
isc_info_attachment_id = _k.isc_info_attachment_id
isc_info_read_seq_count = _k.isc_info_read_seq_count
isc_info_read_idx_count = _k.isc_info_read_idx_count
isc_info_insert_count = _k.isc_info_insert_count
isc_info_update_count = _k.isc_info_update_count
isc_info_delete_count = _k.isc_info_delete_count
isc_info_backout_count = _k.isc_info_backout_count
isc_info_purge_count = _k.isc_info_purge_count
isc_info_expunge_count = _k.isc_info_expunge_count
isc_info_sweep_interval = _k.isc_info_sweep_interval
isc_info_ods_version = _k.isc_info_ods_version
isc_info_ods_minor_version = _k.isc_info_ods_minor_version
isc_info_no_reserve = _k.isc_info_no_reserve
isc_info_logfile = _k.isc_info_logfile
isc_info_cur_logfile_name = _k.isc_info_cur_logfile_name
isc_info_cur_log_part_offset = _k.isc_info_cur_log_part_offset
isc_info_num_wal_buffers = _k.isc_info_num_wal_buffers
isc_info_wal_buffer_size = _k.isc_info_wal_buffer_size
isc_info_wal_ckpt_length = _k.isc_info_wal_ckpt_length
isc_info_wal_cur_ckpt_interval = _k.isc_info_wal_cur_ckpt_interval
isc_info_wal_prv_ckpt_fname = _k.isc_info_wal_prv_ckpt_fname
isc_info_wal_prv_ckpt_poffset = _k.isc_info_wal_prv_ckpt_poffset
isc_info_wal_recv_ckpt_fname = _k.isc_info_wal_recv_ckpt_fname
isc_info_wal_recv_ckpt_poffset = _k.isc_info_wal_recv_ckpt_poffset
isc_info_wal_grpc_wait_usecs = _k.isc_info_wal_grpc_wait_usecs
isc_info_wal_num_io = _k.isc_info_wal_num_io
isc_info_wal_avg_io_size = _k.isc_info_wal_avg_io_size
isc_info_wal_num_commits = _k.isc_info_wal_num_commits
isc_info_wal_avg_grpc_size = _k.isc_info_wal_avg_grpc_size
isc_info_forced_writes = _k.isc_info_forced_writes
isc_info_user_names = _k.isc_info_user_names
isc_info_page_errors = _k.isc_info_page_errors
isc_info_record_errors = _k.isc_info_record_errors
isc_info_bpage_errors = _k.isc_info_bpage_errors
isc_info_dpage_errors = _k.isc_info_dpage_errors
isc_info_ipage_errors = _k.isc_info_ipage_errors
isc_info_ppage_errors = _k.isc_info_ppage_errors
isc_info_tpage_errors = _k.isc_info_tpage_errors
isc_info_set_page_buffers = _k.isc_info_set_page_buffers
# Following is a group of constants that should only be imported if the C
# portion of kinterbasdb was compiled against Interbase 6 or later.
if hasattr(_k, 'isc_info_db_sql_dialect'):
isc_info_db_sql_dialect = _k.isc_info_db_sql_dialect
# Mis-cased version of the above has now been deprecated and is maintained
# only for compatibility:
isc_info_db_SQL_dialect = _k.isc_info_db_SQL_dialect
isc_info_db_read_only = _k.isc_info_db_read_only
isc_info_db_size_in_pages = _k.isc_info_db_size_in_pages
# Only when compiled against Firebird 1.0 or later:
if hasattr(_k, 'frb_info_att_charset'):
frb_info_att_charset = _k.frb_info_att_charset
isc_info_db_class = _k.isc_info_db_class
isc_info_firebird_version = _k.isc_info_firebird_version
isc_info_oldest_transaction = _k.isc_info_oldest_transaction
isc_info_oldest_active = _k.isc_info_oldest_active
isc_info_oldest_snapshot = _k.isc_info_oldest_snapshot
isc_info_next_transaction = _k.isc_info_next_transaction
isc_info_db_provider = _k.isc_info_db_provider
# Only when compiled against Firebird 1.5 or later:
if hasattr(_k, 'isc_info_active_transactions'):
isc_info_active_transactions = _k.isc_info_active_transactions
##########################################
## 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
def init(type_conv=1):
global _initialized, _MINIMAL_TYPE_TRANS_TYPES, \
_NORMAL_TYPE_TRANS_IN, _NORMAL_TYPE_TRANS_OUT
if _initialized:
raise ProgrammingError('Cannot initialize module more than once.')
globalz = globals()
if not isinstance(type_conv, types.IntType):
typeConvModule = type_conv
else:
typeConvOptions = {
0: 'typeconv_naked',
1: 'typeconv_backcompat', # the default
100: 'typeconv_23plus',
}
chosenTypeConvModuleName = typeConvOptions[type_conv]
typeConvModule = __import__('kinterbasdb.' + chosenTypeConvModuleName,
globalz, locals(), (chosenTypeConvModuleName,)
)
if type_conv == 100:
_MINIMAL_TYPE_TRANS_TYPES = _MINIMAL_TYPE_TRANS_TYPES + ('TEXT_UNICODE',)
for name in BASELINE_TYPE_TRANSLATION_FACILITIES:
# If the global context already has an entry for the name we're about
# to load, don't overwrite the object, but hijack its implementation
# (func_code) and perceived context (func_globals) instead.
# The fact that the function object is *modifed* rather than replaced
# is crucial to the preservation of compatibility with the
# 'from kinterbasdb import *' form of importation.
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
if not globalz.has_key(name):
globalz[name] = typeConvModuleMember
else:
# fakeFunc was originally created by the
# 'for _requiredDBAPIConstuctorName in ...: exec ...'
# loop at the module level.
fakeFunc = globalz[name]
realFunc = typeConvModuleMember
fakeFunc.func_code = realFunc.func_code
fakeFunc.func_globals.update(realFunc.func_globals)
# 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 == 100:
_NORMAL_TYPE_TRANS_IN['TEXT_UNICODE'] = unicode_conv_in
_NORMAL_TYPE_TRANS_OUT['TEXT_UNICODE'] = unicode_conv_out
_initialized = True
def _ensureInitialized():
if not _initialized:
init()
# We now know the module has been initialized; replace this function's
# implementation with a no-op.
def noop(): pass
_ensureInitialized.func_code = noop.func_code
for _requiredDBAPIConstuctorName in (
'Date', 'Time', 'Timestamp',
'DateFromTicks', 'TimeFromTicks', 'TimestampFromTicks',
):
# The initialization of type converters (in function init) will replace
# the dummy implementations created here with versions that needn't check
# whether the module has been "initialized".
#
# Note that only the function *implementations* (func_code) created here
# will be replaced; the functions objects themselves will not be replaced.
# This is crucial to the preservation of compatibility with the
# 'from kinterbasdb import *' form of importation.
exec '''\
def %s(*args, **kwargs):
_ensureInitialized()
return globals()['%s'](*args, **kwargs)
''' % (_requiredDBAPIConstuctorName, _requiredDBAPIConstuctorName)
###################################################
## 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:
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(types.StringType, types.UnicodeType)
BINARY = DBAPITypeObject(types.StringType, types.BufferType)
NUMBER = DBAPITypeObject(types.IntType, types.LongType, types.FloatType)
# 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 ##
############################################
###################################################################
## GLOBAL VARIABLES (IN THE TRADITIONAL SENSE): BEGIN ##
###################################################################
if _EVENT_HANDLING_SUPPORTED:
# Use this lock to enforce the current one-event-waiting-thread-per-process
# limitation (which is a limitation in the database client library, not in
# kinterbasdb):
if _threads_supported:
_eventLock = thread.allocate_lock()
###################################################################
## GLOBAL VARIABLES (IN THE TRADITIONAL SENSE): 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.
C_con = _k.create_database(*args)
return Connection(_ConnectionObject=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 function).
"""
_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 ##
##########################################
class Connection:
"""
Represents a connection between the database client (the Python process)
and the database server.
The basic behavior of this class is documented by the Python DB API
Specification 2.0; this docstring covers only some extensions. Also see
the KInterbasDB Usage Guide (docs/usage.html).
Attributes:
$dialect (read-only):
The Interbase SQL dialect of the connection. One of:
1 for Interbase < 6.0
2 for "migration mode"
3 for Interbase >= 6.0 and Firebird (the default)
$precision_mode (read/write): (DEPRECATED)
precision_mode is deprecated in favor of dynamic type translation
(see the [set|get]_type_trans_[in|out] methods, and the Usage Guide).
---
precision_mode 0 (the default) represents database fixed point values
(NUMERIC/DECIMAL fields) as Python floats, potentially losing precision.
precision_mode 1 represents database fixed point values as scaled
Python integers, preserving precision.
For more information, see the KInterbasDB Usage Guide.
$server_version (read-only):
The version string of the database server to which this connection
is connected.
$default_tpb (read/write):
The transaction parameter buffer (TPB) that will be used by default
for new transactions opened in the context of this connection.
For more information, see the KInterbasDB Usage Guide.
"""
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 attach_db. (The create_database function uses this
# facility, for example.)
if keywords_args.has_key('_ConnectionObject'):
self._C_con = keywords_args['_ConnectionObject']
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:
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]}
# Pre-render the requisite buffers (plus the dialect), then send
# them down to the C level. _k.attach_db() will give us a C-level
# connection structure (self._C_con, of type ConnectionType) in
# return. self will then spend the rest of its insignificant life
# serving as a proxy for _C_con.
(dsn, dpb, dialect) = self._build_connect_structures(**source_dict)
self._C_con = _k.attach_db(dsn, dpb, dialect)
self._normalize_type_trans()
# 2003.03.30: Moved precision_mode up to the Python level (it's deprecated).
self._precision_mode = 0
# 2003.10.06:
# This list will contain weak references to cursors created on this
# connection. When this connection is close()d explicitly by the client
# programmer or garbage collected without having been explicitly
# close()d, it will ask its remaining cursors to close() themselves
# before the attachment to the database is severed, in order to avoid a
# situation in which the cursors need to call isc_dsql_free_statement
# but no longer have the necessary context, which is provided by their
# connection.
self._cursors = []
def _build_connect_structures(self,
dsn=None, user=None, password=None, host=None, database=None,
role=None, charset=None, dialect=0
):
# Build <<DSN>>:begin:
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
assert dsn, 'Internal error in _build_connect_structures DSN preparation.'
# Build <<DSN>>:end
# Build <<DPB>>:begin:
# Build the database parameter buffer. $dpb is a list of raw strings
# that will be rolled up into a single raw string and passed,
# ultimately, to the C function isc_attach_database as the 'dpb'
# argument.
# Start with requisite DPB boilerplate, a single byte that informs the
# database API what version of DPB it's dealing with:
dpb = [ struct.pack('c', _k.isc_dpb_version1) ]
def add_str(code_as_byte, 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 byte code telling the purpose of the upcoming string
# - a byte telling the length of the upcoming string
# - the string itself
# See IB 6 API guide page 44 for documentation of WTF is going on here.
s_len = len(s)
if s_len >= 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' % s_len # like 'cc50s' for a 50-byte string
dpb.append( struct.pack(format, code_as_byte, chr(s_len), s) )
if user:
add_str(_k.isc_dpb_user_name, user)
if password:
add_str(_k.isc_dpb_password, password)
if role:
add_str(_k.isc_dpb_sql_role_name, role)
self.charset = (charset and charset) or None
if charset:
add_str(_k.isc_dpb_lc_ctype, charset)
# Roll dpb up into a single raw string (That's "buffer" to you, sonny.)
dpb = ''.join(dpb)
# Build <<DPB>>:end
# Leave dialect alone; the C code will validate it.
return (dsn, dpb, dialect)
def __del__(self):
# This method should not call close().
self._forcibly_close_cursors()
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.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.
"""
if self.group is not None:
self.group.begin()
return
if tpb is None:
_k.begin(self._C_con, self.default_tpb)
else:
tpb = _validateTPB(tpb) # 2004.04.19
_k.begin(self._C_con, 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.
"""
if self.group is not None:
self.group.prepare()
return
_k.prepare(self._C_con)
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.
"""
if self.group is not None:
self.group.commit(retaining=retaining)
return
_k.commit(self._C_con, 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')
"""
self.execute_immediate('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.
"""
if savepoint is None:
if self.group is not None:
self.group.rollback(retaining=retaining)
return
_k.rollback(self._C_con, retaining)
else:
self.execute_immediate('ROLLBACK TO ' + 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.
"""
self._ensure_transaction()
_k.execute_immediate(self._C_con, 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.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 cursor(self):
"""
Creates new cursor that operates within the context of this connection.
"""
cur = Cursor(self)
self._cursors.append( weakref.ref(cur) )
return cur
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._forcibly_close_cursors()
self._close_physical_connection(raiseExceptionOnError=True)
def _forcibly_close_cursors(self):
# For an explanation of this method's purpose, see the comment in the
# constructor regarding self._cursors.
if hasattr(self, '_cursors'):
for cur_weakref in self._cursors:
cur = cur_weakref()
if cur is not None and _k and _k.is_purportedly_open(cur._C_cursor):
cur.close()
del self._cursors
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.
if hasattr(self, '_C_con'):
if _k and _k.is_purportedly_open(self._C_con):
_k.close_connection(self._C_con)
self._C_con = _k.null_connection
elif raiseExceptionOnError:
raise ProgrammingError('Connection is already closed.')
def _has_db_handle(self):
return self._C_con != _k.null_connection
def _has_transaction(self):
# Does this connection currently have an active transaction (including
# a distributed transaction)?
return _k.has_transaction(self._C_con)
def _ensure_transaction(self):
if self._has_transaction():
return
if self.group is None:
self.begin()
else:
self.group.begin()
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 not trans_dict.has_key(type_name):
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)
trans_return_types = _make_output_translator_return_type_dict_from_trans_dict(trans_dict)
return _k.set_con_type_trans_out(self._C_con, trans_dict, trans_return_types)
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_con_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_con_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_con_type_trans_in(self._C_con)
# Exclude event handling methods if support for them is not compiled into
# the underlying C module:
if _EVENT_HANDLING_SUPPORTED:
def event_conduit(self, event_names):
if not _threads_supported:
raise NotSupportedError("This Python installation is not"
" compiled with thread support, so kinterbasdb's event"
" support is unavailable."
)
if self._C_con is _k.null_connection:
raise ProgrammingError("Cannot open event conduit on closed connection.")
# Only one event-waiting-thread per process is supported by the DB
# client library; kinterbasdb reflects this.
# Try to acquire the single thread lock that serializes all
# EventConduits. If that acquisition attempt is not *immediately*
# successful, it must be because there's already an active
# EventConduit.
if _eventLock.acquire(0) == 0:
raise NotSupportedError("This version of kinterbasdb does not"
" support listening for events with more than one"
" EventConduit per process. Within this process, there is"
" already an active EventConduit; you must close() it"
" before creating a new one."
)
try:
if hasattr(self, '_hasActiveConduit'):
if self._hasActiveConduit:
raise ProgrammingError("Only one EventConduit can be"
" allocated per Connection; one is already"
" allocated for this connection. Use the"
" EventConduit.close() method to release the old"
" conduit before allocating another."
)
conduit = EventConduit(event_names, self)
self._hasActiveConduit = True
return conduit
except:
# Notice that in the non-exceptional case, the _eventLock is
# *not* released until the Connection._event_conduit_released()
# method is called by the active EventConduit as it "dies".
_eventLock.release()
raise
def _event_conduit_released(self, conduit):
# The event conduit associated with this connection will call this
# method when it ceases to be active.
self._hasActiveConduit = False
_eventLock.release()
def __getattr__(self, attr):
if attr == "dialect":
return _k.get_dialect(self._C_con)
elif attr == "precision_mode":
# 2003.04.02: postpone this warning until a later version:
#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
elif attr == "server_version":
rawVersion = self.database_info(isc_info_version, 's')
# As defined by the IB 6 API Guide, the first byte is the constant
# 1; the second byte contains the size of the server_version string
# in bytes.
return rawVersion[2:2 + raw_byte_to_int(rawVersion[1])]
elif attr == "group":
return _k.get_group(self._C_con)
else:
try:
return self.__dict__[attr]
except KeyError:
raise AttributeError(
"Connection instance has no attribute '%s'" % attr
)
def __setattr__(self, attr, value):
if attr == "dialect":
_k.set_dialect(self._C_con, value)
elif attr == "precision_mode":
# 2003.04.02: postpone this warning until a later version:
#warnings.warn(
# 'precision_mode is deprecated in favor of dynamic type'
# ' translation (see the [set|get]_type_trans_[in|out] methods).',
# DeprecationWarning
# )
if value not in (0,1):
raise ValueError('precision_mode must be 0 or 1')
# Preserve the previous DTT settings 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 == 0: # imprecise:
trans_in['FIXED'] = fixed_conv_in_imprecise
trans_out['FIXED'] = fixed_conv_out_imprecise
else: # precise:
trans_in['FIXED'] = fixed_conv_in_precise
trans_out['FIXED'] = fixed_conv_out_precise
self.set_type_trans_in(trans_in)
self.set_type_trans_out(trans_out)
self._precision_mode = value
elif attr == "server_version":
raise AttributeError("server_version is a read-only attribute")
elif attr == "group":
raise AttributeError("group is a read-only attribute")
elif attr == "charset":
# Allow the "charset" attribute to be set the first time (by the
# constructor), but never again.
if hasattr(self, "charset"):
raise AttributeError("charset is a read-only attribute")
else:
self.__dict__[attr] = value
elif attr == "default_tpb": # 2004.04.19
self.__dict__["default_tpb"] = _validateTPB(value)
else:
self.__dict__[attr] = value
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.
if group is not None:
assert _k.get_group(self._C_con) is None
# Unless the group is being cleared (set to None), pass a *WEAK*
# reference down to the C level (otherwise, even the cyclic garbage
# collector can't collect ConnectionGroups or their Connections because
# the Connections' references are held at the C level, not the Python
# level).
if group is None:
_k.set_group(self._C_con, None)
else:
_k.set_group(self._C_con, weakref.proxy(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)
class ConnectionGroup: # Added 2003.04.27 to support distributed transactions.
# XXX: Discuss the (lack of) threadsafety of ConnectionGroup in the docs.
# 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.')
### 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 _k.DIST_TRANS_MAX_DATABASES members:
if self.count() > _k.DIST_TRANS_MAX_DATABASES - 1:
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.'
% (_k.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.')
# The following assertion was invalidated by the introduction of weak refs:
#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._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._trans_handle, 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._trans_handle, retaining)
self._trans_handle = None
# Exclude EventConduit if support for it is not compiled into the underlying C
# library:
if _EVENT_HANDLING_SUPPORTED:
class EventConduit:
def __init__(self, event_names, connection):
"""
Parameters:
$event_names: a sequence of event names (strings) for which this
conduit will wait when the wait() method is called.
$connection: the kinterbasdb.Connection with which this conduit is
to be associated.
"""
_ensureInitialized()
if isinstance(event_names, types.StringType):
raise ProgrammingError("event_names must be a sequence of"
" strings, but not a string itself."
)
if len(event_names) == 0:
raise ProgrammingError("Can't wait for zero events.")
if len(event_names) > _k.MAX_EVENT_NAMES:
raise ProgrammingError("The database engine is limited to"
" waiting for %d or fewer events at a time."
% _k.MAX_EVENT_NAMES
)
if 0 != len([n for n in event_names if not isinstance(n, types.StringType)]):
raise ProgrammingError("All event names must be strings.")
self._con = connection
self._C_conduit = _k.event_conduit_new(
event_names, connection._C_con
)
def __del__(self):
self.close()
def wait(self, timeout=0.0):
"""
Waits for the occurrence of one or more of the events whose names
were supplied in constructor parameter $event_names.
Parameters:
$timeout is a float indicating the number of seconds to wait
before timing out, or 0.0 (the default) to wait infinitely.
Returns:
A dictionary that maps (event name -> occurence count), or None
if the wait timed out.
"""
self._requireValidState()
return _k.event_conduit_wait(self._C_conduit, timeout)
def flush(self):
"""
After the first wait() call, event notifications continue to
accumulate asynchronously within the conduit until the conduit is
close()d, regardless of whether the Python programmer continues to
call wait() to receive those notifications.
This method allows the Python programmer to manually clear any
event notifications that have queued up since the last wait() call.
Returns:
The number of event notifications that were flushed from the queue.
"""
self._requireValidState()
return _k.event_conduit_flush_queue(self._C_conduit)
def close(self):
"""
Cancels the request for this conduit to be informed of events,
clearing the way for another event conduit to register to be
informed of events (via the Connection.event_conduit() method).
After this method has been called, this EventConduit object
is useless, and should be discarded.
"""
try:
# Must not assume that self._C_conduit is present, because the
# event_conduit_new call in the constructor may have failed:
if hasattr(self, '_C_conduit'):
_k.event_conduit_cancel(self._C_conduit)
del self._C_conduit
finally:
# Inform the Connection with which this Conduit is associated that
# this Conduit is no longer "active".
if hasattr(self, '_con'):
self._con._event_conduit_released(self)
del self._con
def _requireValidState(self):
if not hasattr(self, '_C_conduit'):
raise ProgrammingError("This EventConduit has been close()d;"
" it can no longer be used."
)
if not hasattr(self, '_con') or self._con._C_con is _k.null_connection:
raise ProgrammingError("The Connection associated with this"
" EventConduit has been closed; this conduit can no longer"
" be used."
)
class Cursor:
"""
Represents a database cursor that operates within the context of a Connection.
Cursors are typically used to send SQL statements to the database (via one
of the 'execute*' methods) and to retrieve the results of those statements
(via one of the 'fetch*' methods).
The behavior of this class is further documented by the Python DB API
Specification 2.0.
Attribute and method notes:
$description:
kinterbasdb makes ABSOLUTELY NO GUARANTEES about the description attribute
of a cursor except those required by the Python Database API Specification
2.0 (that is, description is either None or a sequence of 7-item sequences).
Therefore, client programmers should NOT rely on description being an
instance of a particular class or type.
$rowcount:
The rowcount attribute is defined only in order to conform to the Python
Database API Specification 2.0.
The value of the rowcount attribute is initially -1, and it never changes,
because the Interbase/Firebird C API does not support the determination of
the number of rows affected by an executed statement.
$fetch* methods:
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.
$arraysize:
The arraysize attribute is defined only in order to conform to the Python
Database API Specification 2.0.
The Interbase/Firebird C API does not provide a facility for bulk fetch,
so the value of the arraysize attribute does not affect perfomance at all.
The Python DB API specification still requires that arraysize be present,
and that the fetchmany() method take its value into account if fetchmany()'s
optional $size parameter is not specified.
"""
def __init__(self, _con):
_ensureInitialized()
# The instance of Python class Connection that represents the database
# connection within the context of which this cursor operates:
self._con = weakref.proxy(_con) # 2003.10.27: Switched to weak ref.
# The instance of C type CursorType that represents this cursor in _k:
self._C_cursor = _k.cursor(self._con._C_con)
# cursor attributes required by the Python DB API 2.0:
self.description = None
self.arraysize = 1
def __getattr__(self, attr):
# The read-only 'connection' attribute is one of the "Optional DB API
# Extensions" documented in PEP-249.
if attr == 'connection':
return self._con
elif attr == 'name':
return _k.get_cursor_name(self._C_cursor)
elif attr == 'rowcount':
return _k.get_rowcount(self._C_cursor)
else:
try:
return self.__dict__[attr]
except KeyError:
raise AttributeError(
"Cursor instance has no attribute '%s'" % attr
)
def __setattr__(self, attr, value):
# The read-only 'connection' attribute is one of the "Optional DB API
# Extensions" documented in PEP-249.
if attr == 'connection':
raise AttributeError("connection is a read-only attribute")
elif attr == 'name':
_k.set_cursor_name(self._C_cursor, value)
elif attr == 'rowcount':
raise AttributeError("rowcount is a read-only attribute")
else:
self.__dict__[attr] = value
def __iter__(self):
"The default iterator returns sequences, not mappings."
return self.iter()
def iter(self):
return iter(self.fetchone, None)
def itermap(self):
"""
Returns an iterator of (field name -> field value) mappings for the
remaining rows available from this cursor.
"""
return iter(self.fetchonemap, None)
def setinputsizes(self, sizes):
"""
Defined for compatibility with the DB API specification, but currently
does nothing.
"""
pass
def setoutputsize(self, size, column=None):
"""
Defined for compatibility with the DB API specification, but currently
does nothing.
"""
pass
def execute(self, sql, params=()):
"""
The behavior of this method is explained by the Python DB API
Specification 2.0.
"""
self._ensure_transaction()
# If a non-virtual rowcount has been set (an attribute that'll take
# precedence over the __getattr__-based rowcount), delete it before
# executing another statement.
# For an explanation of this behavior, see comments in the executemany
# method.
if self.__dict__.has_key('rowcount'):
del self.rowcount
self.description = _k.execute(self._C_cursor, sql, params)
# Note that this method does not return anything; use the fetch* methods
# to retrieve the results of the just-executed SQL statement.
def executemany(self, sql, manySetsOfParameters):
"""
The behavior of this method is explained by the Python DB API
Specification 2.0.
"""
self._ensure_transaction()
totalRowcount = 0
for setOfParameters in manySetsOfParameters:
self.description = _k.execute(self._C_cursor, sql, setOfParameters)
totalRowcount += self.rowcount
# In order to force cur.rowcount to return the total rowcount of the
# executemany call rather than the rowcount of only the last execute
# call, store the total rowcount as an attribute that'll take precedence
# over the __getattr__-based rowcount.
# Any new execute call will delete this non-virtual rowcount figure.
self.__dict__['rowcount'] = totalRowcount
def _ensure_transaction(self):
# Ensure that the connection associated with this cursor has an active
# transaction.
self._con._ensure_transaction()
def set_type_trans_out(self, trans_dict):
_trans_require_dict(trans_dict)
trans_return_types = _make_output_translator_return_type_dict_from_trans_dict(trans_dict)
return _k.set_cur_type_trans_out(self._C_cursor, trans_dict, trans_return_types)
def get_type_trans_out(self):
return _k.get_cur_type_trans_out(self._C_cursor)
def set_type_trans_in(self, trans_dict):
_trans_require_dict(trans_dict)
return _k.set_cur_type_trans_in(self._C_cursor, trans_dict)
def get_type_trans_in(self):
return _k.get_cur_type_trans_in(self._C_cursor)
# The next two methods are used by the other fetch methods to retrieve an
# individual row as either a sequence (_fetch) or a mapping (_fetchmap).
def _fetch(self):
row = _k.fetch(self._C_cursor)
return row or None
def _fetchmap(self):
row = self._fetch()
if not row:
return None
return _RowMapping(self.description, row)
# Generic fetch(one|many|all) methods parameterized by fetchMethod so that
# their logical structure can be reused for both conventional sequence
# fetch and mapping fetch:
def _fetchone(self, fetchMethod):
return fetchMethod()
def _fetchmany(self, size, fetchMethod):
if size is None:
size = self.arraysize
elif size <= 0:
raise ProgrammingError("The size parameter of the fetchmany or"
" fetchmanymap method (which specifies the number of rows to"
" fetch) must be greater than zero. It is an optional"
" parameter, so it can be left unspecifed, in which case it"
" will default to the value of the cursor's arraysize"
" attribute."
)
manyRows = []
i = 0
while i < size:
row = fetchMethod()
if row is None:
break
manyRows.append(row)
i += 1
return manyRows
def _fetchall(self, fetchMethod):
allRows = []
while True:
row = fetchMethod()
if row is None:
break
allRows.append(row)
return allRows
# The public fetch methods:
def fetchone(self):
"""
The behavior of this method is explained by the Python DB API
Specification 2.0.
"""
return self._fetchone(self._fetch)
def fetchonemap(self):
"""
This method is just like fetchone, except that it returns a mapping
of field name to field value, rather than a sequence.
"""
return self._fetchone(self._fetchmap)
def fetchmany(self, size=None):
"""
The behavior of this method is explained by the Python DB API
Specification 2.0.
"""
return self._fetchmany(size, self._fetch)
def fetchmanymap(self, size=None):
"""
This method is just like fetchmany, except that it returns a sequence
of mappings of field name to field value, rather than a sequence of
sequences.
"""
return self._fetchmany(size, self._fetchmap)
def fetchall(self):
"""
The behavior of this method is explained by the Python DB API
Specification 2.0.
"""
return self._fetchall(self._fetch)
def fetchallmap(self):
"""
This method is just like fetchall, except that it returns a sequence
of mappings of field name to field value, rather than a sequence of
sequences.
"""
return self._fetchall(self._fetchmap)
def close(self):
"""
The behavior of this method is explained by the Python DB API
Specification 2.0.
"""
_k.close_cursor(self._C_cursor)
def callproc(self, procname, params=()):
"""
The behavior of this method is explained by the Python DB API
Specification 2.0.
"""
sql = 'EXECUTE PROCEDURE %s ' % procname
if params:
# Add a series of N comma-delimited question marks, where
# N = len(params).
sql += ','.join( ('?',) * len(params) )
self.execute(sql, params)
# The database engine doesn't support input/output parameters or
# in-place memory-modified output parameters (it's like Python in this
# regard), so return the input parameter sequence unmodified.
# With this database engine, it's kind of silly to return anything from
# this method, but the DB API Spec requires it.
# To retrieve the *results* of the procedure call, use the fetch*
# methods, as specified by the DB API Spec.
return params
##########################################
## PUBLIC CLASSES: END ##
##########################################
class _RowMapping:
"""
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 fields.has_key(fieldName):
return fields[fieldName]
else:
if fieldName.startswith('"') and fieldName.endswith('"'):
# Quoted name; leave the case of the field name untouched, but
# strip the quotes.
fieldNameNormalized = fieldName[1:-1]
else:
# Everything else is normalized to uppercase to support
# case-insensitive lookup.
fieldNameNormalized = fieldName.upper()
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()]
if sys.version_info >= (2,2):
import _py21incompat
_py21incompat.init(globals())
iterkeys = _py21incompat._RowMapping__iterkeys
__iter__ = iterkeys
itervalues = _py21incompat._RowMapping__itervalues
iteritems = _py21incompat._RowMapping__iteritems
def _trans_require_dict(obj):
if not isinstance(obj, types.DictType):
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))
)
)
# 2003.10.16:
_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):
# 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, trans_func) in trans_dict.items():
if trans_func 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 = trans_func(sample_arg)
return_type = type(return_val)
trans_return_types[trans_key] = return_type
return trans_return_types
# 2004.04.07: A 'isinstance(x, basestring)' predicate compatible with < 2.3.
if sys.version_info < (2,3):
def _is_basestring(x):
return isinstance(x, types.StringType) or isinstance(x, types.UnicodeType)
else:
def _is_basestring(x):
return isinstance(x, basestring)
# 2004.04.19:
def _validateTPB(tpb):
if not (isinstance(tpb, types.StringType) 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 (_k.isc_tpb_version3, ..., _k.isc_tpb_versionN):
# tpb = _k.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] != _k.isc_tpb_version3:
tpb = _k.isc_tpb_version3 + tpb
return tpb
_DATABASE_INFO__KNOWN_LOW_LEVEL_EXCEPTIONS = ( # Added 2004.12.12
isc_info_user_names,
)
|