1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632
|
<html>
<head>
<title>KInterbasDB Usage Guide</title>
<link rel="stylesheet" href="global.css" type="text/css">
</head>
<body>
<a href="index.html">Overall Table of Contents</a>
<hr>
<a name="top"><h1 class="compactHeading">KInterbasDB Usage Guide</h1></a>
<a name="toc"><h3>Contents</h3></a>
<ul>
<li><a href="#introduction">Introduction</a>
<br><br>
</li>
<li><a href="#db_api_compliance">Python Database API 2.0 Compliance</a>
<ul>
<li><a href="#db_api_incompatibilities">Incompatibilities</a></li>
<li><a href="#db_api_optional_unsupported">Unsupported Optional Features</a></li>
<li><a href="#db_api_optional_nominally_supported">Nominally Supported Optional Features</a></li>
<li><a href="#db_api_extensions_and_caveats">Extensions and Caveats</a></li>
</ul>
<br>
</li>
<li><a href="#tutorial">Brief Tutorial</a>
<ul>
<li><a href="#tutorial_connect">Connecting to a Database</a></li>
<li><a href="#tutorial_execute_sql">Executing SQL Statements (and Retrieving Results)</a></li>
<li><a href="#tutorial_stored_procedures">Calling Stored Procedures</a></li>
</ul>
<br>
</li>
<li><a href="#adv">Native Database Engine Features and Extensions Beyond the Python DB API</a>
<ul>
<li><a href="#adv_db_creation_deletion">Programmatic Database Creation and Deletion</a></li>
<li><a href="#adv_event">Database Event Notification</a></li>
<li><a href="#adv_trans_control">Advanced Transaction Control</a>
<ul>
<li><a href="#adv_trans_control_parameters">Transaction Parameters</a></li>
<li><a href="#adv_trans_control_retaining">Retaining Operations</a></li>
<li><a href="#adv_trans_control_savepoints">Savepoints</a></li>
<li><a href="#adv_trans_control_distributed">Distributed Transactions</a></li>
</ul>
</li>
<li><a href="#adv_param_conv">Parameter Conversion</a>
<ul>
<li><a href="#adv_param_conv_implicit_from_string">Implicit Conversion of Input Parameters from Strings</a></li>
<li><a href="#adv_param_conv_dynamic_type_translation">Dynamic Type Translation</a></li>
<li><a href="#adv_param_conv_database_arrays">Database Arrays</a></li>
</ul>
</li>
<li><a href="#adv_named_cursors">Named Cursors</a></li>
<li><a href="#adv_prog_maint">Programmatic Server, Database, and User Maintenance</a>
<ul>
<li><a href="#adv_prog_maint_servapi">Services API</a>
<ul>
<li><a href="#adv_prog_maint_servapi_connect">Establishing Services API Connections</a></li>
<li><a href="#adv_prog_maint_servapi_server_config">Querying Server Configuration and Activity Levels</a></li>
<li><a href="#adv_prog_maint_servapi_database_stats">Querying Database Statistics</a></li>
<li><a href="#adv_prog_maint_servapi_backup_restore">Backup and Restoration</a></li>
<li><a href="#adv_prog_maint_servapi_database_maint">Controlling Database Operating Modes, Sweeps, and Repair</a></li>
<li><a href="#adv_prog_maint_servapi_users">User Maintenance</a></li>
</ul>
</li>
<li><a href="#adv_prog_maint_database_info">The <code>database_info</code> Method</a></li>
</ul>
</li>
</ul>
<br>
</li>
<li><a href="#faq_fep">Frequently Asked Questions and Frequently Encountered Pitfalls</a>
<ul>
<li><a href="#faq_fep_result_set_fields_by_name">Refer to Result Row Fields by Name Rather than Index</a></li>
<li><a href="#faq_fep_fixed_point_precise">Precise Fixed Point (<code>NUMERIC</code>/<code>DECIMAL</code>) Handling</a></li>
<li><a href="#faq_fep_datetime">Dates and Times: egenix <code>mx.DateTime</code> vs. Python 2.3+ standard library <code>datetime</code></a></li>
<li><a href="#faq_fep_unicode">Unicode Fields and KInterbasDB</a></li>
<li><a href="#faq_fep_embedded_using_with">Using KInterbasDB with Embedded Firebird</a></li>
<li><a href="#faq_fep_zope_using_with">Using KInterbasDB with Zope</a></li>
<li><a href="#faq_fep_services_api_classic_embedded">Services API on the Classic and Embedded Server Architectures</a></li>
</ul>
<br>
</li>
<li><a href="#references">References (external links)</a></li>
<li><a href="#feedback">Feedback</a><br><br></li>
</ul>
<hr>
<a name="introduction">
<span style="font-size: 175%; font-weight: bold;">Introduction</span>
<span style="font-size: 90%; text-decoration: line-through;">(Propaganda)</span>
</a>
<p class="textParagraph" style="margin-top: 1em;">
The <a href="http://firebirdsql.org">Firebird</a> relational database engine
has a large feature set,
conforms closely to SQL standards,
and is flexible enough to operate either as a standalone server or
as an embedded library on diverse platforms.
In spite of this versatility, the database is exceptionally easy to
use--almost self-managing.
</p>
<p class="textParagraph" style="margin-bottom: 3px;">
The <a href="http://python.org">Python</a> programming language
supports numerous paradigms,
is suitable for constructing both very small and very large programs,
and integrates well with native C and C++ libraries.
Despite the versatility of the language, well written Python code achieves an
almost astonishing lucidity that has led some to call the language
"executable pseudocode".
Noted author and teacher
<a href="http://www.bruceeckel.com">Bruce Eckel</a> has
<a href="http://www.ddj.com/documents/s=876/ddj0050e/0050e.htm">praised</a>
Python as
</p>
<blockquote style="margin-top: 0px;">
"the most efficient language I've ever used. It's 10 times better than any
of the other tools I have used. It's free, it's object-oriented, it adapts
to everything, it runs on everything. There is almost an indescribable,
'quality without a name' attraction on my part."
</blockquote>
<p class="textParagraph">
These two top-flight software tools intersect in a library named KInterbasDB.
KInterbasDB implements Python's standard
<a href="Python-DB-API-2.0.html">Database API 2.0</a>,
but also extends far beyond, to cover Firebird's entire native client API.
KInterbasDB strives to deliver the power of Firebird into the hands of the
Python programmer without compromising the qualities of either tool.
</p>
<p class="textParagraph">
This Usage Guide is not a tutorial on Python, SQL, or Firebird; rather, it
is a topical presentation of KInterbasDB's feature set, with example code
to demonstrate basic usage patterns.
This guide is meant to be consumed in conjunction with the
<a href="Python-DB-API-2.0.html">Python Database API Specification</a>
and the
<a href="#ref_fb_docs_directory">Firebird documentation</a>, especially the
professional, seven-volume
<a href="#ref_ib6_docs">manual</a>
for Firebird's commercial ancestor, Interbase®.
</p>
<p class="textParagraph">
The <a href="#toc">table of contents</a> presents a structural overview
of this document.
</p>
<br>
<hr>
<br>
<a name="db_api_compliance"><h2>Python Database API 2.0 Compliance</h2></a>
<a name="db_api_incompatibilities"><h3>Incompatibilities</h3></a>
<ul>
<li><code>DATETIME</code> type comparison singleton
<p class="textParagraph">
KInterbasDB's deferred loading of dynamic type translators causes this
singleton to behave in violation of the standard until the
<code>kinterbasdb.init</code> function has been called (whether
explicitly or implicitly).
</p>
<p class="textParagraph">
For more information, see
<a href="#adv_param_conv_dynamic_type_translation_deferred_loading_backcompat">this section</a>.
</p>
</li>
</ul>
<a name="db_api_optional_unsupported"><h3>Unsupported Optional Features</h3></a>
<ul>
<li><code>Cursor</code> class
<ul>
<li><code>nextset</code> method<br>
<p class="textParagraph">
This method is not implemented because the database engine does
not support opening multiple result sets simultaneously
with a single cursor.
</p>
<br>
</li>
</ul>
</li>
</ul>
<a name="db_api_optional_nominally_supported"><h3>Nominally Supported Optional Features</h3></a>
<ul>
<li><code>Cursor</code> class
<ul>
<li><code>arraysize</code> attribute<br>
<p class="textParagraph">
As required by the spec, the value of this attribute
is observed with respect to the <code>fetchmany</code>
method. However, changing the value of this attribute does
not make any difference in fetch efficiency because the
database engine only supports fetching a single row at a time.
</p>
<br>
</li>
<li><code>setinputsizes</code> method<br>
<p class="textParagraph">
Although this method is present, it does nothing, as allowed
by the spec.
</p>
<br>
</li>
<li><code>setoutputsize</code> method<br>
<p class="textParagraph">
Although this method is present, it does nothing, as allowed
by the spec.
</p>
</li>
</ul>
</li>
</ul>
<a name="db_api_extensions_and_caveats"><h3>Extensions and Caveats</h3></a>
<p class="textParagraph">
KInterbasDB offers a large feature set beyond the minimal requirements of
the Python DB API.
Most of these extensions are documented in the section of this document
entitled
<a href="#adv">Native Database Engine Features and Extensions Beyond the Python DB API</a>.
</p>
<p class="textParagraph">
This section attempts to document only those features that overlap with
the DB API, or are too insignificant to warrant their own subsection
elsewhere.
</p>
<ul>
<li><code>connect</code> function
<p class="textParagraph">
This function supports the following optional keyword arguments in
addition to those required by the spec:
<ul>
<li><code>role</code> -
for connecting to a database with a specific SQL role
(see page 92 of the
<a href="#ref_ib6_docs">Interbase® 6 Operations Guide</a>
for a discussion of Interbase® roles).
<p class="textParagraph" style="margin-bottom: 0px;">
Example:
</p>
<pre style="margin-top: 0px;">
kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'host:/path/database.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'limited_user'</FONT>,
password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>, <strong>role</strong>=<FONT COLOR="#8f8c47">'MORE_POWERFUL_ROLE'</FONT>)
</pre>
</li>
<li><code>charset</code> -
for explicitly specifying the character set of the connection.
See page 221 of the
<a href="#ref_ib6_docs">Interbase® 6 Data Definition Guide</a>
for a list of available character sets, and
<a href="#faq_fep_unicode">this FAQ</a>
for information on handling extended character sets with KInterbasDB.
<p class="textParagraph" style="margin-bottom: 0px;">
Example:
</p>
<pre style="margin-top: 0px;">
kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'host:/path/database.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>,
password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>, <strong>charset</strong><FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'UNICODE_FSS'</FONT>)
</pre>
</li>
<li><code>dialect</code> -
for explicitly specifying the SQL dialect of the connection.
<p class="textParagraph">
In KInterbasDB 2.x, the default dialect was <code>1</code>
(the compatibility dialect for Interbase® 5.5 and earlier).
In KInterbasDB 3.x, the default dialect is <code>3</code>
(the most featureful dialect, ideal for Interbase® 6.0+
and Firebird).
If you want to connect to Interbase® 5.5 or earlier, you must
explicitly set this argument's value to <code>1</code>.
Dialect <code>2</code> is a transitional dialect that is
normally used only during ports from IB < 6 to IB >= 6 or
Firebird.
</p>
<p class="textParagraph" style="margin-bottom: 0px;">
Example:
</p>
<pre style="margin-top: 0px;">
kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'host:/path/database.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>,
password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>, <strong>dialect</strong><FONT COLOR="#7d0000">=</FONT><FONT COLOR="#666600">1</FONT>)
</pre>
</li>
</ul>
</li>
<li style="margin-top: 1em;"><code>Connection</code> class
<ul>
<li style="margin-bottom: 1em;"><code>charset</code> attribute <em>(read-only)</em><br>
<p class="textParagraph">
The character set of the connection (set via the <code>charset</code>
parameter of <code>kinterbasdb.connect</code>).
</p>
<p class="textParagraph">
See page 221 of the
<a href="#ref_ib6_docs">Interbase® 6 Data Definition Guide</a>
for a list of available character sets, and
<a href="#faq_fep_unicode">this FAQ</a>
for information on handling extended character sets with KInterbasDB.
</p>
</li>
<li style="margin-bottom: 1em;"><code>dialect</code> attribute<br>
<p class="textParagraph">
This integer attribute indicates which SQL dialect the connection
is using.
</p>
<p class="textParagraph">
You should not change a connection's dialect; instead, discard the
connection and establish a new one with the desired dialect.
</p>
<p class="textParagraph">
For more information, see the documentation of the
<code>dialect</code> argument of the
<code>connect</code> function.
</p>
</li>
<li><code>server_version</code> attribute <em>(read-only)</em><br>
<p class="textParagraph">
The version string of the database server
to which this connection is connected.
</p>
<p class="textParagraph">
For example, a connection to Firebird 1.0 on Windows has the
following <code>server_version</code>:<br>
<code>WI-V6.2.794 Firebird 1.0</code>
</p>
<br>
</li>
<li><code>execute_immediate</code> method<br>
<p class="textParagraph">
Executes a statement without caching its prepared form. The statement
must <em>not</em> be of a type that returns a result set.
</p>
<p class="textParagraph">
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 <code>cursor</code> method, then execute the statement
using one of the cursor's execute methods.
</p>
<p style="margin-bottom: 0px;">
Arguments:
</p>
<ul>
<li>
<code>sql</code> -
string containing the SQL statement to execute.<br>
</li>
</ul>
<br>
</li>
<li style="margin-bottom: 1em;">
<a name="db_api_extensions_and_caveats_precision_mode">
<code>precision_mode</code> attribute
</a><br>
<p class="textParagraph">
Although this attribute is present in KInterbasDB 3.1 and works
in a backward-compatible fashion, it is deprecated in favor of
the more general
<a href="#adv_param_conv_dynamic_type_translation">dynamic type translation</a>
feature.
</p>
</li>
<li><code>commit</code> and <code>rollback</code> methods<br>
<p class="textParagraph">
The <code>commit</code> and <code>rollback</code> methods
accept an optional boolean parameter <code>retaining</code>
(default <code>False</code>) that indicates whether the transactional
context of the transaction being resolved should be recycled.
For details, see the
<a href="#adv_trans_control_retaining">Advanced Transaction Control: Retaining Operations</a>
section of this document.
</p>
<p class="textParagraph">
The <code>rollback</code> method accepts an optional string parameter
<code>savepoint</code> that causes the transaction to roll back only
as far as the designated savepoint, rather than rolling back entirely.
For details, see the
<a href="#adv_trans_control_savepoints">Advanced Transaction Control: Savepoints</a>
section of this document.
</p>
</li>
</ul>
</li>
<li style="margin-top: 1em;"><code>Cursor</code> class
<ul>
<li><code>description</code> attribute<br>
<p class="textParagraph">
KInterbasDB makes <strong>absolutely no guarantees</strong> about
<code>description</code> <strong>except</strong>
those required by the Python Database API Specification 2.0 (that
is, <code>description</code> is
either <code>None</code> or a sequence of 7-element sequences).
Therefore, client programmers should <em>not</em> rely on
<code>description</code> being an instance of a particular class or
type.
<br><br>
</p>
<p class="textParagraph">
KInterbasDB provides several named positional constants to be
used as indices into a given element of <code>description</code> .
The contents of all <code>description</code> elements are defined by
the DB API spec; these constants are provided merely for
convenience.
</p>
<pre>DESCRIPTION_NAME
DESCRIPTION_TYPE_CODE
DESCRIPTION_DISPLAY_SIZE
DESCRIPTION_INTERNAL_SIZE
DESCRIPTION_PRECISION
DESCRIPTION_SCALE
DESCRIPTION_NULL_OK</pre>
<p class="textParagraph">
Here is an example of accessing the <em>name</em> of the first
field in the <code>description</code> of cursor <code>cur</code>:
</p>
<pre class="codeBlock" style="margin-top: 0px;">nameOfFirstField <FONT COLOR="#7d0000">=</FONT> cur.description[<FONT COLOR="#666600">0</FONT>][kinterbasdb.DESCRIPTION_NAME]</pre>
<br>
</li>
<li><code>rowcount</code> attribute<br>
<p class="textParagraph">
Although KInterbasDB's <code>Cursor</code>s implement this attribute, the database
engine's own support for the determination of "rows affected"/"rows
selected" is quirky.
</p>
<p class="textParagraph">
The database engine only supports the determination of rowcount for
<code>INSERT</code>, <code>UPDATE</code>, <code>DELETE</code>, and
<code>SELECT</code> statements.
When stored procedures become involved, row count figures are usually
not available to the client.
</p>
<p class="textParagraph">
Determining rowcount for <code>SELECT</code> statements is
problematic:
the rowcount is reported as zero until at least one row has been
fetched from the result set,
and the rowcount is misreported if the result set is larger than
1302 rows. The server apparently marshals result sets internally
in batches of
1302, and will misreport the rowcount for result sets larger
than 1302 rows until the 1303rd row is fetched, result sets larger
than 2604 rows until the 2605th row is fetched, and so on,
in increments of 1302.
</p>
<p class="textParagraph">
As required by the Python DB API Spec, the rowcount attribute
"is -1 in case no executeXX() has been performed on the cursor or
the rowcount of the last operation is not determinable by the
interface".
</p>
<br>
</li>
<li><code>fetch*</code> methods<br>
<p class="textParagraph">
KInterbasDB makes <strong>absolutely no guarantees</strong>
about the return value of the
<code>fetchone</code> / <code>fetchmany</code> / <code>fetchall</code>
methods <strong>except</strong> that it is a sequence indexed by
field position.
</p>
<p class="textParagraph">
KInterbasDB makes <strong>absolutely no guarantees</strong>
about the return value of the
<code>fetchonemap</code> / <code>fetchmanymap</code> / <code>fetchallmap</code>
methods (documented below)
<strong>except</strong> that it is a mapping of field name to field
value.
</p>
<p class="textParagraph">
Therefore, client programmers should <em>not</em> rely on the return value being
an instance of a particular class or type.
</p>
<br>
</li>
<li>
<a name="db_api_extensions_and_caveats_cursor_fetchonemap">
<code>fetchonemap</code> method<br>
</a>
<p class="textParagraph">
This method is just like the standard <code>fetchone</code> method
of the DB API, except that it returns a mapping of field name to
field value, rather than a sequence.
<br><br>
</p>
</li>
<li><code>fetchmanymap</code> method<br>
<p class="textParagraph">
This method is just like the standard <code>fetchmany</code> method
of the DB API, except that it returns a sequence of mappings of
field name to field value, rather than a sequence of sequences.
<br><br>
</p>
</li>
<li><code>fetchallmap</code> method<br>
<p class="textParagraph">
This method is just like the standard <code>fetchall</code> method
of the DB API, except that it returns a sequence of mappings
of field name to field value, rather than a sequence of sequences.
<br><br>
</p>
</li>
<li><code>iter</code>/<code>itermap</code> methods<br>
<p class="textParagraph">
These methods are equivalent to the
<code>fetchall</code> and <code>fetchallmap</code> methods,
respectively, except that they return iterators rather than
materialized sequences.
</p>
<p class="textParagraph">
<code>iter</code> and <code>itermap</code> are exercised in
<a href="#tutorial_executing_example_2">this example</a>.
</p>
<br><br>
</li>
</ul>
</li>
</ul>
<hr>
<a name="tutorial"><h2>Tutorial</h2></a>
<p class="textParagraph">
This brief tutorial aims to get the reader started by
demonstrating elementary usage of KInterbasDB. It
is not a comprehensive Python Database API tutorial, nor is it
comprehensive in its coverage of anything else.
</p>
<p class="textParagraph">
The numerous advanced features of KInterbasDB are covered in
<a href="#adv">another section</a> of this document, which is not in a
tutorial format, though it is replete with examples.
</p>
<a name="tutorial_connect"><h3>Connecting to a Database</h3></a>
<a name="tutorial_connecting_example_1"><h4>Example 1</h4>
<p class="textParagraph">
A database connection is typically established with code such as this:
</p>
<pre class="codeBlock"><FONT COLOR="#0000ff">import</FONT> kinterbasdb
<FONT COLOR="#32a532"># The server is named 'bison'; the database file is at '/temp/test.db'.</FONT>
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'bison:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
<FONT COLOR="#32a532"># Or, equivalently:</FONT>
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(
host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'bison'</FONT>, database<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'/temp/test.db'</FONT>,
user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>
)
</PRE>
</pre>
<a name="tutorial_connecting_example_2"><h4>Example 2</h4></a>
<p class="textParagraph">
Suppose we want to connect to an Interbase® 5.5 server, specifying UNICODE_FSS
as the character set of the connection:
<pre class="codeBlock"><FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(
dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'bison:/temp/test.db'</FONT>,
user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>,
dialect<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#666600">1</FONT>, <FONT COLOR="#32a532"># necessary for Interbase® < 6.0</FONT>
charset<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'UNICODE_FSS'</FONT> <FONT COLOR="#32a532"># specify a character set for the connection</FONT>
)
</pre>
</p>
<br>
<a name="tutorial_execute_sql"><h3>Executing SQL Statements</h3></a>
<p class="textParagraph">
For this section, suppose we have a table defined and populated by the
following SQL code:
</p>
<pre class="codeBlock"><FONT COLOR="#0000ff">create</FONT> <FONT COLOR="#0000ff">table</FONT> people
(
name_last <FONT COLOR="#0000ff">varchar</FONT>(<FONT COLOR="#666600">20</FONT>),
age <FONT COLOR="#0000ff">integer</FONT>
);
<FONT COLOR="#0000ff">insert</FONT> <FONT COLOR="#0000ff">into</FONT> people (name_last, age) <FONT COLOR="#0000ff">values</FONT> (<FONT COLOR="#8f8c47">'Yeltsin'</FONT>, <FONT COLOR="#666600">72</FONT>);
<FONT COLOR="#0000ff">insert</FONT> <FONT COLOR="#0000ff">into</FONT> people (name_last, age) <FONT COLOR="#0000ff">values</FONT> (<FONT COLOR="#8f8c47">'Putin'</FONT>, <FONT COLOR="#666600">51</FONT>);
</pre>
<a name="tutorial_executing_example_1"><h4>Example 1</h4></a>
<p class="textParagraph">
This example shows the <em>simplest</em> way to
print the entire contents of the <code>people</code> table:
</p>
<pre class="codeBlock"><FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(
dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'bison:/temp/test.db'</FONT>,
user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>
)
<FONT COLOR="#32a532"># Get a Cursor object that operates in the context of Connection con:</FONT>
cur <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
<FONT COLOR="#32a532"># Execute the SELECT statement:</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select * from people order by age"</FONT>)
<FONT COLOR="#32a532"># Retrieve all rows as a sequence and print that sequence:</FONT>
<FONT COLOR="#0000ff">print</FONT> cur.<FONT COLOR="#000066">fetchall</FONT>()
</pre>
<p class="textParagraph">
Sample output:
</p>
<pre class="programOutputBlock">
[(<FONT COLOR="#8f8c47">'Putin'</FONT>, <FONT COLOR="#666600">51</FONT>), (<FONT COLOR="#8f8c47">'Yeltsin'</FONT>, <FONT COLOR="#666600">72</FONT>)]
</pre>
<br>
<a name="tutorial_executing_example_2"><h4>Example 2</h4></a>
<p class="textParagraph">
Here's another trivial example that demonstrates various ways of fetching a
single row at a time from a <code>SELECT</code>-cursor:
<pre class="codeBlock"><FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(
dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'bison:/temp/test.db'</FONT>,
user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>
)
cur <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
SELECT <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#8f8c47">"select name_last, age from people order by age, name_last"</FONT>
<FONT COLOR="#32a532"># 1. Iterate over the rows available from the cursor, unpacking the</FONT>
<FONT COLOR="#32a532"># resulting sequences to yield their elements (name_last, age):</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(SELECT)
<FONT COLOR="#0000ff">for</FONT> (name_last, age) <FONT COLOR="#0000ff">in</FONT> cur:
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'%s is %d years old.'</FONT> <FONT COLOR="#7d0000">%</FONT> (name_last, age)
<FONT COLOR="#32a532"># 2. Equivalently:</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(SELECT)
<FONT COLOR="#0000ff">for</FONT> row <FONT COLOR="#0000ff">in</FONT> cur:
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'%s is %d years old.'</FONT> <FONT COLOR="#7d0000">%</FONT> (row[<FONT COLOR="#666600">0</FONT>], row[<FONT COLOR="#666600">1</FONT>])
<FONT COLOR="#32a532"># 3. Using mapping-iteration rather than sequence-iteration:</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(SELECT)
<FONT COLOR="#0000ff">for</FONT> row <FONT COLOR="#0000ff">in</FONT> cur.<FONT COLOR="#000066">itermap</FONT>():
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'%(name_last)s is %(age)d years old.'</FONT> <FONT COLOR="#7d0000">%</FONT> row
<FONT COLOR="#32a532"># 4. Here's the ugly pre-iterator (i.e., Python 2.1) approach:</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(SELECT)
<FONT COLOR="#0000ff">while</FONT> <FONT COLOR="#666600">1</FONT>:
row <FONT COLOR="#7d0000">=</FONT> cur.<FONT COLOR="#000066">fetchonemap</FONT>()
<FONT COLOR="#0000ff">if</FONT> <FONT COLOR="#0000ff">not</FONT> row:
<FONT COLOR="#0000ff">break</FONT>
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'%(name_last)s is %(age)d years old.'</FONT> <FONT COLOR="#7d0000">%</FONT> row
</pre>
</p>
<p class="textParagraph">
Sample output:
</p>
<pre class="programOutputBlock">
Putin is 51 years old.
Yeltsin is 72 years old.
Putin is 51 years old.
Yeltsin is 72 years old.
Putin is 51 years old.
Yeltsin is 72 years old.
Putin is 51 years old.
Yeltsin is 72 years old.
</pre>
<br>
<a name="tutorial_executing_example_3"><h4>Example 3</h4></a>
<p class="textParagraph">
The following program is a simplistic table printer
(applied in this example to <code>people</code>):
</p>
<pre class="codeBlock"><FONT COLOR="#0000ff">import</FONT> kinterbasdb <FONT COLOR="#0000ff">as</FONT> k
TABLE_NAME <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#8f8c47">'people'</FONT>
SELECT <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#8f8c47">'select * from %s order by age, name_last'</FONT> <FONT COLOR="#7d0000">%</FONT> TABLE_NAME
con <FONT COLOR="#7d0000">=</FONT> k.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'bison:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
cur <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
cur.<FONT COLOR="#000066">execute</FONT>(SELECT)
<FONT COLOR="#32a532"># Print a header.</FONT>
<FONT COLOR="#0000ff">for</FONT> fieldDesc <FONT COLOR="#0000ff">in</FONT> cur.description:
<FONT COLOR="#0000ff">print</FONT> fieldDesc[k.DESCRIPTION_NAME].<FONT COLOR="#000066">ljust</FONT>(fieldDesc[k.DESCRIPTION_DISPLAY_SIZE]) ,
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#32a532"># Finish the header with a newline.</FONT>
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'-'</FONT> <FONT COLOR="#7d0000">*</FONT> <FONT COLOR="#666600">78</FONT>
<FONT COLOR="#32a532"># For each row, print the value of each field left-justified within</FONT>
<FONT COLOR="#32a532"># the maximum possible width of that field.</FONT>
fieldIndices <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#4343b8">range</FONT>(<FONT COLOR="#4343b8">len</FONT>(cur.description))
<FONT COLOR="#0000ff">for</FONT> row <FONT COLOR="#0000ff">in</FONT> cur:
<FONT COLOR="#0000ff">for</FONT> fieldIndex <FONT COLOR="#0000ff">in</FONT> fieldIndices:
fieldValue <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#4343b8">str</FONT>(row[fieldIndex])
fieldMaxWidth <FONT COLOR="#7d0000">=</FONT> cur.description[fieldIndex][k.DESCRIPTION_DISPLAY_SIZE]
<FONT COLOR="#0000ff">print</FONT> fieldValue.<FONT COLOR="#000066">ljust</FONT>(fieldMaxWidth) ,
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#32a532"># Finish the row with a newline.</FONT>
</pre>
<p class="textParagraph">
Sample output:
</p>
<pre class="programOutputBlock">
NAME_LAST AGE
------------------------------------------------------------------------------
Putin 51
Yeltsin 72
</pre>
<br>
<a name="tutorial_executing_example_4"><h4>Example 4</h4></a>
<p class="textParagraph">
Let's insert more people into the <code>people</code> table:
</p>
<pre class="codeBlock"><FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(
dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'bison:/temp/test.db'</FONT>,
user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>
)
cur <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
newPeople <FONT COLOR="#7d0000">=</FONT> (
(<FONT COLOR="#8f8c47">'Lebed'</FONT> , <FONT COLOR="#666600">53</FONT>),
(<FONT COLOR="#8f8c47">'Zhirinovsky'</FONT> , <FONT COLOR="#666600">57</FONT>),
)
<FONT COLOR="#0000ff">for</FONT> person <FONT COLOR="#0000ff">in</FONT> newPeople:
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"insert into people (name_last, age) values (?, ?)"</FONT>, person)
<FONT COLOR="#32a532"># The changes will not be saved unless the transaction is committed explicitly:</FONT>
con.<FONT COLOR="#000066">commit</FONT>()
</pre>
<p class="textParagraph">
Note the use of a <em>parameterized</em> SQL statement above. When dealing
with repetitive statements, this is <strong>much faster and less error-prone</strong>
than assembling each SQL statement manually.
</p>
<p class="textParagraph">It's also worth noting that in the example above,
the code:
<pre class="codeBlock" style="margin-left: 15px;"><FONT COLOR="#0000ff">for</FONT> person <FONT COLOR="#0000ff">in</FONT> newPeople:
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"insert into people (name_last, age) values (?, ?)"</FONT>, person)
</pre>
could be rewritten as:
<pre class="codeBlock" style="margin-left: 15px;">cur.<FONT COLOR="#000066">executemany</FONT>(<FONT COLOR="#8f8c47">"insert into people (name_last, age) values (?, ?)"</FONT>, newPeople)
</pre>
</p>
<p class="textParagraph" style="margin-top: 30px;">
After running Example 4, the table printer from Example 3
would print:
</p>
<pre class="programOutputBlock">
NAME_LAST AGE
------------------------------------------------------------------------------
Putin 51
Lebed 53
Zhirinovsky 57
Yeltsin 72
</pre>
<br>
<a name="tutorial_stored_procedures"><h3>Calling Stored Procedures</h3></a>
<p class="textParagraph">
Interbase® and Firebird support stored procedures written in a proprietary
procedural SQL language.
IB/FB stored procedures can have <em>input</em> parameters and/or
<em>output</em> parameters. Some databases support <em>input/output</em>
parameters, where the same parameter is used for both input and output; IB/FB
does not support this.
</p>
<p class="textParagraph">
It is important to distinguish between procedures that <em>return a result set</em>
and procedures that <em>populate and return their output parameters exactly once</em>.
Conceptually, the latter "return their output parameters" like a Python
function, whereas the former "yield result rows" like a Python generator.
</p>
<p class="textParagraph">
IB/FB's <em>server-side</em> procedural SQL syntax
makes no such distinction, but <em>client-side</em> SQL code (and C API code)
must.
A result set is retrieved from a stored procedure by
<code>SELECT</code>ing from the procedure, whereas output
parameters are retrieved with an <code>EXECUTE PROCEDURE</code>
statement.
<br><br>
</p>
<p class="textParagraph">
To <em>retrieve a result set</em> from a stored procedure with KInterbasDB,
use code such as this:
</p>
<pre class="codeBlock">cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select output1, output2 from the_proc(?, ?)"</FONT>, (input1, input2))
<FONT COLOR="#32a532"># Ordinary fetch code here, such as:</FONT>
<FONT COLOR="#0000ff">for</FONT> row <FONT COLOR="#0000ff">in</FONT> cur:
... <FONT COLOR="#32a532"># process row</FONT>
con.<FONT COLOR="#000066">commit</FONT>() <FONT COLOR="#32a532"># If the procedure had any side effects, commit them.</FONT>
</pre>
<p class="textParagraph">
To <em>execute</em> a stored procedure and <em>access its output parameters</em>,
use code such as this:
</p>
<pre class="codeBlock">cur.<FONT COLOR="#000066">callproc</FONT>(<FONT COLOR="#8f8c47">"the_proc"</FONT>, (input1, input2))
<FONT COLOR="#32a532"># If there are output parameters, retrieve them as though they were the</FONT>
<FONT COLOR="#32a532"># first row of a result set. For example:</FONT>
outputParams <FONT COLOR="#7d0000">=</FONT> cur.<FONT COLOR="#000066">fetchone</FONT>()
con.<FONT COLOR="#000066">commit</FONT>() <FONT COLOR="#32a532"># If the procedure had any side effects, commit them.</FONT>
</pre>
<p class="textParagraph">
This latter is not very elegant; it would be preferable to access the
procedure's output parameters as the return value of
<code>Cursor.callproc</code>. The Python DB API specification requires the
current behavior, however.
</p>
<br><br>
<hr>
<br>
<a name="adv">
<h2 style="margin-bottom: 25px;">Native Database Engine Features and Extensions Beyond the Python DB API</h2>
</a>
<hr>
<a name="adv_db_creation_deletion">
<h2>Programmatic Database Creation and Deletion</h2>
</a>
<p class="textParagraph">
The Firebird engine stores a database in a fairly straightforward manner:
as a single file or, if desired, as a segmented group of files.
</p>
<p class="textParagraph">
The engine supports dynamic database creation via the SQL statement
<code>CREATE DATABASE</code>, which is documented on page 49 of the
<a href="#ref_ib6_docs">Interbase® 6 Language Reference</a>.
</p>
<p class="textParagraph">
The engine also supports dropping (deleting) databases dynamically, but
dropping is a more complicated operation than creating, for several reasons:
an existing database may be in use by users other than the one who requests the
deletion, it may have supporting objects such as temporary sort files, and it may
even have dependent shadow databases. Although the database engine recognizes a
<code>DROP DATABASE</code> SQL statement, support for that statement is
limited to the <code>isql</code> command-line administration utility. However,
the engine supports the deletion of databases via an API call, which
KInterbasDB exposes to Python (see below).
</p>
<p class="textParagraph">
KInterbasDB supports dynamic database creation and deletion via the
module-level function <code>create_database</code> and the method
<code>Connection.drop_database</code>. These are documented below, then
demonstrated by a brief example.
</p>
<table border="1" class="memberDocFrame">
<tr>
<td class="memberDocHeader">
<code class="memberDocName">create_database</code>
<span class="memberDocNameCaption">(function; member of <code>kinterbasdb</code>)</span>
</td>
</tr>
<tr>
<td>
<p>
Creates a database according to the supplied <code>CREATE DATABASE</code>
SQL statement. Returns an open connection to the newly created database.
</p>
<p class="argHeader">Arguments:</p>
<ul class="argList">
<li>
<code>sql</code> -
string containing the <code>CREATE DATABASE</code> statement.<br>
<p class="textParagraph">
Note that this statement may need to include a username and password
(see the <a href="#ref_ib6_docs">IB 6 Language Reference</a> for syntax).
</p>
</li>
<li>
<code>dialect</code> <span class="memberDocArgOptTag">(optional)</span> -
the SQL dialect under which to execute the statement
(defaults to <code>3</code>).
</li>
</ul>
</td>
</tr>
</table>
<table border="1" class="memberDocFrame">
<tr>
<td class="memberDocHeader">
<code class="memberDocName">drop_database</code>
<span class="memberDocNameCaption">(method; member of <code>kinterbasdb.Connection</code>)</span>
</td>
</tr>
<tr>
<td>
<p>
Deletes the database to which the connection is attached.
</p>
<p>
This method performs the database deletion in a responsible
fashion. Specifically, it:
<ul class="argList">
<li>raises an <code>OperationalError</code> instead of deleting
the database if there are other active connections to the
database</li>
<li>deletes supporting files and logs in addition to the
primary database file(s)</li>
</ul>
</p>
<p>
This method has no arguments.
</p>
</td>
</tr>
</table>
<p class="textParagraph" style="margin-top: 1.5em;">
Example program:
</p>
<pre class="codeBlock" style="margin-top: 0px;"><FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">create_database</FONT>(
<FONT COLOR="#8f8c47">"create database '/temp/db.db' user 'sysdba' password 'pass'"</FONT>
)
con.<FONT COLOR="#000066">drop_database</FONT>()</pre>
<hr>
<a name="adv_event"><h2>Database Event Notification</h2></a>
<ul style="margin-bottom: 2em;">
<li><a href="#adv_event_what">What are database events?</a></li>
<li><a href="#adv_event_why">Why use database events?</a></li>
<li><a href="#adv_event_native_exposure">
How does the database engine expose events to SQL (in the server process)
and C (in the client process)?
</a>
</li>
<li><a href="#adv_event_python_exposure">
How does KInterbasDB expose database events to the Python programmer?
</a>
</li>
<li><a href="#adv_event_example">Example Program</a></li>
<li><a href="#adv_event_limitations">Pitfalls and Limitations</a></li>
</ul>
<a name="adv_event_what"><h4>What are database events?</h4></a>
<p class="textParagraph">
The database engine features a distributed, interprocess communication
mechanism based on messages called <em>database events</em>.
Chapter 11 of the
<a href="#ref_ib6_docs">Interbase® 6 API Guide</a>
describes database events this way:
</p>
<blockquote>
[A database event is] a message passed from a trigger or stored procedure to an
application to
announce the occurrence of a specified condition or action, usually a database
change such as an insertion, modification, or deletion of a record.
</blockquote>
<blockquote>
The Interbase® [and Firebird] event mechanism enables applications to respond
to actions and database changes made by other, concurrently running
applications without the need for those applications to communicate directly
with one another, and without incurring the expense of CPU time required for
periodic polling to determine if an event has occurred.
</blockquote>
<a name="adv_event_why"><h4>Why use database events?</h4></a>
<p class="textParagraph">
Anything that can be accomplished with database events can also be
implemented using other techniques, so why bother with events?
Since you've chosen to write database-centric programs in Python rather
than assembly language, you probably already know the answer to this
question, but let's illustrate.
</p>
<p class="textParagraph">
A classic application for database events is the handling of administrative
messages. Suppose you have an administrative message database with a
<code>messages</code> table, into which various applications insert timestamped
status reports. It may be desirable to react to these messages in diverse ways,
depending on the status they indicate:
to ignore them,
to initiate the update of dependent databases upon their arrival,
to forward them by e-mail to a remote administrator,
or even to set off an audible alarm so that on-site administrators will know
a problem has occurred.
</p>
<p class="textParagraph">
It is undesirable to tightly couple the program whose status is being reported
(the <em>message producer</em>) to the program that handles the status reports
(the <em>message handler</em>).
There are obvious losses of flexibility in doing so.
For example, the message producer may run on a separate machine from the
administrative message database and may lack access rights to the downstream
reporting facilities (e.g., network access to the SMTP server, in the case of
forwarded e-mail notifications). Additionally, the actions required to
handle status reports may themselves be time-consuming and
error-prone, as in accessing a remote network to transmit e-mail.
</p>
<p class="textParagraph">
In the absence of database event support, the message handler would probably
be implemented via <em>polling</em>. Polling is simply the repetition of
a check for a condition at a specified interval.
In this case, the message handler would check in an infinite loop to see
whether the most recent record in the <code>messages</code> table was more
recent than the last message it had handled. If so, it would handle the
fresh message(s); if not, it would go to sleep for a specified interval,
then loop.
</p>
<p class="textParagraph">
The <em>polling-based</em> implementation of the message handler is
fundamentally flawed. Polling is a form of
<a href="http://www.catb.org/~esr/jargon/html/entry/busy-wait.html">busy-wait</a>;
the check for new messages is performed at the specified interval, regardless
of the actual activity level of the message producers.
If the polling interval is lengthy,
messages might not be handled within a reasonable time period after their arrival;
if the polling interval is brief, the message handler program (and there may
be many such programs) will waste a large amount of CPU time on unnecessary
checks.
</p>
<p class="textParagraph">
The database server is necessarily aware of the exact moment
when a new message arrives. Why not let the message handler program request
that the database server send it a notification when a new message arrives?
The message handler can then efficiently sleep until the moment its services
are needed. Under this <em>event-based</em>
scheme, the message handler becomes aware of new messages at the instant
they arrive, yet it does not waste CPU time checking in vain for new messages
when none is available.
</p>
<a name="adv_event_native_exposure">
<h4>How does the database engine expose events to SQL (in the server process)
and C (in the client process)?
</h4>
</a>
<p class="textParagraph">
<ol>
<li style="margin-bottom: 1.5em;">Server Process
<span style="font-size: 85%;">("An event just occurred!")</span>
<p class="textParagraph">
Recall from Chapter 11 of the
<a href="#ref_ib6_docs">Interbase® 6 API Guide</a>
that
</p>
<blockquote style="margin-top: 0px;">
[A database event is] a message passed from a trigger or stored procedure
to an application to announce the occurrence of a specified condition or
action, usually a database change such as an insertion, modification, or
deletion of a record.
</blockquote>
<p class="textParagraph">
To notify any interested listeners that a specific event has occurred,
issue the
<code>POST_EVENT</code> statement
(see page 176 of the <a href="#ref_ib6_docs">Interbase® 6 Language Reference</a>).
The <code>POST_EVENT</code> statement has one parameter: the name of the
event to post.
</p>
<p class="textParagraph">
In the preceding example of the administrative message database,
<code>POST_EVENT</code> might be used from an <code>after insert</code>
trigger on the <code>messages</code> table, like this:
</p>
<pre class="codeBlock" style="margin-top: 0px;">create trigger trig_messages_handle_insert
for messages
after insert
as
begin
<span style="color: blue;">POST_EVENT</span> 'new_message';
end
</pre>
<p class="textParagraph">
Note that the physical notification of the client process does not occur until the
transaction in which the <code>POST_EVENT</code> took place is actually
committed. Therefore, multiple events may <em>conceptually</em> occur
before the client process is <em>physically</em> informed of even one
occurrence.
</p>
<p class="textParagraph">Furthermore, the database engine makes no
guarantee that clients will be informed of events in the same groupings
in which they conceptually occurred. If, within a single transaction, an event
named <code>event_a</code> is posted once and an event named
<code>event_b</code> is posted once, the client may receive those posts
in separate "batches", despite the fact that they occurred in the same
conceptual unit (a single transaction). This also applies to multiple
occurrences of <em>the same</em> event within a single conceptual unit: the
physical notifications may arrive at the client separately.
</p>
</li>
<li>Client Process <span style="font-size: 85%;">("Send me a message when an event occurs.")</span><br>
<p class="textParagraph" style="margin-bottom: 1.5em;">
<strong>Note:</strong>
This section is intended mainly as an implementation hint to the authors of
future libraries based on the Firebird C client library, and as a reminder
to the author David Rushby himself, stored away in plain sight as a
vaccination against the recurrence of the headaches that ensued from his
attempt to use the most abysmally documented area of the Firebird C API.
If you're a Python programmer who doesn't care about the gory details
and isn't anxious to read a whole series of sentences as long as the
previous one, skip to the section that describes
<a href="#adv_event_python_exposure">KInterbasDB's Python-level event handling API</a>.
</p>
<p class="textParagraph">
The Interbase®/Firebird C client library offers two forms of event notification.
</p>
<p class="textParagraph">
The first form is <em>synchronous</em> notification, by way of the function
<code>isc_wait_for_event</code>. This form is admirably simple for a C
programmer to use, but completely inappropriate as a basis for KInterbasDB's
event support, for two reasons.
The database's C client library implements <code>isc_wait_for_event</code>
via <em>process suspension</em>, which puts the entire process to sleep until
an event notification arrives. This behavior clashes with
multithreaded programs, which may need to have one thread enter
a blocking wait for event notifications while other threads remain active.
Secondly, process suspension is not available on the Windows platform, and the
database client library does not implement <code>isc_wait_for_event</code>
on Linux.
Although the implementation of <code>isc_wait_for_event</code> makes it
unsuitable for use by the internals of KInterbasDB, the ease with which
it exposes database event notification to the client programmer is quite
Pythonic, a fact that was
<a href="#adv_event_python_exposure">not lost</a> on the bleary-eyed
Mr. Rushby.
</p>
<p class="textParagraph">
The other form of event notification offered by the database client library
is <em>asynchronous</em>, by way of the functions
<code>isc_que_events</code> (apparently the letters
<code>u</code> and <code>e</code> were in short supply that day),
<code>isc_cancel_events</code>, and others.
</p>
<p class="textParagraph">
The details are as nasty as they are numerous, but the essence of using
asynchronous notification from C is as follows:
</p>
<ol style="margin-left: 3em;">
<li>Call <code>isc_event_block</code> to create a formatted binary buffer
that will tell the server which events the client wants to listen for.
</li>
<li>Call <code>isc_que_events</code> (passing the buffer created in the
previous step) to inform the server that the client is ready to receive
event notifications, and provide a callback that will be asynchronously
invoked when one or more of the registered events occurs.
</li>
<li>[The thread that called <code>isc_que_events</code> to initiate event
listening must now do something else.]
</li>
<li>When the callback is invoked (the database client library starts a thread
dedicated to this purpose), it can use the <code>isc_event_counts</code>
function to determine how many times each of the registered events has
occurred since the last call to <code>isc_event_counts</code> (if any).
</li>
<li>[The callback thread should now "do its thing", which may include
communicating with the thread that called <code>isc_que_events</code>.]
</li>
<li>When the callback thread is finished handling an event notification, it
must call <code>isc_que_events</code> again in order to receive future
notifications. Future notifications will invoke the callback again,
effectively "looping" the callback thread back to Step 4.
</li>
</ol>
<p class="textParagraph">
As implemented by the Interbase®/Firebird C client library, asynchronous event
notification suffers from a significant limitation: only one thread per
process can listen for events at any given time.
</p>
<p class="textParagraph">
The rest of this section describes the C-level internals of KInterbasDB's event
support; the exposed Python API is documented in
<a href="#adv_event_python_exposure">the next section</a>.
</p>
<p class="textParagraph">
KInterbasDB's event-related internals conform loosely to the outline
above, although the Python interpreter's own threading limitations complicate
matters greatly.
Let's fill in the blanks of Steps 3 and 5 from the outline with
specific descriptions.
</p>
<p class="textParagraph" style="font-style: italic;">
3. [The thread that called <code>isc_que_events</code> to initiate event
listening must now do something else.]
</p>
<p class="textParagraph">
In KInterbasDB, "<i>the thread that called <code>isc_que_events</code> to
initiate event listening</i>" is a native thread started by Python
(either explicitly by the Python programmer, or implicitly by the Python
interpreter to run the main program); let's call it Thread-Py.
</p>
<p class="textParagraph">
Thread-Py, running in KInterbasDB's C layer, executes Steps 1 and 2, then
<em>waits</em> on a native event object (on Win32, an <code>Event</code>;
on POSIX, a pair of <code>pthread_cond_t</code> and <code>pthread_mutex_t</code>).
</p>
<p class="textParagraph" style="font-style: italic;">
5. [The callback thread should now "do its thing", which may include
communicating with the thread that called <code>isc_que_events</code>.]
</p>
<p class="textParagraph">
In KInterbasDB, the "<i>callback thread</i>" is a native thread started by the
database's C client library; let's call it Thread-Ev.
</p>
<p class="textParagraph">
The client library actually starts Thread-Ev as soon as Thread-Py calls
<code>isc_que_events</code>, without waiting for any events to occur. This
initial "dummy run" gives Thread-Ev a chance to perform any necessary
initialization. In KInterbasDB, this consists merely of clearing the buffer
used to tally the occurrence counts of the registered events (and of
re-queueing Thread-Ev to receive future event notifications--Step 6 from
the outline).
</p>
<p class="textParagraph">
Thread-Ev, having been started by the database client library rather than
the Python interpreter, is a "naked" native thread. Although any thread
started via Python's <code>thread</code> or <code>threading</code> modules
is a full-fledged native thread, a "naked" thread must have Python
threadstate bootstrapped onto it before the Python interpreter can execute
Python code on that thread.
Thread-Ev does not need any Python threadstate, however, because KInterbasDB's
C-level event callback function is designed to avoid Python code and operate
solely in native C.
</p>
<p class="textParagraph">
Step 5 consists of the callback thread
"<span style="font-style: italic;">doing its thing</span>"; in KInterbasDB,
the mission of Thread-Ev during a given iteration of the event callback is
threefold:
first, to supply Thread-Py with enough information to generate
the return value required by the interface of the
<code>EventConduit.wait</code> method;
secondly, to notify Thread-Py that an event has occurred;
and finally (Step 6 from the outline) for Thread-Ev to re-queue itself
via <code>isc_que_events</code> so that the callback will be invoked upon
the occurrence of future events.
</p>
<p class="textParagraph">
To accomplish the first element of the mission, Thread-Ev inserts a node
into a C linked list associated with the <code>EventConduit</code> upon
which Thread-Py is <code>wait</code>ing.
Every <code>EventConduit</code> holds a C linked list of type
<code>EventQueue</code>. An <code>EventQueue</code> is comprised of
<code>EventQueueItem</code>s; each <code>EventQueueItem</code> contains an
array of C <code>long</code>s. This array is designed to hold the occurrence
counts of the registered events, as reported by <code>isc_event_counts</code>
during the ongoing iteration of the event callback by Thread-Ev.
</p>
<p class="textParagraph">
Secondly, Thread-Ev issues a native event notification
(<code>SetEvent</code> on Win32; <code>pthread_cond_signal</code> on POSIX)
to release Thread-Py from its blocking call to <code>EventConduit.wait</code>.
</p>
<p class="textParagraph">
Finally, Thread-Ev re-queues itself via <code>isc_que_events</code>, and
control of the thread passes out of the callback and back into the database
client library.
The database client library does not start and destroy a new thread per
event notification; rather, it starts the thread we've nicknamed Thread-Ev
upon the first call to <code>isc_que_events</code>, then
reuses that same thread for all future event notifications within the same
process. This thread is recycled even for notifications that concern a
different set of event names (in KInterbasDB terminology, "even for a different
<code>EventConduit</code> object").
</p>
<p class="textParagraph">
When Thread-Py is awakened by Thread-Ev, it retrieves the head
<code>EventQueueItem</code> from the <code>EventQueue</code>, extracts the
<code>long</code> values from that node's <code>count</code> array into a
Python dictionary that maps
<code>event name -> event occurrence count</code>,
and returns the dictionary to the Python programmer as the return value of
<code>EventConduit.wait</code>.
</p>
<p class="textParagraph">
Throughout this process, responsible thread synchronization is observed
(with respect to the Python interpreter, the database client library, and
a specific <code>EventQueue</code>).
There is one avoidable scenario in which deadlocks are possible; it is
documented in the
<a href="#adv_event_limitations">Pitfalls and Limitations</a> subsection.
</p>
<p class="textParagraph">
The high-level event handling API that KInterbasDB exposes to the Python
programmer is documented in the next section.
</p>
</li>
</ol>
<a name="adv_event_python_exposure">
<h4>How does KInterbasDB expose database events to the Python programmer?</h4>
</a>
<p class="textParagraph">
The KInterbasDB database event API is comprised of the following:
the method <code>Connection.event_conduit</code> and the class
<code>EventConduit</code>.
</p>
<table border="1" class="memberDocFrame">
<tr>
<td class="memberDocHeader">
<code class="memberDocName">event_conduit</code>
<span class="memberDocNameCaption">(method; member of <code>kinterbasdb.Connection</code>)</span>
</td>
</tr>
<tr>
<td>
<p>
Creates a conduit (an instance of <code>EventConduit</code>) through
which database event notifications will flow into the Python program.
</p>
<p>
<code>event_conduit</code> is a method of <code>Connection</code>
rather than a module-level function or a class constructor because
the database engine deals with events in the context of a particular
database (after all, <code>POST_EVENT</code> must be issued by a
stored procedure or a trigger).
</p>
<p class="argHeader">Arguments:</p>
<ul class="argList">
<li>
<code>event_names</code> -
a sequence of string event names<br>
<p class="textParagraph">
The <code>EventConduit.wait</code> method will block until the
occurrence of at least one of the events named by the strings in
<code>event_names</code>.
</p>
</li>
</ul>
</td>
</tr>
</table>
<p class="compactParagraph" style="font-size: 100%;">
<code>EventConduit:</code>
</p>
<!-- kinterbasdb.EventConduit.__init__ -->
<table border="1" class="memberDocFrame">
<tr>
<td class="memberDocHeader">
<code class="memberDocName">__init__</code>
<span class="memberDocNameCaption">(method; member of <code>kinterbasdb.EventConduit</code>)</span>
</td>
</tr>
<tr>
<td>
<p>
The <code>EventConduit</code> class is not designed to be instantiated
directly by the Python programmer. Instead, use the
<code>Connection.event_conduit</code> method to create
<code>EventConduit</code> instances.
</p>
</td>
</tr>
</table>
<!-- kinterbasdb.EventConduit.wait -->
<table border="1" class="memberDocFrame">
<tr>
<td class="memberDocHeader">
<code class="memberDocName">wait</code>
<span class="memberDocNameCaption">(method; member of <code>kinterbasdb.EventConduit</code>)</span>
</td>
</tr>
<tr>
<td>
<p class="compactParagraph">
Blocks the calling thread until at least one of the events occurs,
or the specified <code>timeout</code> (if any) expires.
</p>
<p class="compactParagraph">
If one or more event notifications has arrived since the last call
to <code>wait</code>, this method will retrieve a notification from
the head of the <code>EventConduit</code>'s internal queue and
return immediately.
</p>
<p class="compactParagraph" style="margin-bottom: 0px;">
The names of the relevant events were supplied to the
<code>Connection.event_conduit</code> method during the creation
of this <code>EventConduit</code>.
In the code snippet below, the relevant events are named
<code>event_a</code> and <code>event_b</code>:
</p>
<pre class="codeBlockInMemberDoc">conduit <FONT COLOR="#7d0000">=</FONT> connection.<FONT COLOR="#000066">event_conduit</FONT>( (<FONT COLOR="#8f8c47">'event_a'</FONT>, <FONT COLOR="#8f8c47">'event_b'</FONT>) )
conduit.<FONT COLOR="#000066">wait</FONT>()
</pre>
<p class="argHeader">Arguments:</p>
<ul class="argList">
<li><code>timeout</code> <em>(optional)</em> -
number of seconds (use a <code>float</code> to indicate fractions of seconds)<br>
<p class="textParagraph">
If not even one of the relevant events has occurred after
<code>timeout</code> seconds, this method will unblock and return
<code>None</code>.
The default <code>timeout</code> is infinite.
</p>
</li>
</ul>
<p class="retHeader">Returns:</p>
<p class="retDesc">
<code>None</code> if the wait timed out, otherwise a dictionary
that maps <code>event_name -> event_occurrence_count</code>.
</p>
<p class="compactParagraph" style="margin-bottom: 0px;">
In the code snippet above, if <code>event_a</code> occurred once and
<code>event_b</code> did not occur at all, the return value from
<code>conduit.wait()</code> would be the following dictionary:
</p>
<pre class="codeBlockInMemberDoc">{
<FONT COLOR="#8f8c47">'event_a'</FONT>: <FONT COLOR="#666600">1</FONT>,
<FONT COLOR="#8f8c47">'event_b'</FONT>: <FONT COLOR="#666600">0</FONT>
}
</pre>
</td>
</tr>
</table>
<!-- kinterbasdb.EventConduit.close -->
<table border="1" class="memberDocFrame">
<tr>
<td class="memberDocHeader">
<code class="memberDocName">close</code>
<span class="memberDocNameCaption">(method; member of <code>kinterbasdb.EventConduit</code>)</span>
</td>
</tr>
<tr>
<td>
<p class="compactParagraph">
Cancels the standing request for this conduit to be notified of events,
clearing the way for the creation of another
<code>EventConduit</code>
(via the <code>Connection.event_conduit</code> method).
</p>
<p class="compactParagraph">
After this method has been called, this <code>EventConduit</code>
object is useless, and should be discarded.
</p>
<p class="compactParagraph">
This method has no arguments.
</p>
</td>
</tr>
</table>
<!-- kinterbasdb.EventConduit.flush -->
<table border="1" class="memberDocFrame">
<tr>
<td class="memberDocHeader">
<code class="memberDocName">flush</code>
<span class="memberDocNameCaption">(method; member of <code>kinterbasdb.EventConduit</code>)</span>
</td>
</tr>
<tr>
<td>
<p class="compactParagraph">
This method allows the Python programmer to manually clear any
event notifications that have queued up since the last
<code>wait</code> call.
</p>
<p class="compactParagraph">
After the first <code>wait</code> call on a given
<code>EventConduit</code>, notifications of any events that occur
will accumulate asynchronously within the conduit's internal
queue until the conduit is <code>close</code>d either explicitly or
implicitly (via garbage collection). There are two ways to dispose
of the accumulated notifications: call <code>wait</code> to receive
them one at a time (<code>wait</code> will block when the conduit's
internal queue is empty), or call this method to get rid of all
accumulated notifications.
</p>
<p class="compactParagraph">
This method has no arguments.
</p>
<p class="retHeader">Returns:</p>
<p class="retDesc">
The number of event notifications that were flushed from the queue.
The "number of event <em>notifications</em>" is not necessarily the
same as the "number of event <em>occurrences</em>", since a single
notification can indicate multiple occurrences of a given event
(see the return value of the <code>wait</code> method).
</p>
</td>
</tr>
</table>
<br><br>
<a name="adv_event_example"><h4>Example Program</h4></a>
<p class="textParagraph">
The following code (a SQL table definition, a SQL trigger definition, and
two Python programs) demonstrates KInterbasDB-based event notification.
</p>
<p class="textParagraph">
The example is based on a database at
<code>'localhost:/temp/test.db'</code>, which contains
a simple table named <code>test_table</code>.
<code>test_table</code> has an <code>after insert</code>
trigger that posts several events.
Note that the trigger posts <code>test_event_a</code> twice,
<code>test_event_b</code> once, and <code>test_event_c</code> once.
</p>
<p class="textParagraph">
The Python event <em>handler</em> program connects to the database and
establishes an <code>EventConduit</code> in the context of that connection.
As specified by the list of <code>RELEVANT_EVENTS</code> passed to
<code>event_conduit</code>, the event conduit
will concern itself only with events named <code>test_event_a</code>
and <code>test_event_b</code>.
Next, the program calls the conduit's <code>wait</code> method
without a timeout; it will wait infinitely until <em>at least one</em>
of the relevant events is posted in a transaction that is
subsequently committed.
</p>
<p class="textParagraph">
The Python event <em>producer</em> program simply connects to the database,
inserts a row into <code>test_table</code>, and commits the transaction.
Notice that except for the printed comment, no code in the producer
makes any mention of events--the events are posted as an implicit
consequence of the row's insertion into <code>test_table</code>.
</p>
<p class="textParagraph">
The insertion into <code>test_table</code> causes the trigger
to <em>conceptually</em> post events, but those events are not
<em>physically</em> sent to interested listeners until the transaction
is committed.
When the commit occurs, the handler program returns from the <code>wait</code>
call and prints the notification that it received.
</p>
<p style="margin-bottom: 0px;">
SQL table definition:
</p>
<pre class="codeBlock" style="margin-top: 0px;">
create table test_table (a integer)
</pre>
<p style="margin-bottom: 0px;">
SQL trigger definition:
</p>
<pre class="codeBlock" style="margin-top: 0px;">
create trigger trig_test_insert_event
for test_table
after insert
as
begin
POST_EVENT 'test_event_a';
POST_EVENT 'test_event_b';
POST_EVENT 'test_event_c';
POST_EVENT 'test_event_a';
end
</pre>
<p style="margin-bottom: 0px;">
Python event <em>handler</em> program:
</p>
<pre class="codeBlock" style="margin-top: 0px;">
<FONT COLOR="#0000ff">import</FONT> kinterbasdb
RELEVANT_EVENTS <FONT COLOR="#7d0000">=</FONT> [<FONT COLOR="#8f8c47">'test_event_a'</FONT>, <FONT COLOR="#8f8c47">'test_event_b'</FONT>]
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
conduit <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">event_conduit</FONT>(RELEVANT_EVENTS)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'HANDLER: About to wait for the occurrence of one of %s...\n'</FONT> <FONT COLOR="#7d0000">%</FONT> RELEVANT_EVENTS
result <FONT COLOR="#7d0000">=</FONT> conduit.<FONT COLOR="#000066">wait</FONT>()
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'HANDLER: An event notification has arrived:'</FONT>
<FONT COLOR="#0000ff">print</FONT> result
conduit.<FONT COLOR="#000066">close</FONT>()
</pre>
<p style="margin-bottom: 0px;">
Python event <em>producer</em> program:
</p>
<pre class="codeBlock" style="margin-top: 0px;">
<FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
cur <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"insert into test_table values (1)"</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'PRODUCER: Committing transaction that will cause event notification to be sent.'</FONT>
con.<FONT COLOR="#000066">commit</FONT>()
</pre>
<p style="margin-bottom: 0px;">
Event producer output:
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
PRODUCER: Committing transaction that will cause event notification to be sent.
</pre>
<p style="margin-bottom: 0px;">
Event handler output (assuming that the handler was already started and waiting
when the event producer program was executed):
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
HANDLER: About to wait for the occurrence of one of ['test_event_a', 'test_event_b']...
HANDLER: An event notification has arrived:
{'test_event_a': 2, 'test_event_b': 1}
</pre>
<p class="textParagraph">
Notice that there is no mention of <code>test_event_c</code> in the result
dictionary received by the event handler program.
Although <code>test_event_c</code> was posted by the <code>after insert</code>
trigger, the event conduit in the handler program was created to
listen only for <code>test_event_a</code> and
<code>test_event_b</code> events.
</p>
<br>
<a name="adv_event_limitations">
<h4>Pitfalls and Limitations</h4>
</a>
<ul>
<li>
<p>
Only one <code>EventConduit</code> can be active in a single process
at any given time
(limitation imposed by the database client library).<br>
KInterbasDB enforces this limitation by raising an exception if the Python programmer tries to breach it.
</p>
</li>
<li>
<p>
No more than 16 event names can be <code>wait</code>ed for with
a single <code>EventConduit</code>
(limitation imposed by the database client library).<br>
KInterbasDB enforces this limitation by raising an exception if the Python programmer tries to breach it.
</p>
</li>
<li>
<p>
Remember that if an <code>EventConduit</code> is left active (not yet
<code>close</code>d or garbage collected), notifications for any
registered events that actually occur
will continue to accumulate in the <code>EventConduit</code>'s
internal queue even if the Python programmer doesn't call
<code>EventConduit.wait</code> to receive the notifications or
<code>EventConduit.flush</code> to clear the queue.
The ill-informed may misinterpret this behavior as a memory leak in
KInterbasDB; it is not.
</p>
</li>
<li>
<span style="color: red; font-weight: bold;">
NEVER use LOCAL-protocol connections in a multithreaded program that
also uses event handling!
</span><br>
<p class="textParagraph">
The database client library implements the local protocol on some
platforms in such a way that deadlocks may arise in bizarre places if
you do this.
<em>This no-LOCAL prohibition is not limited to connections that are
used as the basis for event conduits; it applies to all connections
throughout the process.</em>
</p>
<p class="textParagraph">
So why doesn't KInterbasDB protect the Python programmer from this
mistake? Because the event handling thread is started by the
database client library, and it
<a href="#adv_event_native_exposure">operates</a>
beyond the synchronization domain of KInterbasDB at times.
</p>
</li>
</ul>
<br>
<hr>
<br>
<a name="adv_trans_control">
<h2>Advanced Transaction Control</h2>
</a>
<p class="textParagraph">
For the sake of simplicity, KInterbasDB lets the Python programmer
ignore transaction management to the greatest extent allowed by the
Python Database API Specification 2.0. The specification says,
"if the database supports an auto-commit feature, this must be
initially off". At a minimum, therefore, it is necessary to call the
<code>commit</code> method of the connection in order to persist any
changes made to the database. Transactions left unresolved by the
programmer will be <code>rollback</code>ed when the connection is
garbage collected.
</p>
<p class="textParagraph">
Remember that because of
<a href="http://philip.greenspun.com/panda/databases-choosing#acid">ACID</a>,
every data manipulation operation in the Interbase®/Firebird database engine
takes place in the context of a transaction, including operations that are
conceptually "read-only", such as a typical <code>SELECT</code>.
The client programmer of KInterbasDB establishes a transaction
implicitly by using any SQL execution method, such as
<code>Connection.execute_immediate</code>, <code>Cursor.execute</code>,
or <code>Cursor.callproc</code>.
</p>
<p class="textParagraph">
Although KInterbasDB allows the programmer to pay little attention to
transactions, it also exposes the full complement of the database engine's
advanced transaction control features:
transaction parameters, retaining transactions, savepoints, and
distributed transactions.
</p>
<br>
<a name="adv_trans_control_parameters"><h4>Transaction Parameters</h4></a>
<p class="textParagraph">
The database engine offers the client programmer an optional facility called
<em>transaction parameter buffers</em> (TPBs) for tweaking the operating characteristics
of the transactions he initiates. These include characteristics such as
"whether the transaction has read and write access to tables,
or read-only access, and whether or not other simultaneously active
transactions can share table access with the transaction"
(<a href="#ref_ib6_docs">IB 6 API Guide</a>, page 62).
</p>
<p class="textParagraph">
In addition to the implicit transaction initiation mentioned in the
<a href="#adv_trans_control">introduction</a> of this section, KInterbasDB
allows the programmer to start transactions explicitly via the
<code>Connection.begin</code> method.
Connections have a <code>default_tpb</code> attribute
that can be changed to set the default TPB for all transactions subsequently
started on the connection.
Alternatively, if the programmer only wants to set the TPB for a single
transaction, he can start a transaction explicitly via the
<code>Connection.begin</code> method and pass a TPB for that single
transaction.
</p>
<p class="textParagraph">
For details about TPB construction, see Chapter 5 of the
<a href="#ref_ib6_docs">Interbase® 6 API Guide</a>.
In particular, page 63 of that document presents a table of possible
TPB elements--single bytes that the C API defines as constants whose names
begin with <code>isc_tpb_</code>.
KInterbasDB makes all of those TPB constants available (under the same names)
as module-level constants in the form of single-character strings.
A transaction parameter <em>buffer</em> is handled in C as a
character array; KInterbasDB requires that TPBs be constructed as Python
strings. Since the constants in the <code>kinterbasdb.isc_tpb_*</code>
family are single-character Python strings, they can simply be concatenated
to create a TPB.
<br><br>
</p>
<p class="textParagraph">
The following example program uses explicit transaction initiation and TPB
construction to establish an unobtrusive transaction for read-only
access to the database:
</p>
<pre class="codeBlock">
<FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
<FONT COLOR="#32a532"># Construct a TPB by concatenating single-character strings (bytes)</FONT>
<FONT COLOR="#32a532"># from the kinterbasdb.isc_tpb_* family.</FONT>
customTPB <FONT COLOR="#7d0000">=</FONT> (
kinterbasdb.isc_tpb_read
<FONT COLOR="#7d0000">+</FONT> kinterbasdb.isc_tpb_read_committed
<FONT COLOR="#7d0000">+</FONT> kinterbasdb.isc_tpb_rec_version
)
<FONT COLOR="#32a532"># Explicitly start a transaction with the custom TPB:</FONT>
con.<FONT COLOR="#000066">begin</FONT>(tpb<FONT COLOR="#7d0000">=</FONT>customTPB)
<FONT COLOR="#32a532"># Now read some data using cursors:</FONT>
...
<FONT COLOR="#32a532"># Commit the transaction with the custom TPB. Future transactions</FONT>
<FONT COLOR="#32a532"># opened on con will not use a custom TPB unless it is explicitly</FONT>
<FONT COLOR="#32a532"># passed to con.begin every time, as it was above, or</FONT>
<FONT COLOR="#32a532"># con.default_tpb is changed to the custom TPB, as in:</FONT>
<FONT COLOR="#32a532"># con.default_tpb = customTPB</FONT>
con.<FONT COLOR="#000066">commit</FONT>()
</pre>
<br>
<a name="adv_trans_control_retaining"><h4>Retaining Operations</h4></a>
<p class="textParagraph">
The <code>commit</code> and <code>rollback</code> methods of
<code>kinterbasdb.Connection</code>
accept an optional boolean parameter <code>retaining</code>
(default <code>False</code>) to indicate whether to recycle the
transactional context of the transaction being resolved by the
method call.
</p>
<p class="textParagraph">
If <code>retaining</code> is <code>True</code>, the infrastructural
support for the transaction active
at the time of the method call will be "retained" (efficiently and
transparently recycled) after the database server has committed or rolled
back the conceptual transaction.
In code that commits or rolls back frequently, "retaining" the
transaction yields considerably better performance.
</p>
<p class="textParagraph">
For more information about retaining transactions, see page 291 of the
<a href="#ref_ib6_docs">Interbase® 6 API Guide</a>.
</p>
<br>
<a name="adv_trans_control_savepoints"><h4>Savepoints</h4></a>
<p class="textParagraph">
Firebird 1.5 introduced support for transaction savepoints.
Savepoints are named, intermediate control points within an open transaction
that can later be rolled back to, without affecting the preceding work.
Multiple savepoints can exist within a single unresolved transaction,
providing "multi-level undo" functionality.
</p>
<p class="textParagraph">
Although Firebird savepoints are fully supported from SQL alone via the
<code>SAVEPOINT 'name'</code> and <code>ROLLBACK TO 'name'</code>
statements, KInterbasDB also exposes savepoints at the Python API level
for the sake of convenience.
The method <code>Connection.savepoint(name)</code> establishes a savepoint
with the specified <code>name</code>.
To roll back to a specific savepoint, call the
<code>Connection.rollback</code> method and provide a value (the name of
the savepoint) for the optional <code>savepoint</code> parameter.
If the <code>savepoint</code> parameter of <code>Connection.rollback</code>
is not specified, the active transaction is cancelled in its entirety,
as required by the Python Database API Specification.
</p>
<p class="textParagraph">
The following example program demonstrates savepoint manipulation via
the KInterbasDB API, rather than raw SQL.
</p>
<span style="color: blue;"></span>
<pre class="codeBlock" style="margin-top: 0px;">
<FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
cur <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"recreate table test_savepoints (a integer)"</FONT>)
con.<FONT COLOR="#000066">commit</FONT>()
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'Before the first savepoint, the contents of the table are:'</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select * from test_savepoints"</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">' '</FONT>, cur.<FONT COLOR="#000066">fetchall</FONT>()
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"insert into test_savepoints values (?)"</FONT>, [<FONT COLOR="#666600">1</FONT>])
<strong>con.<FONT COLOR="#000066">savepoint</FONT>(<FONT COLOR="#8f8c47">'A'</FONT>)</strong>
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'After savepoint A, the contents of the table are:'</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select * from test_savepoints"</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">' '</FONT>, cur.<FONT COLOR="#000066">fetchall</FONT>()
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"insert into test_savepoints values (?)"</FONT>, [<FONT COLOR="#666600">2</FONT>])
<strong>con.<FONT COLOR="#000066">savepoint</FONT>(<FONT COLOR="#8f8c47">'B'</FONT>)</strong>
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'After savepoint B, the contents of the table are:'</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select * from test_savepoints"</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">' '</FONT>, cur.<FONT COLOR="#000066">fetchall</FONT>()
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"insert into test_savepoints values (?)"</FONT>, [<FONT COLOR="#666600">3</FONT>])
<strong>con.<FONT COLOR="#000066">savepoint</FONT>(<FONT COLOR="#8f8c47">'C'</FONT>)</strong>
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'After savepoint C, the contents of the table are:'</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select * from test_savepoints"</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">' '</FONT>, cur.<FONT COLOR="#000066">fetchall</FONT>()
<strong>con.<FONT COLOR="#000066">rollback</FONT>(savepoint<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'A'</FONT>)</strong>
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'After rolling back to savepoint A, the contents of the table are:'</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select * from test_savepoints"</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">' '</FONT>, cur.<FONT COLOR="#000066">fetchall</FONT>()
<strong>con.<FONT COLOR="#000066">rollback</FONT>()</strong>
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'After rolling back entirely, the contents of the table are:'</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select * from test_savepoints"</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">' '</FONT>, cur.<FONT COLOR="#000066">fetchall</FONT>()
</pre>
<p class="textParagraph">
The output of the example program is shown below.
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
Before the first savepoint, the contents of the table are:
[]
After savepoint A, the contents of the table are:
[(1,)]
After savepoint B, the contents of the table are:
[(1,), (2,)]
After savepoint C, the contents of the table are:
[(1,), (2,), (3,)]
After rolling back to savepoint A, the contents of the table are:
[(1,)]
After rolling back entirely, the contents of the table are:
[]
</pre>
<br>
<a name="adv_trans_control_distributed"><h4>Distributed Transactions</h4></a>
<span class="XXX_ADDRESS_THIS">XXX: KInterbasDB's support for distributed
transactions has not yet been thoroughly documented. In the meantime, read the
source code for the <code>kinterbasdb.ConnectionGroup</code> class
and examine the brief example program below.</span>
<pre class="codeBlock">
<FONT COLOR="#0000ff">import</FONT> kinterbasdb
<FONT COLOR="#32a532"># Establish multiple connections the usual way:</FONT>
con1 <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'stalin:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
con2 <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'bison:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
<FONT COLOR="#32a532"># Create a ConnectionGroup to associate multiple connections in such a</FONT>
<FONT COLOR="#32a532"># way that they can participate in a distributed transaction.</FONT>
<FONT COLOR="#32a532"># !!!</FONT>
<FONT COLOR="#32a532"># NO TWO MEMBERS OF A SINGLE CONNECTIONGROUP SHOULD BE ATTACHED TO THE SAME DATABASE!</FONT>
<FONT COLOR="#32a532"># !!!</FONT>
group <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">ConnectionGroup</FONT>( connections<FONT COLOR="#7d0000">=</FONT>(con1,con2) )
<FONT COLOR="#32a532"># Start a distributed transaction involving all of the members of the group</FONT>
<FONT COLOR="#32a532"># (con1 and con2 in this case) with one of the following approaches:</FONT>
<FONT COLOR="#32a532"># - Call group.begin()</FONT>
<FONT COLOR="#32a532"># - Call con1.begin(); the operation will "bubble upward" and apply to the group.</FONT>
<FONT COLOR="#32a532"># - Call con2.begin(); the operation will "bubble upward" and apply to the group.</FONT>
<FONT COLOR="#32a532"># - Just start executing some SQL statements on either con1 or con2.</FONT>
<FONT COLOR="#32a532"># A transaction will be started implicitly; it will be a distributed</FONT>
<FONT COLOR="#32a532"># transaction because con1 and con2 are members of a ConnectionGroup.</FONT>
group.<FONT COLOR="#000066">begin</FONT>()
<FONT COLOR="#32a532"># Perform some database changes the usual way (via cursors on con1 and con2):</FONT>
...
<FONT COLOR="#32a532"># Commit or roll back the distributed transaction by calling the commit</FONT>
<FONT COLOR="#32a532"># or rollback method of the ConnectionGroup itself, or the commit or</FONT>
<FONT COLOR="#32a532"># rollback method of any member connection (con1 or con2 in this case).</FONT>
group.<FONT COLOR="#000066">commit</FONT>()
<FONT COLOR="#32a532"># Unless you want to perform another distributed transaction, disband the</FONT>
<FONT COLOR="#32a532"># group so that member connections can operate independently again.</FONT>
group.<FONT COLOR="#000066">clear</FONT>()
</pre>
<p style="margin-bottom: 0px;"><strong>Notes:</strong></p>
<p class="textParagraph">
While a <code>Connection</code> belongs to a
<code>ConnectionGroup</code>, any calls to the connection's transactional
methods (begin, prepare, commit, rollback) will "bubble upward" to apply to the
distributed transaction shared by the group as a whole.
</p>
<p class="textParagraph">
Connections can be dynamically <code>add</code>ed and <code>remove</code>d
from a <code>ConnectionGroup</code> provided that neither the group nor
the connection itself has an unresolved transaction at the time of the
addition/removal.
</p>
<p class="textParagraph">
Never add two connections to the same database to the same
<code>ConnectionGroup</code>!
</p>
<br>
<br>
<hr>
<br>
<a name="adv_param_conv">
<h2>Parameter Conversion</h2>
</a>
<p class="textParagraph">
KInterbasDB converts bound parameters marked with a <code>?</code>
in SQL code in a standard way. However, the module also offers several
extensions to standard parameter binding, intended to make client code
more readable and more convenient to write.
</p>
<a name="adv_param_conv_implicit_from_string">
<h3>Implicit Conversion of Input Parameters from Strings</h3>
</a>
<p class="textParagraph">
The database engine treats most SQL data types in a weakly typed fashion:
the engine may attempt to convert the raw value to a different type,
as appropriate for the current context.
For instance, the SQL expressions <code>123</code> (integer)
and <code>'123'</code> (string) are treated equivalently when the value is
to be inserted into an <code>integer</code> field; the same applies when
<code>'123'</code> and <code>123</code> are to be inserted into a
<code>varchar</code> field.
</p>
<p class="textParagraph">
This weak typing model is quite unlike Python's dynamic yet strong typing.
Although weak typing is regarded with suspicion by most experienced
Python programmers, the database engine is in certain situations so
aggressive about its typing model that KInterbasDB must
<a href="http://sourceforge.net/tracker/index.php?func=detail&aid=531828&group_id=9913&atid=309913">compromise</a>
in order to remain an elegant means of programming the database engine.
</p>
<p class="textParagraph">
An example is the handling of "magic values" for date and time fields.
The database engine interprets string values such as
<code>'yesterday'</code>, <code>'now'</code>,
and <code>'current_timestamp'</code> as having special meaning in a
date/time context.
If KInterbasDB did not accept strings as the values of parameters destined
for storage in date/time fields, the resulting code would be awkward.
Consider the difference between the two Python snippets
below, which insert a row containing an integer and a timestamp into a
table defined with the following DDL statement:
</p>
<pre class="codeBlock" style="margin-top: 0px;">
<FONT COLOR="#0000ff">create</FONT> <FONT COLOR="#0000ff">table</FONT> test_table (i <FONT COLOR="#0000ff">int</FONT>, t <FONT COLOR="#0000ff">timestamp</FONT>)
</pre>
<pre class="codeBlock">
i <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#666600">1</FONT>
t <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#8f8c47">'now'</FONT>
sqlWithMagicValues <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#8f8c47">"insert into test_table (i, t) values (?, '%s')"</FONT> <FONT COLOR="#7d0000">%</FONT> t
cur.<FONT COLOR="#000066">execute</FONT>( sqlWithMagicValues, (i,) )
</pre>
<pre class="codeBlock">
i <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#666600">1</FONT>
t <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#8f8c47">'now'</FONT>
cur.<FONT COLOR="#000066">execute</FONT>( <FONT COLOR="#8f8c47">"insert into test_table (i, t) values (?, ?)"</FONT>, (i, t) )
</pre>
<p class="textParagraph">
If KInterbasDB did not support weak parameter typing, string parameters
that the database engine is to interpret as "magic values" would have to
be rolled into the SQL statement in a separate operation from the
binding of the rest of the parameters, as in the first Python
snippet above.
Implicit conversion of parameter values from strings allows the consistency
evident in the second snippet, which is both more readable and more general.
</p>
<p class="textParagraph">
It should be noted that KInterbasDB does not perform the conversion from
string itself. Instead, it passes that responsibility to the database
engine by changing the parameter metadata structure dynamically at the
last moment, then restoring the original state of the metadata structure
after the database engine has performed the conversion.
</p>
<p class="textParagraph">
A secondary benefit is that when one uses KInterbasDB to import large
amounts of data from flat files into the database, the incoming values
need not necessarily be converted to their proper Python types before
being passed to the database engine. Eliminating this
intermediate step may accelerate the import process considerably, although
other factors such as the chosen connection protocol and the deactivation
of indexes during the import are more consequential.
For bulk import tasks, the database engine's external tables also deserve
consideration. External tables can be used to suck semi-structured data
from flat files directly into the relational database without the
intervention of an ad hoc conversion program.
</p>
<a name="adv_param_conv_dynamic_type_translation">
<h3>Dynamic Type Translation</h3>
</a>
<p class="textParagraph">
Dynamic type translators are conversion functions registered by the
Python programmer to transparently convert database field values
to and from their internal representation.
</p>
<p class="textParagraph">
The client programmer can choose to ignore translators altogether, in
which case KInterbasDB will manage them behind the scenes.
Otherwise, the client programmer can use any of several
<a href="#adv_param_conv_dynamic_type_translation_tbl_ref_trans">standard type translators</a>
included with KInterbasDB, register custom translators, or
set the translators to <code>None</code> to deal directly with the
KInterbasDB-internal representation of the data type.
When translators have been registered for a specific SQL data
type, Python objects on their way into a database field of that type
will be passed through the input translator before they are presented
to the database engine; values on their way out of the database into
Python will be passed through the corresponding output translator.
Output and input translation for a given type is usually implemented
by two different functions.
</p>
<p class="textParagraph">
</p>
<a name="adv_param_conv_dynamic_type_translation_specifics">
<h4>Specifics of the Dynamic Type Translation API</h4>
</a>
<p class="textParagraph">
Translators are registered with the <code>[set|get]_type_trans_[in|out]</code>
methods of <code>Connection</code> and <code>Cursor</code>.
The <code>set_type_trans_[in|out]</code> methods accept a single argument:
a mapping of type name to translator.
The <code>get_type_trans[in|out]</code> methods return a copy of the
translation table. <code>Cursor</code>s inherit their
<code>Connection</code>'s translation settings, but can override
them without affecting the connection or other cursors (much as
subclasses can override the methods of their base classes).
</p>
<p class="textParagraph">
The following code snippet installs an input translator for fixed
point types (<code>NUMERIC</code>/<code>DECIMAL</code> SQL types)
into a connection:
</p>
<pre class="codeBlock" style="margin-top: 0px; margin-bottom: 0px;">
con.set_type_trans_in( {'FIXED': fixed_input_translator_function} )
</pre>
<p class="textParagraph">
The following method call retrieves the type translation table for
<code>con</code>:
</p>
<pre class="codeBlock" style="margin-top: 0px; margin-bottom: 0px;">
con.get_type_trans_in()
</pre>
<p class="textParagraph">
The method call above would return a translation table (dictionary) such as
this:
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
{
'DATE': <function date_conv_in at 0x00920648>,
'TIMESTAMP': <function timestamp_conv_in at 0x0093E090>,
'FIXED': <function <lambda> at 0x00962DB0>,
'TIME': <function time_conv_in at 0x009201B0>
}
</pre>
<p class="textParagraph">
Notice that although the sample code registered only one type
translator, there are four listed in the mapping returned by the
<code>get_type_trans_in</code> method. KInterbasDB itself uses
dynamic type translation to implement <code>mx.DateTime</code>-based
date/time I/O, and to implement the deprecated
<code>Connection.precision_mode</code> API.
For the source code locations of KInterbasDB's reference translators,
see the
<a href="#adv_param_conv_dynamic_type_translation_tbl_ref_trans">table</a>
in the next section.
The <code>Connection.precision_mode</code> API is deprecated because
using it in combination with dynamic type translation is error-prone.
KInterbasDB itself installs new dynamic type translators when the value
of <code>Connection.precision_mode</code> is changed; if the programmer
has previously registered input or output translators for
<code>'FIXED'</code> types, those translators will be overwritten.
</p>
<p class="textParagraph">
In the sample above, a translator is registered under the key
<code>'FIXED'</code>, but Firebird has no SQL data type named
<code>FIXED</code>. The following table lists the names of the
database engine's SQL data types in the left column, and the
corresponding key under which client programmers can register
translators in the right column.
</p>
<table style="margin-left: 2em;">
<tr>
<td style="font-size: 105%; font-style: italic; font-weight: bold;">
<a name="adv_param_conv_dynamic_type_translation_tbl_trans_keys">
Mapping of SQL Data Type Names to Translator Keys
</a>
</td>
</tr>
<tr>
<td>
<table border="1">
<thead style="background-color: #EEEEEE; font-weight: bold;">
<tr>
<td style="width: 9em;">SQL Type(s)</td>
<td>Translator Key</td>
</tr>
</thead>
<tr>
<td style="vertical-align: top;">
<code>CHAR</code>/<code>VARCHAR</code>
</td>
<td>
<code>'TEXT'</code>
<span style="font-size: 80%;">for fields with charsets
<code>NONE</code>, <code>OCTETS</code>, or <code>ASCII</code></span>
<br>
<code>'TEXT_UNICODE'</code>
<span style="font-size: 80%;">for all other charsets</span>
</td>
</tr>
<tr>
<td><code>BLOB</code></td>
<td><code>'BLOB'</code></td>
</tr>
<tr>
<td><code>SMALLINT/INTEGER/BIGINT</code></td>
<td><code>'INTEGER'</code></td>
</tr>
<tr>
<td><code>FLOAT</code>/<code>DOUBLE PRECISION</code></td>
<td><code>'FLOATING'</code></td>
</tr>
<tr>
<td><code>NUMERIC</code>/<code>DECIMAL</code></td>
<td><code>'FIXED'</code></td>
</tr>
<tr>
<td><code>DATE</code></td>
<td><code>'DATE'</code></td>
</tr>
<tr>
<td><code>TIME</code></td>
<td><code>'TIME'</code></td>
</tr>
<tr>
<td><code>TIMESTAMP</code></td>
<td><code>'TIMESTAMP'</code></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="adv_param_conv_dynamic_type_translation_consequences">
<h4>Consequences of the Availability of Dynamic Type Translation in KInterbasDB</h4>
</a>
<p class="textParagraph">
Dynamic type translation has eliminated KInterbasDB's compile-time
dependency on <code>mx.DateTime</code>. Although KInterbasDB will continue
to use <code>mx.DateTime</code> as its default date/time representation
for the sake of backward compatibility, dynamic type translation allows Python 2.3
users to conveniently deal with database date/time values in terms of the
new standard library module <code>datetime</code>, if they choose to.
</p>
<p class="textParagraph">
Dynamic type translation also allows <code>NUMERIC</code>/<code>DECIMAL</code>
values to be transparently represented as
<a href="#ref_fixedpoint"><code>fixedpoint.FixedPoint</code></a>
objects rather than scaled integers, which is much more convenient.
For backward compatibility, <code>NUMERIC</code>/<code>DECIMAL</code>
values are still represented by default as Python <code>float</code>s,
and the older API based on <code>Connection.precision_mode</code> is still
present. However, all of these representations are now implemented
"under the hood" via dynamic type translation.
</p>
<p class="textParagraph">
Reference implementations of all of the translators discussed above
are provided with KInterbasDB 3.1 and later, in these modules:
</p>
<table style="margin-left: 2em;">
<tr>
<td style="font-size: 105%; font-style: italic; font-weight: bold;">
<a name="adv_param_conv_dynamic_type_translation_tbl_ref_trans">
Reference Translators Included with KInterbasDB
</a>
</td>
</tr>
<tr>
<td>
<table border="1">
<thead style="background-color: #EEEEEE; font-weight: bold;">
<tr>
<td style="width: 11em;">SQL Type(s)</td>
<td style="width: 16em;">Python Type(s)</td>
<td style="width: 21em;">Reference Implementation In Module</td>
</tr>
</thead>
<tr>
<td rowspan="3"><code>NUMERIC</code>/<code>DECIMAL</code></td>
<td><code>float</code> <em>(imprecise)</em> (default)</td>
<td><code>kinterbasdb.typeconv_fixed_stdlib</code></td>
</tr>
<tr>
<td>scaled <code>int</code> <em>(precise)</em></td>
<td><code>kinterbasdb.typeconv_fixed_stdlib</code></td>
</tr>
<tr>
<td><code>fixedpoint.FixedPoint</code> <em>(precise)</em></td>
<td><code>kinterbasdb.typeconv_fixed_fixedpoint</code></td>
</tr>
<tr>
<td rowspan="2"><code>DATE</code>/<code>TIME</code>/<code>TIMESTAMP</code></td>
<td><code>mx.DateTime</code> (default)</td>
<td><code>kinterbasdb.typeconv_datetime_mx</code></td>
</tr>
<tr>
<td>Python 2.3+ <code>datetime</code></td>
<td><code>kinterbasdb.typeconv_datetime_stdlib</code></td>
</tr>
<tr>
<td>
<code>CHAR/VARCHAR</code>
<div style="font-size: 80%;">(with any character set except<br> NONE, OCTETS, ASCII)</div>
</td>
<td style="vertical-align: top;"><code>unicode</code></td>
<td style="vertical-align: top;"><code>kinterbasdb.typeconv_text_unicode</code></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="adv_param_conv_dynamic_type_translation_writing_translators">
<h4>Writing Custom Translators</h4>
</a>
<p class="textParagraph">
Below is a table that specifies the required argument and return value
signatures of input and output converters for the various translator
keys.
Python's native types map perfectly to
<code>'TEXT'</code>,
<code>'TEXT_UNICODE'</code>,
<code>'BLOB'</code>,
<code>'INTEGER'</code>,
and <code>'FLOATING'</code>
types, so in those cases the translator signatures are very simple.
The signatures for
<code>'FIXED'</code>,
<code>'DATE'</code>,
<code>'TIME'</code>,
and <code>'TIMESTAMP'</code>
are not as simple because Python (before 2.3) lacks native types to
represent these values with both precision <em>and</em> convenience.
KInterbasDB handles <code>'FIXED'</code> values internally as scaled
integers; the date and time types as tuples.
</p>
<p class="textParagraph">
KInterbasDB itself uses translators implemented according to the rules in
the table below; the code for these reference translators can be found
in the Python modules named <code>kinterbasdb.typeconv_*</code>
(see the
<a href="#adv_param_conv_dynamic_type_translation_tbl_ref_trans">table</a>
in the previous section for details).
</p>
<table style="margin-left: 1em;">
<tr>
<td style="font-size: 105%; font-style: italic; font-weight: bold;">
<a name="adv_param_conv_dynamic_type_translation_tbl_signatures">
Signature Specifications for Input and Output Translators
</a>
</td>
</tr>
<tr>
<td>
<table border="1">
<thead style="background-color: #EEEEEE; font-weight: bold;">
<tr>
<td style="width: 6em;">Translator Key</td>
<td>Input Translator Argument/Return Value Signature</td>
<td>Output Translator Signature</td>
</tr>
</thead>
<tr>
<td>
<code>'TEXT'</code><br><br>
<span style="font-size: 80%">
(for <code>CHAR</code>/<code>VARCHAR</code> fields
with character sets <code>NONE</code>, <code>OCTETS</code>,
or <code>ASCII</code>)
</span>
</td>
<td>Args: a single Python <code>str</code>ing argument
(or <code>None</code>)
<br><br>
Returns: a single Python <code>str</code>ing
</td>
<td>Same signature as input translator, except that return value is not constrained.</td>
</tr>
<tr>
<td>
<code>'TEXT_UNICODE'</code><br><br>
<span style="font-size: 80%">
(for <code>CHAR</code>/<code>VARCHAR</code> fields
with character sets other than <code>NONE</code>, <code>OCTETS</code>,
or <code>ASCII</code>)
</span>
</td>
<td>Args:
a single Python 2-tuple argument containing a Python <code>unicode</code>
or <code>str</code> object (or <code>None</code>) in the first element;
the database character set code in the second element (the tuple is
of the form <code>(val, dbCharacterSetCode)</code>).
<br><br>
The database character set codes (which are integers) are defined on
pages 221-225 of the
<a href="#ref_ib6_docs">Interbase® 6 Data Definition Guide</a>.
The module <code>kinterbasdb.typeconv_text_unicode</code> contains a
dictionary named <code>DB_TO_PYTHON_ENCODING_MAP</code> that maps database
character set codes to Python codec names. For example, the database
character set <code>UNICODE_FSS</code> has code <code>3</code>;
<code>kinterbasdb.typeconv_text_unicode.DB_TO_PYTHON_ENCODING_MAP[3]</code>
is <code>'utf_8'</code>, the name of a Python codec that can be passed to
the <code>encode</code>/<code>decode</code> methods of
<code>unicode</code>/<code>str</code>.
<br><br>
Returns: a Python <code>str</code> object containing the
<span style="font-weight: bold; text-decoration: underline;">en</span>coded
representation of the incoming value (typically computed
via <code>val.encode</code>).
</td>
<td style="vertical-align: top;">
Args:
a single Python 2-tuple argument containing a Python <code>str</code>
object (or <code>None</code>) in the first element; the database
character set code in the second element (the tuple is
of the form <code>(val, dbCharacterSetCode)</code>).
<code>val</code> contains the encoded representation of the Unicode string.
<br><br>
Returns: a Python <code>unicode</code> object containing the
<span style="font-weight: bold; text-decoration: underline;">de</span>coded
representation of the outgoing value (typically computed
via <code>val.decode</code>).
</td>
</tr>
<tr>
<td><code>'BLOB'</code></td>
<td>Same signature as that of <code>'TEXT'</code>.</td>
<td>Same signature as input translator, except that return value is not constrained.</td>
</tr>
<tr>
<td><code>'INTEGER'</code></td>
<td>Args: a single Python <code>int</code> argument
(or <code>None</code>)
<br><br>
Returns: a single Python <code>int</code>
</td>
<td>Same signature as input translator, except that return value is not constrained.</td>
</tr>
<tr>
<td><code>'FLOATING'</code></td>
<td>Args: a single Python <code>float</code> argument
(or <code>None</code>)<br>
Returns: a single Python <code>float</code>
</td>
<td>Same signature as input translator, except that return value is not constrained.</td>
</tr>
<tr>
<td><code>'FIXED'</code></td>
<td>Args: a single Python 2-tuple argument containing a scaled Python
integer in the first element and the scale factor in the second
element (the tuple is of the form <code>(val, scale)</code>).
<br><br>
Returns: a single Python integer, scaled appropriately
</td>
<td>Same signature as input translator, except that return value is not constrained.</td>
</tr>
<tr>
<td><code>'DATE'</code></td>
<td>Args: an instance of the chosen date type (such as Python 2.3's
<code>datetime.date</code>) or <code>None</code>
<br><br>
Returns: a single Python 3-tuple of the form
<code>(year, month, day)</code>
</td>
<td>Args: a single Python 3-tuple of the form
<code>(year, month, day)</code>
(or <code>None</code> if the database field was <code>NULL</code>)
<br><br>
Return value is not constrained.
</td>
</tr>
<tr>
<td><code>'TIME'</code></td>
<td>Args: an instance of the chosen time type (such as Python 2.3's
<code>datetime.time</code>) or <code>None</code>
<br><br>
Returns: a single Python 3-tuple of the form
<code>(hour, minute, second)</code>
</td>
<td>Args: a single Python 3-tuple of the form
<code>(hour, minute, second)</code>
(or <code>None</code> if the database field was <code>NULL</code>).
<br><br>
Return value is not constrained.
</td>
</tr>
<tr>
<td><code>'TIMESTAMP'</code></td>
<td>Args: an instance of the chosen time type (such as Python 2.3's
<code>datetime.datetime</code>) or <code>None</code>
<br><br>
Returns: a single Python 6-tuple of the form
<code>(year, month, day, hour, minute, second)</code>
</td>
<td>Args: a single Python 3-tuple of the form
<code>(year, month, day, hour, minute, second)</code>.
(or <code>None</code> if the database field was <code>NULL</code>).
<br><br>
Return value is not constrained.
</td>
</tr>
</table>
</td>
</tr>
</table>
<br><br>
<a name="adv_param_conv_dynamic_type_translation_example">
<h4>Example Programs</h4>
</a>
<a name="adv_param_conv_dynamic_type_translation_example_datetime">
<h5>DATE/TIME/TIMESTAMP</h5>
</a>
<pre class="codeBlock">
<FONT COLOR="#0000ff">import</FONT> datetime <FONT COLOR="#32a532"># Python 2.3 standard library module</FONT>
<FONT COLOR="#0000ff">import</FONT> kinterbasdb
<FONT COLOR="#0000ff">import</FONT> kinterbasdb.typeconv_datetime_stdlib <FONT COLOR="#0000ff">as</FONT> tc_dt
<FONT COLOR="#0000ff">def</FONT> <FONT COLOR="#000066">connect</FONT>(<FONT COLOR="#7d0000">*</FONT>args, <FONT COLOR="#7d0000">**</FONT>kwargs):
<FONT COLOR="#404040">"""</FONT>
<FONT COLOR="#404040"> This wrapper around kinterbasdb.connect creates connections that use</FONT>
<FONT COLOR="#404040"> the datetime module (which entered the standard library in Python 2.3)</FONT>
<FONT COLOR="#404040"> for both input and output of DATE, TIME, and TIMESTAMP database fields.</FONT>
<FONT COLOR="#404040"> This wrapper simply registers kinterbasdb's official date/time</FONT>
<FONT COLOR="#404040"> translators for the datetime module, which reside in the</FONT>
<FONT COLOR="#404040"> kinterbasdb.typeconv_datetime_stdlib module.</FONT>
<FONT COLOR="#404040"> An equivalent set of translators for mx.DateTime (which kinterbasdb</FONT>
<FONT COLOR="#404040"> uses by default for backward compatibility) resides in the</FONT>
<FONT COLOR="#404040"> kinterbasdb.typeconv_datetime_mx module.</FONT>
<FONT COLOR="#404040"> Note that because cursors inherit their connection's dynamic type</FONT>
<FONT COLOR="#404040"> translation settings, cursors created upon connections returned by this</FONT>
<FONT COLOR="#404040"> function will also use the datetime module.</FONT>
<FONT COLOR="#404040"> """</FONT>
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(<FONT COLOR="#7d0000">*</FONT>args, <FONT COLOR="#7d0000">**</FONT>kwargs)
con.<FONT COLOR="#000066">set_type_trans_in</FONT>({
<FONT COLOR="#8f8c47">'DATE'</FONT>: tc_dt.date_conv_in,
<FONT COLOR="#8f8c47">'TIME'</FONT>: tc_dt.time_conv_in,
<FONT COLOR="#8f8c47">'TIMESTAMP'</FONT>: tc_dt.timestamp_conv_in,
})
con.<FONT COLOR="#000066">set_type_trans_out</FONT>({
<FONT COLOR="#8f8c47">'DATE'</FONT>: tc_dt.date_conv_out,
<FONT COLOR="#8f8c47">'TIME'</FONT>: tc_dt.time_conv_out,
<FONT COLOR="#8f8c47">'TIMESTAMP'</FONT>: tc_dt.timestamp_conv_out,
})
<FONT COLOR="#0000ff">return</FONT> con
<FONT COLOR="#0000ff">def</FONT> <FONT COLOR="#000066">_test</FONT>():
con <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
cur <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
<FONT COLOR="#32a532"># Retrieve the current timestamp of the database server.</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select current_timestamp from rdb$database"</FONT>)
curStamp <FONT COLOR="#7d0000">=</FONT> cur.<FONT COLOR="#000066">fetchone</FONT>()[<FONT COLOR="#666600">0</FONT>]
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'The type of curStamp is'</FONT>, <FONT COLOR="#4343b8">type</FONT>(curStamp)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'curStamp is'</FONT>, curStamp
<FONT COLOR="#32a532"># Create a test table with a single TIMESTAMP column.</FONT>
con.<FONT COLOR="#000066">execute_immediate</FONT>(<FONT COLOR="#8f8c47">"recreate table test_stamp (a timestamp)"</FONT>)
con.<FONT COLOR="#000066">commit</FONT>()
<FONT COLOR="#32a532"># Insert a timestamp into the database, then retrieve it.</FONT>
py23StandardLibTimestamp <FONT COLOR="#7d0000">=</FONT> datetime.datetime.<FONT COLOR="#000066">now</FONT>()
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"insert into test_stamp values (?)"</FONT>, (py23StandardLibTimestamp,))
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select * from test_stamp"</FONT>)
curStamp <FONT COLOR="#7d0000">=</FONT> cur.<FONT COLOR="#000066">fetchone</FONT>()[<FONT COLOR="#666600">0</FONT>]
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'The type of curStamp is'</FONT>, <FONT COLOR="#4343b8">type</FONT>(curStamp)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'curStamp is'</FONT>, curStamp
<FONT COLOR="#0000ff">if</FONT> <FONT COLOR="#0066a0">__name__</FONT> <FONT COLOR="#7d0000">==</FONT> <FONT COLOR="#8f8c47">'__main__'</FONT>:
<FONT COLOR="#000066">_test</FONT>()
</pre>
<p class="textParagraph">
Sample output:
</p>
<pre class="programOutputBlock" style="margin-top: 0px; margin-bottom: 1.7em;">
The type of curStamp is <type 'datetime.datetime'>
curStamp is 2003-05-20 03:55:42
The type of stamp is <type 'datetime.datetime'>
stamp is 2003-05-20 03:55:42
</pre>
<a name="adv_param_conv_dynamic_type_translation_example_fixed">
<h5>FIXED</h5>
</a>
<pre class="codeBlock">
<FONT COLOR="#32a532"># Third-party fixedpoint module from</FONT>
<FONT COLOR="#32a532"># http://fixedpoint.sourceforge.net</FONT>
<FONT COLOR="#0000ff">import</FONT> fixedpoint <FONT COLOR="#0000ff">as</FONT> fp
<FONT COLOR="#0000ff">import</FONT> kinterbasdb
<FONT COLOR="#0000ff">import</FONT> kinterbasdb.typeconv_fixed_fixedpoint <FONT COLOR="#0000ff">as</FONT> tc_fp
<FONT COLOR="#0000ff">def</FONT> <FONT COLOR="#000066">connect</FONT>(<FONT COLOR="#7d0000">*</FONT>args, <FONT COLOR="#7d0000">**</FONT>kwargs):
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(<FONT COLOR="#7d0000">*</FONT>args, <FONT COLOR="#7d0000">**</FONT>kwargs)
con.<FONT COLOR="#000066">set_type_trans_in</FONT>({
<FONT COLOR="#8f8c47">'FIXED'</FONT>: tc_fp.fixed_conv_in_precise,
})
con.<FONT COLOR="#000066">set_type_trans_out</FONT>({
<FONT COLOR="#8f8c47">'FIXED'</FONT>: tc_fp.fixed_conv_out_precise,
})
<FONT COLOR="#0000ff">return</FONT> con
<FONT COLOR="#0000ff">def</FONT> <FONT COLOR="#000066">_test</FONT>():
con <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
<FONT COLOR="#32a532"># Create a simple test table.</FONT>
con.<FONT COLOR="#000066">execute_immediate</FONT>(<FONT COLOR="#8f8c47">"recreate table test (a numeric(18,4))"</FONT>)
con.<FONT COLOR="#000066">commit</FONT>()
cur <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
<FONT COLOR="#32a532"># Insert a FixedPoint object.</FONT>
inVal <FONT COLOR="#7d0000">=</FONT> fp.<FONT COLOR="#000066">FixedPoint</FONT>(<FONT COLOR="#8f8c47">'1.2345'</FONT>, <FONT COLOR="#666600">4</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'The type of inVal is '</FONT>, <FONT COLOR="#4343b8">type</FONT>(inVal)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'inVal is '</FONT>, inVal
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"insert into test values (?)"</FONT>, (inVal,))
<FONT COLOR="#32a532"># Retrieve the fixed point value.</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select a from test"</FONT>)
outVal <FONT COLOR="#7d0000">=</FONT> cur.<FONT COLOR="#000066">fetchone</FONT>()[<FONT COLOR="#666600">0</FONT>]
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'The type of outVal is'</FONT>, <FONT COLOR="#4343b8">type</FONT>(outVal)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'outVal is'</FONT>, outVal
<FONT COLOR="#0000ff">if</FONT> <FONT COLOR="#0066a0">__name__</FONT> <FONT COLOR="#7d0000">==</FONT> <FONT COLOR="#8f8c47">'__main__'</FONT>:
<FONT COLOR="#000066">_test</FONT>()
</pre>
<p class="textParagraph">
Sample output:
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
The type of inVal is <class 'fixedpoint.FixedPoint'>
inVal is 1.2345
The type of outVal is <class 'fixedpoint.FixedPoint'>
outVal is 1.2345
</pre>
<br>
<a name="adv_param_conv_dynamic_type_translation_deferred_loading">
<h4>Deferred Loading of Dynamic Type Translators</h4>
</a>
<p class="textParagraph">
In versions of KInterbasDB prior to 3.1_pre5,
there was a difficulty due to backward compatibility constraints: KInterbasDB
would <em>unconditionally</em> import the <code>mx.DateTime</code> module
initially, even if the client programmer did not intend to use it.
Although the advent of dynamic type translation <em>technically</em> obviated
KInterbasDB's dependency on the <code>mx</code> package, KInterbasDB still
required that the <code>mx</code> package be available due to the
aforementioned unconditional import.
</p>
<p class="textParagraph">
KInterbasDB 3.1_pre5 introduces a workaround: it defers the loading of the
dynamic type translators so that the client programmer can forestall an
attempt to import third-party modules he has no intention of using.
The new <code>kinterbasdb.init</code> function takes a keyword argument
<code>type_conv</code>, which controls KInterbasDB's initial choice of
type translators. <code>type_conv</code> can be either an integer or an
object that has all of the attributes named in
<code>kinterbasdb.BASELINE_TYPE_TRANSLATION_FACILITIES</code> (an example
of such an object is the module <code>kinterbasdb.typeconv_backcompat</code>).
If <code>type_conv</code> is an integer, it will cause KInterbasDB to use one
of the following predefined type translator configurations:
</p>
<style type="text/css">
td.num {
font-size: 110%;
text-align: right;
vertical-align: top;
}
p.explanation {
margin-top: 0em;
margin-bottom: 0.4em;
}
</style>
<table border="1" style="margin-left: 1em;">
<tr style="background-color: #EEEEEE; font-weight: bold; vertical-align: top;">
<td>
<a name="adv_param_conv_dynamic_type_translation_tbl_convenience_codes">
<code>type_conv</code> integer "convenience code"
</a>
</td>
<td>Resulting translator configuration</td>
</tr>
<tr>
<td class="num">0</td>
<td>
<p class="explanation">
Minimal type translators that represent
date/time values as <code>tuple</code>s
and fixed point values as either
<code>float</code>s
or scaled <code>int</code>egers,
depending on the connection's
<a href="#db_api_extensions_and_caveats_precision_mode"><code>precision_mode</code></a>.
</p>
<p class="explanation">
Unicode values are not encoded or decoded automatically.
</p>
<p class="explanation">
Implemented by the <code>kinterbasdb.typeconv_naked</code> module.
</p>
</td>
</tr>
<tr>
<td class="num">
1
<br><span style="font-size: 85%">(default)</span>
</td>
<td>
<p class="explanation">
Backward-compatible type translators that represent
date/time values via the <code>mx.DateTime</code> module
and fixed point values as either
<code>float</code>s
or scaled <code>int</code>egers,
depending on the connection's
<a href="#db_api_extensions_and_caveats_precision_mode"><code>precision_mode</code></a>.
</p>
<p class="explanation">
Unicode values are not encoded or decoded automatically.
</p>
<p class="explanation">
Implemented by the <code>kinterbasdb.typeconv_backcompat</code> module.
</p>
<p class="explanation">
This configuration, which is the default, perfectly mimics
the type translation behavior of KInterbasDB 3.0.
</p>
</td>
</tr>
<tr>
<td class="num">100</td>
<td>
<p class="explanation">
This translator configuration, which is intended for use with Python 2.3
and later, represents
date/time values via the new standard library module <code>datetime</code>
and fixed point values via the third-party
<a href="#ref_fixedpoint"><code>fixedpoint</code></a>
module.
</p>
<p class="explanation">
Unicode values <em>are</em> encoded and decoded automatically
(see <a href="#faq_fep_unicode">this FAQ</a> for more info).
</p>
<p class="explanation">
Implemented by the <code>kinterbasdb.typeconv_23plus</code> module.
</p>
</td>
</tr>
</table>
<p class="textParagraph">
These integer type conversion codes are defined <em>solely</em> for convenience.
The same functionality is available via the object variant of
<code>type_conv</code>, but setting it up is more laborious for typical
translator configurations.
</p>
<p class="textParagraph">
It is anticipated that Python 2.4 or 2.5 will introduce into the standard
library a type capable of handling decimal fractions elegantly and precisely.
For convenience, a set of type translators will be added to the official
KInterbasDB distribution to support it. At that time, the combination of date/time handling via the
standard library <code>datetime</code> module and fixed point handling via
the standard library decimal module will become the "ideal" translator
configuration.
For the sake of backward compatibility, the integer convenience code
<code>type_conv=100</code> will not be changed to use the stdlib decimal
module; rather, a new code such as <code>type_conv=101</code> will be added.
</p>
<a name="adv_param_conv_dynamic_type_translation_deferred_loading_backcompat">
<h4 style="margin-left: 1em;">Deferred Loading: Backward Compatibility Issues</h4>
</a>
<p class="textParagraph">
The deferred type translator loading scheme introduced in KInterbasDB 3.1_pre5
goes to great lengths to maintain backward compatibility.
If the client programmer does not call <code>kinterbasdb.init</code>,
KInterbasDB will implicitly initialize itself in a backward-compatible manner
(<code>type_conv=1</code>) the first time one of its public functions is called
or one of its public classes is instantiated.
</p>
<p class="textParagraph">
The only known backward incompatibility is this:
the DB API type comparison singleton <code>DATETIME</code> will not compare
equal to any type until the <code>kinterbasdb.init</code> function has been
called (whether explicitly or implicitly).
After <code>kinterbasdb.init</code> has been called, <code>DATETIME</code>
will compare equal to the date, time, and timestamp types that were loaded.
</p>
<p class="textParagraph">
This issue should affect hardly any existing KInterbasDB-based programs.
</p>
<a name="adv_param_conv_dynamic_type_translation_deferred_loading_example">
<h4 style="margin-left: 1em;">Deferred Loading: Example Program That Uses <code>kinterbasdb.init</code></h4>
</a>
<pre class="codeBlock">
<FONT COLOR="#0000ff">import</FONT> datetime, os.path, string, sys
<FONT COLOR="#32a532"># Third-party fixedpoint module from http://fixedpoint.sourceforge.net</FONT>
<FONT COLOR="#0000ff">import</FONT> fixedpoint
<FONT COLOR="#0000ff">import</FONT> kinterbasdb
kinterbasdb.<FONT COLOR="#000066">init</FONT>(type_conv<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#666600">100</FONT>)
<FONT COLOR="#32a532"># This program never imports mx.DateTime:</FONT>
<FONT COLOR="#0000ff">assert</FONT> <FONT COLOR="#8f8c47">'mx'</FONT> <FONT COLOR="#0000ff">not</FONT> <FONT COLOR="#0000ff">in</FONT> sys.modules
<FONT COLOR="#0000ff">def</FONT> <FONT COLOR="#000066">test</FONT>():
dbFilename <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#8f8c47">'/temp/test_deferred_1.db'</FONT>
<FONT COLOR="#000066">prepareTestDatabase</FONT>(dbFilename)
<FONT COLOR="#32a532"># Connect with character set UNICODE_FSS, to match the default character set</FONT>
<FONT COLOR="#32a532"># of the test database.</FONT>
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT>dbFilename, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>,
charset<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'UNICODE_FSS'</FONT>
)
<FONT COLOR="#0000ff">assert</FONT> con.charset <FONT COLOR="#7d0000">==</FONT> <FONT COLOR="#8f8c47">'UNICODE_FSS'</FONT>
cur <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
<FONT COLOR="#32a532"># Create a test table.</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#404040">"""</FONT>
<FONT COLOR="#404040"> create table test (</FONT>
<FONT COLOR="#404040"> a numeric(18,2),</FONT>
<FONT COLOR="#404040"> b date,</FONT>
<FONT COLOR="#404040"> c time,</FONT>
<FONT COLOR="#404040"> d timestamp,</FONT>
<FONT COLOR="#404040"> e varchar(50), /* Defaults to character set UNICODE_FSS. */</FONT>
<FONT COLOR="#404040"> f varchar(50), /* Defaults to character set UNICODE_FSS. */</FONT>
<FONT COLOR="#404040"> g varchar(50) character set ASCII</FONT>
<FONT COLOR="#404040"> )</FONT>
<FONT COLOR="#404040"> """</FONT>)
con.<FONT COLOR="#000066">commit</FONT>()
<FONT COLOR="#32a532"># Create an input value for each field in the test table.</FONT>
<FONT COLOR="#32a532"># Notice that the DB API date/time constructors in kinterbasdb generate</FONT>
<FONT COLOR="#32a532"># datetime-based objects instead of mx-based objects because of our earlier</FONT>
<FONT COLOR="#32a532"># call to kinterbasdb.init(type_conv=100).</FONT>
aIn <FONT COLOR="#7d0000">=</FONT> fixedpoint.<FONT COLOR="#000066">FixedPoint</FONT>(<FONT COLOR="#8f8c47">'4.53'</FONT>, <FONT COLOR="#666600">2</FONT>)
bIn <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">Date</FONT>(<FONT COLOR="#666600">2004</FONT>,<FONT COLOR="#666600">1</FONT>,<FONT COLOR="#666600">4</FONT>)
cIn <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">Time</FONT>(<FONT COLOR="#666600">16</FONT>,<FONT COLOR="#666600">27</FONT>,<FONT COLOR="#666600">59</FONT>)
dIn <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">Timestamp</FONT>(<FONT COLOR="#666600">2004</FONT>,<FONT COLOR="#666600">1</FONT>,<FONT COLOR="#666600">4</FONT>, <FONT COLOR="#666600">16</FONT>,<FONT COLOR="#666600">27</FONT>,<FONT COLOR="#666600">59</FONT>)
eIn <FONT COLOR="#7d0000">=</FONT> u<FONT COLOR="#8f8c47">'Dav\u2211'</FONT> <FONT COLOR="#32a532"># 'Dav' followed by N-Ary Summation symbol</FONT>
fIn <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#8f8c47">'A plain ASCII string destined for a Unicode field.'</FONT>
gIn <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#8f8c47">'Dave'</FONT>
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'-'</FONT> <FONT COLOR="#7d0000">*</FONT> <FONT COLOR="#666600">70</FONT>
inputValues <FONT COLOR="#7d0000">=</FONT> (aIn, bIn, cIn, dIn, eIn, fIn, gIn)
<FONT COLOR="#000066">reportValues</FONT>(<FONT COLOR="#8f8c47">'In'</FONT>, inputValues)
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"insert into test values (?,?,?,?,?,?,?)"</FONT>, inputValues)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'-'</FONT> <FONT COLOR="#7d0000">*</FONT> <FONT COLOR="#666600">70</FONT>
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select a,b,c,d,e,f,g from test"</FONT>)
(aOut, bOut, cOut, dOut, eOut, fOut, gOut) <FONT COLOR="#7d0000">=</FONT> outputValues <FONT COLOR="#7d0000">=</FONT> cur.<FONT COLOR="#000066">fetchone</FONT>()
<FONT COLOR="#000066">reportValues</FONT>(<FONT COLOR="#8f8c47">'Out'</FONT>, outputValues)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'-'</FONT> <FONT COLOR="#7d0000">*</FONT> <FONT COLOR="#666600">70</FONT>
<FONT COLOR="#32a532"># Notice that all values made the journey to and from the database intact.</FONT>
<FONT COLOR="#0000ff">assert</FONT> inputValues <FONT COLOR="#7d0000">==</FONT> outputValues
<FONT COLOR="#32a532"># Notes about Unicode handling:</FONT>
<FONT COLOR="#32a532">#</FONT>
<FONT COLOR="#32a532"># Upon input, the Python unicode object eIn was encoded transparently for</FONT>
<FONT COLOR="#32a532"># storage in TEST.E (a VARCHAR field with character set UNICODE_FSS (that</FONT>
<FONT COLOR="#32a532"># is, UTF-8)). Upon output, the UNICODE_FSS value in TEST.E was decoded</FONT>
<FONT COLOR="#32a532"># transparently into the Python unicode object eOut.</FONT>
<FONT COLOR="#32a532">#</FONT>
<FONT COLOR="#32a532"># TEST.F accepted a Python str object even though it's a Unicode field.</FONT>
<FONT COLOR="#32a532"># The output value fOut is a Python unicode object rather than a str like</FONT>
<FONT COLOR="#32a532"># fIn, but</FONT>
<FONT COLOR="#0000ff">assert</FONT> fIn <FONT COLOR="#7d0000">==</FONT> fOut
<FONT COLOR="#32a532"># , even though</FONT>
<FONT COLOR="#0000ff">assert</FONT> <FONT COLOR="#4343b8">type</FONT>(fIn) <FONT COLOR="#7d0000">!=</FONT> <FONT COLOR="#4343b8">type</FONT>(fOut)
<FONT COLOR="#32a532">#</FONT>
<FONT COLOR="#32a532"># TEST.G, a VARCHAR field with an ASCII character set, accepted and returned</FONT>
<FONT COLOR="#32a532"># a Python str object, as ever.</FONT>
<FONT COLOR="#0000ff">def</FONT> <FONT COLOR="#000066">reportValues</FONT>(direction, values):
<FONT COLOR="#0000ff">for</FONT> (val, c) <FONT COLOR="#0000ff">in</FONT> <FONT COLOR="#4343b8">zip</FONT>(values, string.ascii_lowercase[:<FONT COLOR="#4343b8">len</FONT>(values)]):
varName <FONT COLOR="#7d0000">=</FONT> c <FONT COLOR="#7d0000">+</FONT> direction
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'%s has type %s, value\n %s'</FONT> <FONT COLOR="#7d0000">%</FONT> (varName, <FONT COLOR="#4343b8">type</FONT>(val), <FONT COLOR="#4343b8">repr</FONT>(val))
<FONT COLOR="#0000ff">def</FONT> <FONT COLOR="#000066">prepareTestDatabase</FONT>(dbFilename):
<FONT COLOR="#32a532"># Delete the test database if an old copy is already present.</FONT>
<FONT COLOR="#0000ff">if</FONT> os.path.<FONT COLOR="#000066">isfile</FONT>(dbFilename):
conOld <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT>dbFilename, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
conOld.<FONT COLOR="#000066">drop_database</FONT>()
<FONT COLOR="#32a532"># Create the test database afresh.</FONT>
kinterbasdb.<FONT COLOR="#000066">create_database</FONT>(<FONT COLOR="#404040">"""</FONT>
<FONT COLOR="#404040"> create database '%s'</FONT>
<FONT COLOR="#404040"> user 'sysdba' password 'pass'</FONT>
<FONT COLOR="#404040"> default character set UNICODE_FSS</FONT>
<FONT COLOR="#404040"> """</FONT> <FONT COLOR="#7d0000">%</FONT> dbFilename
)
<FONT COLOR="#0000ff">if</FONT> <FONT COLOR="#0066a0">__name__</FONT> <FONT COLOR="#7d0000">==</FONT> <FONT COLOR="#8f8c47">'__main__'</FONT>:
<FONT COLOR="#000066">test</FONT>()
</pre>
<p class="textParagraph">
Sample output:
</p>
<pre class="programOutputBlock">
----------------------------------------------------------------------
aIn has type <class 'fixedpoint.FixedPoint'>, value
FixedPoint('4.53', 2)
bIn has type <type 'datetime.date'>, value
datetime.date(2004, 1, 4)
cIn has type <type 'datetime.time'>, value
datetime.time(16, 27, 59)
dIn has type <type 'datetime.datetime'>, value
datetime.datetime(2004, 1, 4, 16, 27, 59)
eIn has type <type 'unicode'>, value
u'Dav\u2211'
fIn has type <type 'str'>, value
'A plain ASCII string destined for a Unicode field.'
gIn has type <type 'str'>, value
'Dave'
----------------------------------------------------------------------
aOut has type <class 'fixedpoint.FixedPoint'>, value
FixedPoint('4.53', 2)
bOut has type <type 'datetime.date'>, value
datetime.date(2004, 1, 4)
cOut has type <type 'datetime.time'>, value
datetime.time(16, 27, 59)
dOut has type <type 'datetime.datetime'>, value
datetime.datetime(2004, 1, 4, 16, 27, 59)
eOut has type <type 'unicode'>, value
u'Dav\u2211'
fOut has type <type 'unicode'>, value
u'A plain ASCII string destined for a Unicode field.'
gOut has type <type 'str'>, value
'Dave'
----------------------------------------------------------------------
</pre>
<br>
<a name="adv_param_conv_database_arrays">
<h3>Database Arrays</h3>
</a>
<p class="textParagraph">
KInterbasDB converts database arrays <em>from</em> Python sequences (except
strings) on input; <em>to</em> Python lists on output.
On input, the Python sequence must be nested appropriately if the array
field is multi-dimensional, and the incoming sequence must not
fall short of its maximum possible length (it will not be "padded"
implicitly--see below).
On output, the lists will be nested if the database array has multiple dimensions.
</p>
<p class="textParagraph">
Database arrays have no place in a purely relational data model, which
requires that data values be <em>atomized</em> (that is, every value stored
in the database must be reduced to elementary, non-decomposable parts).
The Interbase®/Firebird implementation of database arrays,
like that of most relational database engines that support this data type,
is fraught with limitations.
</p>
<p class="textParagraph">
First of all, the database engine claims to support up to 16 dimensions, but
actually malfunctions catastrophically above 10 (this bug is fixed in
Firebird 1.5-RC1 and later, thanks to Dmitry Yemanov).
</p>
<p class="textParagraph">
Database arrays are of fixed size, with a predeclared number of dimensions
and number of elements per dimension. Individual array elements cannot
be set to <code>NULL</code>/<code>None</code>,
so the mapping between Python lists (which have dynamic length and are
therefore <em>not</em> normally "padded" with dummy values) and non-trivial
database arrays is clumsy.
</p>
<p class="textParagraph">
Stored procedures cannot have array parameters.
</p>
<p class="textParagraph">
Finally, many interface libraries, GUIs, and even the isql command line
utility do not support database arrays.
</p>
<p class="textParagraph">
In general, it is preferable to avoid using database arrays unless you
have a compelling reason.
</p>
<a name="adv_param_conv_database_arrays_example">
<h4>Example Program</h4>
</a>
<p class="textParagraph">
The following example program inserts a 3-d array (nested Python list) into a
single database field, then retrieves it.
</p>
<pre class="codeBlock" style="margin-top: 0px;">
<FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
con.<FONT COLOR="#000066">execute_immediate</FONT>(<FONT COLOR="#8f8c47">"recreate table array_table (a int[3,4])"</FONT>)
con.<FONT COLOR="#000066">commit</FONT>()
cur <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
arrayIn <FONT COLOR="#7d0000">=</FONT> [
[<FONT COLOR="#666600">1</FONT>, <FONT COLOR="#666600">2</FONT>, <FONT COLOR="#666600">3</FONT>, <FONT COLOR="#666600">4</FONT>],
[<FONT COLOR="#666600">5</FONT>, <FONT COLOR="#666600">6</FONT>, <FONT COLOR="#666600">7</FONT>, <FONT COLOR="#666600">8</FONT>],
[<FONT COLOR="#666600">9</FONT>,<FONT COLOR="#666600">10</FONT>,<FONT COLOR="#666600">11</FONT>,<FONT COLOR="#666600">12</FONT>]
]
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'arrayIn: %s'</FONT> <FONT COLOR="#7d0000">%</FONT> arrayIn
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"insert into array_table values (?)"</FONT>, (arrayIn,))
cur.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select a from array_table"</FONT>)
arrayOut <FONT COLOR="#7d0000">=</FONT> cur.<FONT COLOR="#000066">fetchone</FONT>()[<FONT COLOR="#666600">0</FONT>]
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'arrayOut: %s'</FONT> <FONT COLOR="#7d0000">%</FONT> arrayOut
con.<FONT COLOR="#000066">commit</FONT>()
</pre>
<p class="textParagraph">
Output:
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
arrayIn: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
arrayOut: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
</pre>
<br>
<hr>
<br>
<a name="adv_named_cursors">
<h2>Named Cursors</h2>
</a>
<p class="textParagraph">
The read/write property <code>Cursor.name</code> allows the Python
programmer to perform scrolling <code>UPDATE</code>s or <code>DELETE</code>s
via the "<code>SELECT ... FOR UPDATE</code>" syntax.
If you don't know what this means, refer to the section of the
<a href="#ref_ib6_docs">Interbase® 6 Language Reference</a>
that covers the <code>SELECT</code> statement (page 139).
The <code>Cursor.name</code> property can be ignored entirely if you don't
need to use it.
</p>
<a name="adv_named_cursors_example">
<h4>Example Program</h4>
</a>
<pre class="codeBlock" style="margin-top: 0px;">
<FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
curScroll <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
curUpdate <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">cursor</FONT>()
curScroll.<FONT COLOR="#000066">execute</FONT>(<FONT COLOR="#8f8c47">"select city from addresses <strong>for update</strong>"</FONT>)
curScroll.name <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#8f8c47">'city_scroller'</FONT>
update <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#8f8c47">"update addresses set city=? <strong>where current of</strong> "</FONT> <FONT COLOR="#7d0000">+</FONT> curScroll.name
<FONT COLOR="#0000ff">for</FONT> (city,) <FONT COLOR="#0000ff">in</FONT> curScroll:
city <FONT COLOR="#7d0000">=</FONT> ... <FONT COLOR="#32a532"># make some changes to city</FONT>
curUpdate.<FONT COLOR="#000066">execute</FONT>( update, (city,) )
con.<FONT COLOR="#000066">commit</FONT>()
</pre>
<br>
<hr>
<br>
<a name="adv_prog_maint">
<h2>Programmatic Server, Database, and User Maintenance</h2>
</a>
<a name="adv_prog_maint_servapi">
<h3>Services API</h3>
</a>
<p class="textParagraph">
Database server maintenance tasks such as user management, load monitoring,
and database backup have traditionally been automated by scripting
the command-line tools <code>gbak</code>, <code>gfix</code>, <code>gsec</code>,
and <code>gstat</code>. These utilities are documented in the
<a href="#ref_ib6_docs">Interbase® 6 Operations Guide</a> (see
"Overview of command-line tools", page 28).
</p>
<p class="textParagraph">
The API presented to the client programmer by these utilities is inelegant
because they are, after all, command-line tools rather than native components
of the client language. To address this problem, Interbase® 6 introduced
a facility called the Services API, which exposes a uniform interface to the
administrative functionality of the traditional command-line tools.
</p>
<p class="textParagraph">
The native Services API, though consistent, is much lower-level than a
Pythonic API. If the native version were exposed directly, accomplishing
a given task would probably require more Python code than scripting the
traditional command-line tools. For this reason, KInterbasDB presents its own
abstraction over the native API via the <code>kinterbasdb.services</code>
module.
</p>
<p class="textParagraph">
</p>
<a name="adv_prog_maint_servapi_connect">
<h4>Establishing Services API Connections</h4>
</a>
<p class="textParagraph">
All Services API operations are performed in the context of a connection to
a specific database server, represented by the
<code>kinterbasdb.services.Connection</code> class.
<code>Connection</code>s are established by calling the
<code>kinterbasdb.services.connect</code> function, which accepts three keyword
arguments: <code>host</code>, <code>user</code>, and <code>password</code>.
<code>host</code> is the network name of the computer on which the database
server is running; <code>user</code> is the name of the database user under
whose authority the maintenance tasks are to be performed;
<code>password</code> is that
user's password. Since maintenance operations are most often initiated by an
administrative user on the same computer as the database server,
<code>host</code> defaults to the local computer, and <code>user</code>
defaults to <code>SYSDBA</code>.
</p>
<p class="textParagraph">
The three calls to <code>kinterbasdb.services.connect</code> in the following
program are equivalent:
</p>
<pre class="codeBlock" style="margin-top: 0px;">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
</pre>
<p class="textParagraph">
A no-argument <code>close</code> method is available to explicitly terminate
a <code>Connection</code>; if this is not invoked, the underlying connection
will be closed implicitly when the <code>Connection</code> object is garbage
collected.
</p>
<a name="adv_prog_maint_servapi_server_config">
<h4>Querying Server Configuration and Activity Levels</h4>
</a>
<h5 class="serviceManagerMethodName">Connection.getServiceManagerVersion</h5>
<p class="textParagraphTight">
To help client programs adapt to version changes, the service manager
exposes its version number as an integer:
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getServiceManagerVersion</FONT>()
</pre>
<p class="textParagraphTight">
Output (on Firebird 1.5.0):
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
2
</pre>
<p class="textParagraph">
<code>kinterbasdb.services</code> is a thick wrapper of the Services
API that can shield its users from changes in the underlying C API, so this
method is unlikely to be useful to the typical Python client programmer.
</p>
<h5 class="serviceManagerMethodName">Connection.getServerVersion</h5>
<p class="textParagraphTight">
The <code>getServerVersion</code> method returns the server's version string:
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getServerVersion</FONT>()
</pre>
<p class="textParagraphTight">
Output (on Firebird 1.5.0/Win32):
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
WI-V1.5.0.4290 Firebird 1.5
</pre>
<p class="textParagraph">
At first glance, the <code>kinterbasdb.services.Connection.getServerVersion</code>
method appears to duplicate the functionality of the
<code>kinterbasdb.Connection.server_version</code> property, but when
working with Firebird, there is a difference.
<code>kinterbasdb.Connection.server_version</code> is based
on a C API call (<code>isc_database_info</code>) that existed long
before the introduction of the Services API in Interbase® 6.
Some programs written before the advent of Firebird test the version number in the return value of
<code>isc_database_info</code>, and refuse to work if it indicates that the
server is too old. Since the first stable version of Firebird
was labeled <code>1.0</code>, this pre-Firebird version testing scheme
incorrectly concludes that (e.g.) Firebird 1.0 is older than
Interbase® 5.0.
</p>
<p class="textParagraph">
Firebird addresses this problem by making
<code>isc_database_info</code> return a "pseudo-Interbase®" version
number, whereas the Services API returns the true Firebird version, as shown:
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:C:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'Interbase-compatible version string:'</FONT>, con.server_version
<FONT COLOR="#0000ff">import</FONT> kinterbasdb.services
svcCon <FONT COLOR="#7d0000">=</FONT> kinterbasdb.services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'Actual Firebird version string: '</FONT>, svcCon.<FONT COLOR="#000066">getServerVersion</FONT>()
</pre>
<p class="textParagraphTight">
Output (on Firebird 1.5.0/Win32):
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
Interbase-compatible version string: WI-V6.3.0.4290 Firebird 1.5
Actual Firebird version string: WI-V1.5.0.4290 Firebird 1.5
</pre>
<h5 class="serviceManagerMethodName">Connection.getArchitecture</h5>
<p class="textParagraphTight">
The <code>getArchitecture</code> method returns platform information for
the server, including hardware architecture and operating system family:
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getArchitecture</FONT>()
</pre>
<p class="textParagraphTight">
Output (on Firebird 1.5.0/Windows 2000):
</p>
<pre class="programOutputBlockTight" style="margin-top: 0px;">
Firebird/x86/Windows NT
</pre>
<p class="textParagraphTight">
Unfortunately, the architecture string is almost useless because its format
is irregular and sometimes outright idiotic, as with Firebird 1.5.0 running
on x86 Linux:
</p>
<pre class="programOutputBlockTight" style="margin-top: 0px;">
Firebird/linux Intel
</pre>
<p class="textParagraphTight">
Magically, Linux becomes a hardware architecture, the ASCII store decides
to hold a 31.92% off sale, and Intel grabs an unfilled
niche in the operating system market.
</p>
<h5 class="serviceManagerMethodName">Connection.getHomeDir</h5>
<p class="textParagraphTight">
The <code>getHomeDir</code> method returns the equivalent of the
<code>RootDirectory</code> setting from <code>firebird.conf</code>:
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getHomeDir</FONT>()
</pre>
<p class="textParagraphTight">
Output (on a particular Firebird 1.5.0/Windows 2000 installation):
</p>
<pre class="programOutputBlockTight">
C:\dev\db\firebird150\
</pre>
<p class="textParagraphTight">
Output (on a particular Firebird 1.5.0/Linux installation):
</p>
<pre class="programOutputBlockTight">
/opt/firebird/
</pre>
<h5 class="serviceManagerMethodName">Connection.getSecurityDatabasePath</h5>
<p class="textParagraphTight">
The <code>getSecurityDatabasePath</code> method returns the location of
the server's core security database, which contains user definitions and
such.
Interbase® and Firebird 1.0 named this database <code>isc4.gdb</code>,
while in Firebird 1.5 and later it's renamed to <code>security.fdb</code>:
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getSecurityDatabasePath</FONT>()
</pre>
<p class="textParagraphTight">
Output (on a particular Firebird 1.5.0/Windows 2000 installation):
</p>
<pre class="programOutputBlockTight">
C:\dev\db\firebird150\security.fdb
</pre>
<p class="textParagraphTight">
Output (on a particular Firebird 1.5.0/Linux installation):
</p>
<pre class="programOutputBlockTight">
/opt/firebird/security.fdb
</pre>
<h5 class="serviceManagerMethodName">Connection.getLockFileDir</h5>
<p class="textParagraphTight">
The database engine
<a href="http://www.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_locking">uses a lock file</a>
to coordinate interprocess communication;
<code>getLockFileDir</code> returns the directory in which that file resides:
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getLockFileDir</FONT>()
</pre>
<p class="textParagraphTight">
Output (on a particular Firebird 1.5.0/Windows 2000 installation):
</p>
<pre class="programOutputBlockTight">
C:\dev\db\firebird150\
</pre>
<p class="textParagraphTight">
Output (on a particular Firebird 1.5.0/Linux installation):
</p>
<pre class="programOutputBlockTight">
/opt/firebird/
</pre>
<h5 class="serviceManagerMethodName">Connection.getCapabilityMask</h5>
<p class="textParagraphTight">
The Services API offers "a bitmask representing the capabilities currently
enabled on the server", but the only available
<a href="#ref_ib6_docs">documentation</a>
for this bitmask suggests that it is "reserved for future implementation".
kinterbasdb exposes this bitmask as a Python <code>int</code> returned from
the <code>getCapabilityMask</code> method.
</p>
<h5 class="serviceManagerMethodName">Connection.getMessageFileDir</h5>
<p class="textParagraphTight">
To support internationalized error messages/prompts, the database engine stores
its messages in a file named <code>interbase.msg</code> (Interbase®
and Firebird 1.0) or <code>firebird.msg</code> (Firebird 1.5 and later).
The directory in which this file resides can be determined with the
<code>getMessageFileDir</code> method.
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getMessageFileDir</FONT>()
</pre>
<p class="textParagraphTight">
Output (on a particular Firebird 1.5.0/Windows 2000 installation):
</p>
<pre class="programOutputBlockTight">
C:\dev\db\firebird150\
</pre>
<p class="textParagraphTight">
Output (on a particular Firebird 1.5.0/Linux installation):
</p>
<pre class="programOutputBlockTight">
/opt/firebird/
</pre>
<h5 class="serviceManagerMethodName">Connection.getConnectionCount</h5>
<p class="textParagraph">
<code>getConnectionCount</code> returns the number of active connections to
databases managed by the server.
This count only includes <em>database</em>
connections (such as open instances of <code>kinterbasdb.Connection</code>),
not <em>services manager</em> connections
(such as open instances of <code>kinterbasdb.services.Connection</code>).
</p>
<pre class="codeBlock">
<FONT COLOR="#0000ff">import</FONT> kinterbasdb, kinterbasdb.services
svcCon <FONT COLOR="#7d0000">=</FONT> kinterbasdb.services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'A:'</FONT>, svcCon.<FONT COLOR="#000066">getConnectionCount</FONT>()
con1 <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:C:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'B:'</FONT>, svcCon.<FONT COLOR="#000066">getConnectionCount</FONT>()
con2 <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:C:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'C:'</FONT>, svcCon.<FONT COLOR="#000066">getConnectionCount</FONT>()
con1.<FONT COLOR="#000066">close</FONT>()
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'D:'</FONT>, svcCon.<FONT COLOR="#000066">getConnectionCount</FONT>()
con2.<FONT COLOR="#000066">close</FONT>()
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'E:'</FONT>, svcCon.<FONT COLOR="#000066">getConnectionCount</FONT>()
</pre>
<p class="textParagraphTight">
On an otherwise inactive server, the example program generates the following
output:
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
A: 0
B: 1
C: 2
D: 1
E: 0
</pre>
<h5 class="serviceManagerMethodName">Connection.getAttachedDatabaseNames</h5>
<p class="textParagraphTight">
<code>getAttachedDatabaseNames</code> returns a list of the names of all
databases to which the server is maintaining at least one connection.
The database names are not guaranteed to be in any particular order.
</p>
<pre class="codeBlock">
<FONT COLOR="#0000ff">import</FONT> kinterbasdb, kinterbasdb.services
svcCon <FONT COLOR="#7d0000">=</FONT> kinterbasdb.services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'A:'</FONT>, svcCon.<FONT COLOR="#000066">getAttachedDatabaseNames</FONT>()
con1 <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:C:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'B:'</FONT>, svcCon.<FONT COLOR="#000066">getAttachedDatabaseNames</FONT>()
con2 <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:C:/temp/test2.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'C:'</FONT>, svcCon.<FONT COLOR="#000066">getAttachedDatabaseNames</FONT>()
con3 <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:C:/temp/test2.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'D:'</FONT>, svcCon.<FONT COLOR="#000066">getAttachedDatabaseNames</FONT>()
con1.<FONT COLOR="#000066">close</FONT>()
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'E:'</FONT>, svcCon.<FONT COLOR="#000066">getAttachedDatabaseNames</FONT>()
con2.<FONT COLOR="#000066">close</FONT>()
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'F:'</FONT>, svcCon.<FONT COLOR="#000066">getAttachedDatabaseNames</FONT>()
con3.<FONT COLOR="#000066">close</FONT>()
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'G:'</FONT>, svcCon.<FONT COLOR="#000066">getAttachedDatabaseNames</FONT>()
</pre>
<p class="textParagraphTight">
On an otherwise inactive server, the example program generates the following
output:
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
A: []
B: ['C:\\TEMP\\TEST.DB']
C: ['C:\\TEMP\\TEST2.DB', 'C:\\TEMP\\TEST.DB']
D: ['C:\\TEMP\\TEST2.DB', 'C:\\TEMP\\TEST.DB']
E: ['C:\\TEMP\\TEST2.DB']
F: ['C:\\TEMP\\TEST2.DB']
G: []
</pre>
<h5 class="serviceManagerMethodName">Connection.getLog</h5>
<p class="textParagraphTight">
The <code>getLog</code> method returns the contents of the server's log file
(named <code>interbase.log</code> by Interbase® and Firebird 1.0;
<code>firebird.log</code> by Firebird 1.5 and later):
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(host<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getLog</FONT>()
</pre>
<p class="textParagraphTight">
Output (on a particular Firebird 1.5.0/Windows 2000 installation):
</p>
<pre class="programOutputBlock" style="margin-top: 0px;">
STALIN (Client) Thu Jun 03 12:01:35 2004
INET/inet_error: send errno = 10054
STALIN (Client) Sun Jun 06 19:21:17 2004
INET/inet_error: connect errno = 10061
</pre>
<a name="adv_prog_maint_servapi_database_stats">
<h4>Querying Database Statistics</h4>
</a>
<h5 class="serviceManagerMethodName">Connection.getStatistics</h5>
<p class="textParagraphTight">
The <code>getStatistics</code> method returns a string containing a printout
in the same format as the output of the <code>gstat</code> command-line
utility. This method has one required parameter, the location of the database
on which to compute statistics, and five optional boolean parameters for
controlling the domain of the statistics.
</p>
<p class="textParagraph">
The section of the
<a href="#ref_ib6_docs">Interbase® 6 Operations Guide</a>
entitled "gstat command-line tool" (page 181)
documents <code>gstat</code>'s command-line options.
Rather than attempting to duplicate that documentation here,
we present a table of equivalence:
</p>
<table border="1" cellpadding="5">
<thead>
<tr style="background-color: #DEDEDE;">
<td><code>gstat</code> command-line option</td>
<td><code>kinterbasdb.services.Connection.getStatistics</code> boolean parameter</td>
</tr>
</thead>
<tr>
<td><code>-header</code></td>
<td><code>showOnlyDatabaseHeaderPages</code></td>
</tr>
<tr>
<td><code>-log</code></td>
<td><code>showOnlyDatabaseLogPages</code></td>
</tr>
<tr>
<td><code>-data</code></td>
<td><code>showUserDataPages</code></td>
</tr>
<tr>
<td><code>-index</code></td>
<td><code>showUserIndexPages</code></td>
</tr>
<tr>
<td><code>-system</code></td>
<td><code>showSystemTablesAndIndexes</code></td>
</tr>
</table>
<p class="textParagraph">
The following example program presents several <code>getStatistics</code>
calls and their <code>gstat</code>-command-line equivalents. In this
context, output is considered "equivalent" even if their are some whitespace
differences. When collecting textual output from the Services API,
kinterbasdb terminates lines with <code>\n</code> regardless of the platform's
convention; <code>gstat</code> is platform-sensitive.
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#32a532"># Equivalent to 'gstat -u sysdba -p masterkey C:/temp/test.db':</FONT>
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getStatistics</FONT>(<FONT COLOR="#8f8c47">'C:/temp/test.db'</FONT>)
<FONT COLOR="#32a532"># Equivalent to 'gstat -u sysdba -p masterkey -header C:/temp/test.db':</FONT>
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getStatistics</FONT>(<FONT COLOR="#8f8c47">'C:/temp/test.db'</FONT>, showOnlyDatabaseHeaderPages<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#0066a0">True</FONT>)
<FONT COLOR="#32a532"># Equivalent to 'gstat -u sysdba -p masterkey -log C:/temp/test.db':</FONT>
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getStatistics</FONT>(<FONT COLOR="#8f8c47">'C:/temp/test.db'</FONT>, showOnlyDatabaseLogPages<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#0066a0">True</FONT>)
<FONT COLOR="#32a532"># Equivalent to 'gstat -u sysdba -p masterkey -data -index -system C:/temp/test.db':</FONT>
<FONT COLOR="#0000ff">print</FONT> con.<FONT COLOR="#000066">getStatistics</FONT>(<FONT COLOR="#8f8c47">'C:/temp/test.db'</FONT>,
showUserDataPages<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#0066a0">True</FONT>,
showUserIndexPages<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#0066a0">True</FONT>,
showSystemTablesAndIndexes<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#0066a0">True</FONT>
)
</pre>
<p class="textParagraphTight">
The output of the example program is not shown here because it is quite long.
</p>
<a name="adv_prog_maint_servapi_backup_restore">
<h4>Backup and Restoration</h4>
</a>
<p class="textParagraph">
KInterbasDB offers convenient programmatic control over database backup and
restoration via the <code>backup</code> and <code>restore</code> methods.
</p>
<p class="textParagraph">
At the time of this writing, released versions of Firebird/Interbase® do
not implement incremental backup, so we can simplistically define
<em>backup</em> as the process of generating and storing an archived replica
of a live database, and <em>restoration</em> as the inverse.
The backup/restoration process exposes numerous parameters, which are properly
documented in
Chapter 7 ("Database Backup and Restore") of the
<a href="#ref_ib6_docs">Interbase® 6 Operations Guide</a>.
The KInterbasDB API to these parameters is presented with minimal
documentation in the sample code below.
</p>
<a name="adv_prog_maint_servapi_backup_restore__backup">
<h5 class="serviceManagerMethodName">Connection.backup</h5>
</a>
<h5 class="serviceManagerMethod_Form">Simplest Form</h5>
<p class="textParagraphTight">
The simplest form of <code>backup</code> creates a single backup file
that contains everything in the database. Although the extension
<code>'.gbk'</code> is conventional, it is not required.
</p>
<pre class="codeBlockNoTop" style="margin-bottom: 0px;">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
backupLog <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">backup</FONT>(<FONT COLOR="#8f8c47">'C:/temp/test.db'</FONT>, <FONT COLOR="#8f8c47">'C:/temp/test_backup.gbk'</FONT>)
<FONT COLOR="#0000ff">print</FONT> backupLog
</pre>
<p class="textParagraphTight" style="margin-bottom: 1em;">
In the example, <code>backupLog</code> is a string containing a
<code>gbak</code>-style log of the backup process. It is too long to
reproduce here.
</p>
<p class="textParagraph">
Although the return value of the <code>backup</code> method is a freeform
log string, <code>backup</code> will raise an exception if there is an error.
For example:
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
<FONT COLOR="#32a532"># Pass an invalid backup path to the engine:</FONT>
backupLog <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">backup</FONT>(<FONT COLOR="#8f8c47">'C:/temp/test.db'</FONT>, <FONT COLOR="#8f8c47">'BOGUS/PATH/test_backup.gbk'</FONT>)
<FONT COLOR="#0000ff">print</FONT> backupLog
</pre>
<pre class="programOutputBlock" style="margin-top: 0px;">
Traceback (most recent call last):
File "adv_services_backup_simplest_witherror.py", line 5, in ?
backupLog = con.backup('C:/temp/test.db', 'BOGUS/PATH/test_backup.gbk')
File "C:\code\projects\kinterbasdb\Kinterbasdb-3.0\build\lib.win32-2.3\kinterbasdb\services.py", line 269, in backup
return self._actAndReturnTextualResults(request)
File "C:\code\projects\kinterbasdb\Kinterbasdb-3.0\build\lib.win32-2.3\kinterbasdb\services.py", line 613, in _actAndReturnTextualResults
self._act(requestBuffer)
File "C:\code\projects\kinterbasdb\Kinterbasdb-3.0\build\lib.win32-2.3\kinterbasdb\services.py", line 610, in _act
return _ksrv.action_thin(self._C_conn, requestBuffer.render())
kinterbasdb.OperationalError: (-902, '_kiservices could not perform the action: cannot open backup file BOGUS/PATH/test_backup.gbk. ')
</pre>
<h5 class="serviceManagerMethod_Form">Multifile Form</h5>
<p class="textParagraphTight">
The database engine has built-in support for splitting the backup into multiple
files, which is useful for circumventing operating system file size limits
or spreading the backup across multiple discs.
</p>
<p class="textParagraph">
KInterbasDB exposes this facility via the <code>Connection.backup</code>
parameters <code>destFilenames</code> and <code>destFileSizes</code>.
<code>destFilenames</code> (the second positional parameter of
<code>Connection.backup</code>) can be either a string (as in the example
above, when creating the backup as a single file) or a sequence of strings
naming each constituent file of the backup.
If <code>destFilenames</code> is a string-sequence with length <code>N</code>,
<code>destFileSizes</code> must be a sequence of integer file sizes
(in bytes) with length <code>N-1</code>. The database engine will constrain
the size of each backup constituent file named in
<code>destFilenames[:-1]</code> to the corresponding size specified in
<code>destFileSizes</code>; any remaining backup data will be placed in the
file name by <code>destFilenames[-1]</code>.
</p>
<p class="textParagraph">
Unfortunately, the database engine does not appear to expose any convenient
means of calculating the total size of a database backup before its creation.
The page size of the database and the number of pages in the database are
available via
<code>kinterbasdb.Connection.database_info(kinterbasdb.isc_info_page_size, 'i')</code>
and
<code>kinterbasdb.Connection.database_info(kinterbasdb.isc_info_db_size_in_pages, 'i')</code>,
respectively, but the size of the backup file is usually smaller than the size
of the database.
</p>
<p class="textParagraph">
There <em>should</em> be no harm in submitting too many constituent specifications; the
engine will write an empty header record into the excess constituents.
However, at the time of this writing, released versions of the database engine
hang the backup task if more than 11 constituents are specified (that is,
if <code>len(destFilenames) > 11</code>).
KInterbasDB does not prevent the programmer from submitting more than 11
constituents, but it does issue a warning.
</p>
<p class="textParagraph">
The following example program directs the engine to split the backup
of the database at <code>'C:/temp/test.db'</code> into
<code>'C:/temp/back01.gbk'</code>, a file 4096 bytes in size,
<code>'C:/temp/back02.gbk'</code>, a file 16384 bytes in size,
and <code>'C:/temp/back03.gbk'</code>, a file containing the remainder
of the backup data.
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
con.<FONT COLOR="#000066">backup</FONT>(<FONT COLOR="#8f8c47">'C:/temp/test.db'</FONT>,
(<FONT COLOR="#8f8c47">'C:/temp/back01.gbk'</FONT>, <FONT COLOR="#8f8c47">'C:/temp/back02.gbk'</FONT>, <FONT COLOR="#8f8c47">'C:/temp/back03.gbk'</FONT>),
destFileSizes<FONT COLOR="#7d0000">=</FONT>(<FONT COLOR="#666600">4096</FONT>, <FONT COLOR="#666600">16384</FONT>)
)
</pre>
<h5 class="serviceManagerMethod_Form">Extended Options</h5>
<p class="textParagraphTight">
In addition to the three parameters documented previously
(positional <code>sourceDatabase</code>,
positional <code>destFilenames</code>,
and keyword <code>destFileSizes</code>),
the <code>Connection.backup</code> method accepts six boolean parameters
that control aspects of the backup process and the backup file output format.
These options are well documented beginning on page 149 of the
<a href="#ref_ib6_docs">Interbase® 6 Operations Guide</a>, so in this
document we present only a table of equivalence between the section caption in
the Interbase® 6 Operations Guide and the name of the boolean keyword
parameter:
</p>
<table border="1" style="margin-left: 1em;">
<thead>
<tr style="background-color: #DEDEDE;">
<td>IB6 Op. Guide Caption</td>
<td><code>Connection.backup</code><br>Parameter Name</td>
<td><code>Connection.backup</code><br>Parameter Default Value</td>
</tr>
</thead>
<tr>
<td>Format</td>
<td><code>transportable</code></td>
<td><code>True</code></td>
</tr>
<tr>
<td>Metadata Only</td>
<td><code>metadataOnly</code></td>
<td><code>False</code></td>
</tr>
<tr>
<td>Garbage Collection</td>
<td><code>garbageCollect</code></td>
<td><code>True</code></td>
</tr>
<tr>
<td>Transactions in Limbo </td>
<td><code>ignoreLimboTransactions</code></td>
<td><code>False</code></td>
</tr>
<tr>
<td>Checksums</td>
<td><code>ignoreChecksums</code></td>
<td><code>False</code></td>
</tr>
<tr>
<td>Convert to Tables</td>
<td><code>convertExternalTablesToInternalTables </code></td>
<td><code>True</code></td>
</tr>
</table>
<a name="adv_prog_maint_servapi_backup_restore__restore">
<h5 class="serviceManagerMethodName" style="margin-top: 1.5em;">Connection.restore</h5>
</a>
<h5 class="serviceManagerMethod_Form">Simplest Form</h5>
<p class="textParagraphTight">
The simplest form of <code>restore</code> creates a single-file database,
regardless of whether the backup data were split across multiple files.
</p>
<pre class="codeBlockNoTop" style="margin-bottom: 0px;">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
restoreLog <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">restore</FONT>(<FONT COLOR="#8f8c47">'C:/temp/test_backup.gbk'</FONT>, <FONT COLOR="#8f8c47">'C:/temp/test_restored.db'</FONT>)
<FONT COLOR="#0000ff">print</FONT> restoreLog
</pre>
<p class="textParagraphTight" style="margin-bottom: 1em;">
In the example, <code>restoreLog</code> is a string containing a
<code>gbak</code>-style log of the restoration process. It is too long to
reproduce here.
</p>
<h5 class="serviceManagerMethod_Form">Multifile Form</h5>
<p class="textParagraphTight">
The database engine has built-in support for splitting the restored database
into multiple files, which is useful for circumventing operating system file
size limits or spreading the database across multiple discs.
</p>
<p class="textParagraph">
KInterbasDB exposes this facility via the <code>Connection.restore</code>
parameters <code>destFilenames</code> and <code>destFilePages</code>.
<code>destFilenames</code> (the second positional argument of
<code>Connection.restore</code>) can be either a string (as in the example
above, when restoring to a single database file) or a sequence of strings
naming each constituent file of the restored database.
If <code>destFilenames</code> is a string-sequence with length <code>N</code>,
<code>destFilePages</code> must be a sequence of integers with length
<code>N-1</code>. The database engine will constrain the size of each
database constituent file named in <code>destFilenames[:-1]</code> to the
corresponding page count specified in <code>destFilePages</code>; any
remaining database pages will be placed in the file name by
<code>destFilenames[-1]</code>.
</p>
<p class="textParagraph">
The following example program directs the engine to restore the backup file at
<code>'C:/temp/test_backup.gbk'</code> into a database with three constituent
files:
<code>'C:/temp/test_restored01.db'</code>,
<code>'C:/temp/test_restored02.db'</code>,
and
<code>'C:/temp/test_restored03.db'</code>.
The engine is instructed to place fifty user data pages in the first file,
seventy in the second, and the remainder in the third file. In practice, the
first database constituent file will be larger than
<code>pageSize*destFilePages[0]</code>, because metadata pages must also be
stored in the first constituent of a multifile database.
</p>
<pre class="codeBlockNoTop">
<FONT COLOR="#0000ff">from</FONT> kinterbasdb <FONT COLOR="#0000ff">import</FONT> services
con <FONT COLOR="#7d0000">=</FONT> services.<FONT COLOR="#000066">connect</FONT>(user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'masterkey'</FONT>)
con.<FONT COLOR="#000066">restore</FONT>(<FONT COLOR="#8f8c47">'C:/temp/test_backup.gbk'</FONT>,
(<FONT COLOR="#8f8c47">'C:/temp/test_restored01.db'</FONT>, <FONT COLOR="#8f8c47">'C:/temp/test_restored02.db'</FONT>, <FONT COLOR="#8f8c47">'C:/temp/test_restored03.db'</FONT>),
destFilePages<FONT COLOR="#7d0000">=</FONT>(<FONT COLOR="#666600">50</FONT>, <FONT COLOR="#666600">70</FONT>),
pageSize<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#666600">1024</FONT>,
replace<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#0066a0">True</FONT>
)
</pre>
<h5 class="serviceManagerMethod_Form">Extended Options</h5>
<p class="textParagraphTight">
These options are well documented beginning on page 155 of the
<a href="#ref_ib6_docs">Interbase® 6 Operations Guide</a>, so in this
document we present only a table of equivalence between the section caption in
the Interbase® 6 Operations Guide and the name of the keyword
parameter to <code>Connection.restore</code>:
</p>
<table border="1" style="margin-left: 1em;">
<thead>
<tr style="background-color: #DEDEDE;">
<td>IB6 Op. Guide Caption</td>
<td><code>Connection.restore</code><br>Parameter Name</td>
<td><code>Connection.restore</code><br>Parameter Default Value</td>
</tr>
</thead>
<tr>
<td>Page Size</td>
<td><code>pageSize</code></td>
<td><code>[use server default]</code></td>
</tr>
<tr>
<td>Overwrite</td>
<td><code>replace</code></td>
<td><code>False</code></td>
</tr>
<tr>
<td>Commit After Each Table</td>
<td><code>commitAfterEachTable</code></td>
<td><code>False</code></td>
</tr>
<tr>
<td>Create Shadow Files</td>
<td><code>doNotRestoreShadows</code></td>
<td><code>False</code></td>
</tr>
<tr>
<td>Deactivate Indexes</td>
<td><code>deactivateIndexes</code></td>
<td><code>False</code></td>
</tr>
<tr>
<td>Validity Conditions</td>
<td><code>doNotEnforceConstraints</code></td>
<td><code>False</code></td>
</tr>
<tr>
<td>Use All Space</td>
<td><code>useAllPageSpace</code></td>
<td><code>False</code></td>
</tr>
</table>
<p class="textParagraph">
Two additional boolean parameters are not covered by the table above:
<code>cacheBuffers</code> and <code>accessModeReadOnly</code>.
<code>cacheBuffers</code> specifies the default number of cache pages for
the restored database. If left unspecified, <code>cacheBuffers</code> uses
the server default.
<code>accessModeReadOnly</code> (default <code>False</code>) specifies whether
the restored database is read-only (<code>True</code>) or
writable (<code>False</code>).
</p>
<a name="adv_prog_maint_servapi_database_maint">
<h4 style="margin-top: 3em;">Controlling Database Operating Modes, Sweeps, and Repair</h4>
</a>
<p class="textParagraph">
<span class="XXX_ADDRESS_THIS">(XXX: not yet documented)</span>
</p>
<a name="adv_prog_maint_servapi_users">
<h4>User Maintenance</h4>
</a>
<p class="textParagraph">
<span class="XXX_ADDRESS_THIS">(XXX: not yet documented)</span>
</p>
<br><br>
<a name="adv_prog_maint_database_info">
<h3>The <code>database_info</code> Method</h3>
</a>
<table border="1" class="memberDocFrame">
<tr>
<td class="memberDocHeader">
<code class="memberDocName">database_info</code>
<span class="memberDocNameCaption">(method; member of <code>kinterbasdb.Connection</code>)</span>
</td>
</tr>
<tr>
<td>
<p>
Wraps the Interbase® C API function <code>isc_database_info</code> .
For extensive documentation, see the
<a href="#ref_ib6_docs">Interbase® 6 API Guide</a>
section
entitled "Requesting information about an attachment" (page 51).
</p>
<p>
Note that this method is a <em>very thin</em> wrapper around
function <code>isc_database_info</code> .
This method does <em>not</em> attempt to interpret
its results except with regard to whether they are a string or an
integer.
</p>
<p>
For example, requesting <code>isc_info_user_names</code> with the
call<br>
<pre class="codeBlockInMemberDoc" style="margin-bottom: 0px;">con.<FONT COLOR="#000066">database_info</FONT>(kinterbasdb.isc_info_user_names, <FONT COLOR="#8f8c47">'s'</FONT>)</pre>
will return a binary string
containing a <em>raw</em> 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 <code>isc_info_*</code> items.
</p>
<p class="argHeader">Arguments:</p>
<ul class="argList">
<li>
<code>request</code> -
one of the <code>kinterbasdb.isc_info_*</code> constants.<br>
</li>
<li>
<code>result_type</code> -
must be either
<code>'s'</code> if you expect a string result, or
<code>'i'</code> if you expect an integer result.
</li>
</ul>
</td>
</tr>
</table>
<a name="adv_prog_maint_database_info_example">
<h4>Example Program</h4>
</a>
<pre class="codeBlock"><FONT COLOR="#0000ff">import</FONT> kinterbasdb
con <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">connect</FONT>(dsn<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'localhost:/temp/test.db'</FONT>, user<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'sysdba'</FONT>, password<FONT COLOR="#7d0000">=</FONT><FONT COLOR="#8f8c47">'pass'</FONT>)
<FONT COLOR="#32a532"># Retrieving an integer info item is quite simple.</FONT>
bytesInUse <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">database_info</FONT>(kinterbasdb.isc_info_current_memory, <FONT COLOR="#8f8c47">'i'</FONT>)
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'The server is currently using %d bytes of memory.'</FONT> <FONT COLOR="#7d0000">%</FONT> bytesInUse
<FONT COLOR="#32a532"># Retrieving a string info item is somewhat more involved, because the</FONT>
<FONT COLOR="#32a532"># information is returned in a raw binary buffer that must be parsed</FONT>
<FONT COLOR="#32a532"># according to the rules defined in the Interbase® 6 API Guide section</FONT>
<FONT COLOR="#32a532"># entitled "Requesting buffer items and result buffer values" (page 51).</FONT>
<FONT COLOR="#32a532">#</FONT>
<FONT COLOR="#32a532"># Often, the buffer contains a succession of length-string pairs</FONT>
<FONT COLOR="#32a532"># (one byte telling the length of s, followed by s itself).</FONT>
<FONT COLOR="#32a532"># Function kinterbasdb.raw_byte_to_int is provided to convert a raw</FONT>
<FONT COLOR="#32a532"># byte to a Python integer (see examples below).</FONT>
buf <FONT COLOR="#7d0000">=</FONT> con.<FONT COLOR="#000066">database_info</FONT>(kinterbasdb.isc_info_db_id, <FONT COLOR="#8f8c47">'s'</FONT>)
<FONT COLOR="#32a532"># Parse the filename from the buffer.</FONT>
beginningOfFilename <FONT COLOR="#7d0000">=</FONT> <FONT COLOR="#666600">2</FONT>
<FONT COLOR="#32a532"># The second byte in the buffer contains the size of the database filename</FONT>
<FONT COLOR="#32a532"># in bytes.</FONT>
lengthOfFilename <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">raw_byte_to_int</FONT>(buf[<FONT COLOR="#666600">1</FONT>])
filename <FONT COLOR="#7d0000">=</FONT> buf[beginningOfFilename:beginningOfFilename <FONT COLOR="#7d0000">+</FONT> lengthOfFilename]
<FONT COLOR="#32a532"># Parse the host name from the buffer.</FONT>
beginningOfHostName <FONT COLOR="#7d0000">=</FONT> (beginningOfFilename <FONT COLOR="#7d0000">+</FONT> lengthOfFilename) <FONT COLOR="#7d0000">+</FONT> <FONT COLOR="#666600">1</FONT>
<FONT COLOR="#32a532"># The first byte after the end of the database filename contains the size</FONT>
<FONT COLOR="#32a532"># of the host name in bytes.</FONT>
lengthOfHostName <FONT COLOR="#7d0000">=</FONT> kinterbasdb.<FONT COLOR="#000066">raw_byte_to_int</FONT>(buf[beginningOfHostName <FONT COLOR="#7d0000">-</FONT> <FONT COLOR="#666600">1</FONT>])
host <FONT COLOR="#7d0000">=</FONT> buf[beginningOfHostName:beginningOfHostName <FONT COLOR="#7d0000">+</FONT> lengthOfHostName]
<FONT COLOR="#0000ff">print</FONT> <FONT COLOR="#8f8c47">'We are connected to the database at %s on host %s.'</FONT> <FONT COLOR="#7d0000">%</FONT> (filename, host)
</pre>
<p class="textParagraph">
Sample output:
</p>
<pre class="programOutputBlock">
The server is currently using 8931328 bytes of memory.
We are connected to the database at C:\TEMP\TEST.DB on host STALIN.
</pre>
<p class="textParagraph">
As you can see, extracting data with the <code>database_info</code> function
is rather clumsy. The Services API (accessible to Python programmers via the
<a href="#adv_prog_maint_servapi"><code>kinterbasdb.services</code></a>
module) provides much higher-level
support for querying many database statistics, as well as numerous other
maintenance tasks.
</p>
<br>
<hr>
<br>
<a name="faq_fep">
<h2>Frequently Asked Questions and Frequently Encountered Pitfalls</h2>
</a>
<a name="faq_fep_result_set_fields_by_name">
<h3>Refer to Result Row Fields by Name Rather than Index</h3>
</a>
<p class="textParagraph">
Use the
<a href="#db_api_extensions_and_caveats_cursor_fetchonemap"><code>Cursor.fetch*map</code></a>
series of methods for traditional <code>fetch</code>es, or the
<code>Cursor.itermap</code> method to iterate over mappings rather than
sequences.
Example code appears in the Tutorial section entitled
<a href="#tutorial_execute_sql">"Executing SQL Statements"</a>.
</p>
<br><br>
<a name="faq_fep_fixed_point_precise">
<h3>Precise Fixed Point (<code>NUMERIC</code>/<code>DECIMAL</code>) Handling</h3>
</a>
<p class="textParagraph">
KInterbasDB's
<a href="#adv_param_conv_dynamic_type_translation">dynamic type translation</a>
allows database fixed point types to be handled both precisely and
conveniently, when combined with a full-featured fixed point data type
such as that implemented by the
<a href="#ref_fixedpoint"><code>fixedpoint</code></a>
module.
</p>
<p class="textParagraph">
An official implementation of dynamic type translators for the
<code>fixedpoint</code> module is distributed with KInterbasDB in the
<code>kinterbasdb.typeconv_fixed_fixedpoint</code> module; it can be
loaded conveniently using the features discussed in
<a href="#adv_param_conv_dynamic_type_translation_deferred_loading">this section</a>.
Example programs appear
<a href="#adv_param_conv_dynamic_type_translation_deferred_loading_example">here</a>
and
<a href="#adv_param_conv_dynamic_type_translation_example_fixed">here</a>.
</p>
<br><br>
<a name="faq_fep_datetime">
<h3>Dates and Times: egenix <code>mx.DateTime</code> vs. Python 2.3+ standard library <code>datetime</code></h3>
</a>
<p class="textParagraph">
KInterbasDB's
<a href="#adv_param_conv_dynamic_type_translation">dynamic type translation</a>
allows either of these date/time modules to be used with nearly equal convenience.
Example programs appear
<a href="#adv_param_conv_dynamic_type_translation_deferred_loading_example">here</a>
and
<a href="#adv_param_conv_dynamic_type_translation_example">here</a>.
</p>
<p class="textParagraph">
Additionally, see
<a href="#adv_param_conv_dynamic_type_translation_deferred_loading">this section</a>
for a discussion of how to conveniently load alternatives to
<code>mx.DateTime</code>.
</p>
<br><br>
<a name="faq_fep_unicode">
<h3>Unicode Fields and KInterbasDB</h3>
</a>
<p class="textParagraph">
By default, KInterbasDB handles Unicode input and output naively, leaving
responsibility for encoding and decoding to the client programmer.
</p>
<p class="textParagraph">
In version <code>3.1_pre7</code>, a dynamic type translation slot named
<code>'TEXT_UNICODE'</code> was introduced.
The <code>'TEXT_UNICODE'</code> translators are invoked for all
<code>CHAR</code> or <code>VARCHAR</code> fields except those with character
sets <code>NONE</code>, <code>OCTETS</code>, or <code>ASCII</code>.
</p>
<p class="textParagraph">
The most convenient way to handle Unicode with KInterbasDB is to combine
the <code>'TEXT_UNICODE'</code> slot with the official translator
implementation in the <code>kinterbasdb.typeconv_text_unicode</code> module.
This can be accomplished either manually, via
<code>[Connection|Cursor].set_type_trans_[in|out]</code>,
or by loading a predefined translator set with
<code>kinterbasdb.init</code>. At present, predefined set <code>100</code>
(as in <code>kinterbasdb.init(type_conv=100)</code>) is the only predefined
set that enables automagic Unicode handling.
</p>
<p class="textParagraph">
For more information, see the
<a href="#adv_param_conv_dynamic_type_translation_tbl_signatures">translator signature table</a>
and this
<a href="#adv_param_conv_dynamic_type_translation_deferred_loading_example">example program</a>.
</p>
<br><br>
<a name="faq_fep_embedded_using_with">
<h3>Using KInterbasDB with Embedded Firebird (Windows Only)</h3>
</a>
<p class="textParagraph">
The Firebird 1.5 Release Notes (<em>ReleaseNotes.pdf</em>, included with RC5
and later) describe Embedded Firebird as "a DLL that merges a single client
attachment with a Firebird Superserver for building very quick and efficient
stand-alone and briefcase applications."
Practically speaking, Embedded Firebird allows an application to use the
database engine without managing an external server process. This is ideal for
applications that will be distributed to end users, or that must be deployed
on operating systems that support background services poorly, such as Win9x.
</p>
<p class="textParagraph">
The KInterbasDB distribution linked against the Firebird 1.5 client library
fbclient.dll
(kinterbasdb-<em>V.V</em>.win32-FB1.5-py<em>V.V</em>)
works fine with Embedded Firebird. Only local-protocol connections
are supported, of course, and some of the standalone-server-oriented features
of the Services API are not supported.
</p>
<p class="textParagraph">
For generic Embedded Firebird configuration instructions, refer to the section
of the Firebird 1.5 Release Notes entitled
"Installing Embedded server from a zip kit"
(page 51 of the <em>ReleaseNotes.pdf</em> accompanying Firebird 1.5.0).
</p>
<p class="textParagraph">
Below are specific instructions for installing Embedded Firebird 1.5.0 for use
with Python 2.3 and KInterbasDB 3.1. These instructions assume that there
are no existing installations of Firebird or KInterbasDB on your system.
</p>
<ol>
<li>
<p class="textParagraph">
Extract the file
<em>kinterbasdb-V.V-win32-all-binaries-manual-pack.zip</em>
to a temporary directory. Copy the <em>kinterbasdb</em> directory
from <em>kinterbasdb-V.V-win32-all-binaries-pack\firebird-1.5\lib.win32-2.3</em>
to a directory on the PYTHONPATH of the python.exe you intend to use
Embedded Firebird with (e.g., <em>the-directory-of-python.exe\Lib\site-packages</em>).
</p>
</li>
<li>
<p class="textParagraph">
Embedded Firebird is determined to use the directory of the application's
executable as its root directory. For Python applications, this
is the directory in which python.exe (or pythonw.exe) resides. It is
supposedly possible to manually override the Embedded Firebird root
directory setting, but that option doesn't work consistently if esoteric
engine features are used.
</p>
<p class="textParagraph">
Extract <em>Firebird-1.5.0.4290_embed_win32.zip</em> to a temporary
directory. Copy the files
<em>fbembed.dll</em>,
<em>firebird.msg</em>,
and <em>ib_util.dll</em>
to the directory in which python.exe resides.
If you intend to use character sets other than ASCII, also copy
the <em>intl</em> subdirectory, which contains <em>fbintl.dll</em>.
</p>
</li>
<li>
<p class="textParagraph">
Rename <em>fbembed.dll</em> to <em>fbclient.dll</em>.
</p>
<p class="textParagraph">
You should now
have the following file structure:
<pre class="codeBlock" style="margin-top: 0px;">
the-directory-of-python.exe\
[python.exe, and other Python-related files]
fbclient.dll
firebird.msg
ib_util.dll
intl\ <--only necessary if using character sets other than ASCII
fbintl.dll <--^
</pre>
</p>
</li>
<li>
<p class="textParagraph">
Run your KInterbasDB-based Python application. The database engine is
"embedded" within the same process as your application; no external server
process is necessary, and no code changes are required.
</p>
</li>
</ol>
<br><br>
<a name="faq_fep_services_api_classic_embedded">
<h3>Services API with the Classic and Embedded Server Architectures</h3>
</a>
<p class="textParagraph">
Firebird's Classic architecture provides only crippled support for the Services
API; the Embedded architecture provides none at all.
Of course KInterbasDB's Services API support is subject to the constraints of
the server architecture to which it connects.
</p>
<br><br>
<a name="faq_fep_zope_using_with">
<h3>Using KInterbasDB with Zope</h3>
</a>
<p class="textParagraph">
There exist at least two Zope adapters based on KInterbasDB; see the
<a href="links.html#zope">links page</a>.
</p>
<br><br>
<br>
<hr>
<br>
<a name="references">
<h2>References (External Links)</h2>
</a>
<ul>
<li>
<a name="ref_fb_docs_directory" href="http://www.firebirdsql.org/index.php?op=doc">Firebird Documentation</a>
(directory of links)
</li>
<li>
<a name="ref_ib6_docs" href="http://www.firebirdsql.org/index.php?op=doc&id=userdoc">Interbase® 6 Documentation</a>
(including the SQL Language Reference, the Data Definition Guide
and the API Guide).
Although this documentation was written for Interbase® 6, it also
applies to Firebird.
</li>
<li><a name="ref_fixedpoint"><a href="http://fixedpoint.sourceforge.net">fixedpoint module</a>
Precise, convenient representation of fixed point values such as those
stored in <code>DECIMAL</code>/<code>NUMERIC</code> fields in Firebird.
</li>
<li>
<a name="ref_kidb_links" href="links.html">KInterbasDB links page</a> A directory of links
to software and documentation useful in conjunction with KInterbasDB.
</li>
</ul>
<br>
<hr>
<br>
<a name="feedback">
<h2>Feedback</h2>
</a>
<p class="textParagraph">
Send feedback about this documentation or the KInterbasDB code to the author
of the current versions of both,
<a href="mailto:woodsplitter@rocketmail.com">David Rushby</a>.
</p>
<br>
<hr>
<br>
<a href="index.html">Overall Table of Contents</a>
<a href="#toc">Usage Guide Table of Contents</a>
<a href="#top">Top of This Page</a>
<br><br>
<div style="margin-bottom: 1.5em; margin-right: 1.5em; text-align: right;">
<a href="http://www.w3.org/Icons/valid-xhtml10"><img border="0" src="w3c.png"></a>
</div>
<div style="margin-top: 15em;"></div>
</body>
</html>
|