/usr/share/pyshared/gluon/dal.py is in python-gluon 1.99.7-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 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 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Thanks to
* Niall Sweeny <niall.sweeny@fonjax.com> for MS SQL support
* Marcel Leuthi <mluethi@mlsystems.ch> for Oracle support
* Denes
* Chris Clark
* clach05
* Denes Lengyel
* and many others who have contributed to current and previous versions
This file contains the DAL support for many relational databases,
including:
- SQLite
- MySQL
- Postgres
- Oracle
- MS SQL
- DB2
- Interbase
- Ingres
- SapDB (experimental)
- Cubrid (experimental)
- CouchDB (experimental)
- MongoDB (in progress)
- Google:nosql
- Google:sql
- Teradata
- IMAP (experimental)
Example of usage:
>>> # from dal import DAL, Field
### create DAL connection (and create DB if it doesn't exist)
>>> db = DAL(('mysql://a:b@localhost/x', 'sqlite://storage.sqlite'), folder=None)
### define a table 'person' (create/alter as necessary)
>>> person = db.define_table('person',Field('name','string'))
### insert a record
>>> id = person.insert(name='James')
### retrieve it by id
>>> james = person(id)
### retrieve it by name
>>> james = person(name='James')
### retrieve it by arbitrary query
>>> query = (person.name=='James') & (person.name.startswith('J'))
>>> james = db(query).select(person.ALL)[0]
### update one record
>>> james.update_record(name='Jim')
### update multiple records by query
>>> db(person.name.like('J%')).update(name='James')
1
### delete records by query
>>> db(person.name.lower() == 'jim').delete()
0
### retrieve multiple records (rows)
>>> people = db(person).select(orderby=person.name, groupby=person.name, limitby=(0,100))
### further filter them
>>> james = people.find(lambda row: row.name == 'James').first()
>>> print james.id, james.name
1 James
### check aggregates
>>> counter = person.id.count()
>>> print db(person).select(counter).first()(counter)
1
### delete one record
>>> james.delete_record()
1
### delete (drop) entire database table
>>> person.drop()
Supported field types:
id string text boolean integer double decimal password upload blob time date datetime
Supported DAL URI strings:
'sqlite://test.db'
'sqlite:memory'
'jdbc:sqlite://test.db'
'mysql://root:none@localhost/test'
'postgres://mdipierro:password@localhost/test'
'postgres:psycopg2://mdipierro:password@localhost/test'
'postgres:pg8000://mdipierro:password@localhost/test'
'jdbc:postgres://mdipierro:none@localhost/test'
'mssql://web2py:none@A64X2/web2py_test'
'mssql2://web2py:none@A64X2/web2py_test' # alternate mappings
'oracle://username:password@database'
'firebird://user:password@server:3050/database'
'db2://DSN=dsn;UID=user;PWD=pass'
'firebird://username:password@hostname/database'
'firebird_embedded://username:password@c://path'
'informix://user:password@server:3050/database'
'informixu://user:password@server:3050/database' # unicode informix
'google:datastore' # for google app engine datastore
'google:sql' # for google app engine with sql (mysql compatible)
'teradata://DSN=dsn;UID=user;PWD=pass; DATABASE=database' # experimental
'imap://user:password@server:port' # experimental
For more info:
help(DAL)
help(Field)
"""
###################################################################################
# this file only exposes DAL and Field
###################################################################################
__all__ = ['DAL', 'Field']
MAXCHARLENGTH = 2**15 # not quite but reasonable default max char length
DEFAULTLENGTH = {'string':512,
'password':512,
'upload':512,
'text':2**15,
'blob':2**31}
TIMINGSSIZE = 100
import re
import sys
import locale
import os
import types
import cPickle
import datetime
import threading
import time
import cStringIO
import csv
import cgi
import copy
import socket
import logging
import copy_reg
import base64
import shutil
import marshal
import decimal
import struct
import urllib
import hashlib
import uuid
import glob
import traceback
CALLABLETYPES = (types.LambdaType, types.FunctionType, types.BuiltinFunctionType,
types.MethodType, types.BuiltinMethodType)
###################################################################################
# following checks allows running of dal without web2py as a standalone module
###################################################################################
try:
from utils import web2py_uuid
except ImportError:
import uuid
def web2py_uuid(): return str(uuid.uuid4())
try:
import portalocker
have_portalocker = True
except ImportError:
have_portalocker = False
try:
import serializers
have_serializers = True
except ImportError:
have_serializers = False
try:
import validators
have_validators = True
except ImportError:
have_validators = False
logger = logging.getLogger("web2py.dal")
DEFAULT = lambda:0
sql_locker = threading.RLock()
thread = threading.local()
# internal representation of tables with field
# <table>.<field>, tables and fields may only be [a-zA-Z0-0_]
regex_type = re.compile('^([\w\_\:]+)')
regex_dbname = re.compile('^(\w+)(\:\w+)*')
regex_table_field = re.compile('^([\w_]+)\.([\w_]+)$')
regex_content = re.compile('(?P<table>[\w\-]+)\.(?P<field>[\w\-]+)\.(?P<uuidkey>[\w\-]+)\.(?P<name>\w+)\.\w+$')
regex_cleanup_fn = re.compile('[\'"\s;]+')
string_unpack=re.compile('(?<!\|)\|(?!\|)')
regex_python_keywords = re.compile('^(and|del|from|not|while|as|elif|global|or|with|assert|else|if|pass|yield|break|except|import|print|class|exec|in|raise|continue|finally|is|return|def|for|lambda|try)$')
regex_select_as_parser = re.compile("\s+AS\s+(\S+)")
# list of drivers will be built on the fly
# and lists only what is available
drivers = []
try:
from new import classobj
from google.appengine.ext import db as gae
from google.appengine.api import namespace_manager, rdbms
from google.appengine.api.datastore_types import Key ### needed for belongs on ID
from google.appengine.ext.db.polymodel import PolyModel
drivers.append('google')
except ImportError:
pass
if not 'google' in drivers:
try:
from pysqlite2 import dbapi2 as sqlite3
drivers.append('pysqlite2')
except ImportError:
try:
from sqlite3 import dbapi2 as sqlite3
drivers.append('SQLite3')
except ImportError:
logger.debug('no sqlite3 or pysqlite2.dbapi2 driver')
try:
import contrib.pymysql as pymysql
drivers.append('pymysql')
except ImportError:
logger.debug('no pymysql driver')
try:
import psycopg2
from psycopg2.extensions import adapt as psycopg2_adapt
drivers.append('psycopg2')
except ImportError:
logger.debug('no psycopg2 driver')
try:
# first try contrib driver, then from site-packages (if installed)
try:
import contrib.pg8000.dbapi as pg8000
except ImportError:
import pg8000.dbapi as pg8000
drivers.append('pg8000')
except ImportError:
logger.debug('no pg8000 driver')
try:
import cx_Oracle
drivers.append('Oracle')
except ImportError:
logger.debug('no cx_Oracle driver')
try:
import pyodbc
drivers.append('MSSQL/DB2/Teradata')
except ImportError:
logger.debug('no MSSQL/DB2/Teradata driver')
try:
import kinterbasdb
drivers.append('Interbase')
except ImportError:
logger.debug('no kinterbasdb driver')
try:
import firebirdsql
drivers.append('Firebird')
except ImportError:
logger.debug('no Firebird driver')
try:
import informixdb
drivers.append('Informix')
logger.warning('Informix support is experimental')
except ImportError:
logger.debug('no informixdb driver')
try:
import sapdb
drivers.append('SAPDB')
logger.warning('SAPDB support is experimental')
except ImportError:
logger.debug('no sapdb driver')
try:
import cubriddb
drivers.append('Cubrid')
logger.warning('Cubrid support is experimental')
except ImportError:
logger.debug('no cubriddb driver')
try:
from com.ziclix.python.sql import zxJDBC
import java.sql
# Try sqlite jdbc driver from http://www.zentus.com/sqlitejdbc/
from org.sqlite import JDBC # required by java.sql; ensure we have it
drivers.append('zxJDBC')
logger.warning('zxJDBC support is experimental')
is_jdbc = True
except ImportError:
logger.debug('no zxJDBC driver')
is_jdbc = False
try:
import ingresdbi
drivers.append('Ingres')
except ImportError:
logger.debug('no Ingres driver')
# NOTE could try JDBC.......
try:
import couchdb
drivers.append('CouchDB')
except ImportError:
logger.debug('no couchdb driver')
try:
import pymongo
drivers.append('mongoDB')
except:
logger.debug('no mongoDB driver')
try:
import imaplib
drivers.append('IMAP')
except:
logger.debug('could not import imaplib')
PLURALIZE_RULES = [
(re.compile('child$'), re.compile('child$'), 'children'),
(re.compile('oot$'), re.compile('oot$'), 'eet'),
(re.compile('ooth$'), re.compile('ooth$'), 'eeth'),
(re.compile('l[eo]af$'), re.compile('l([eo])af$'), 'l\\1aves'),
(re.compile('sis$'), re.compile('sis$'), 'ses'),
(re.compile('man$'), re.compile('man$'), 'men'),
(re.compile('ife$'), re.compile('ife$'), 'ives'),
(re.compile('eau$'), re.compile('eau$'), 'eaux'),
(re.compile('lf$'), re.compile('lf$'), 'lves'),
(re.compile('[sxz]$'), re.compile('$'), 'es'),
(re.compile('[^aeioudgkprt]h$'), re.compile('$'), 'es'),
(re.compile('(qu|[^aeiou])y$'), re.compile('y$'), 'ies'),
(re.compile('$'), re.compile('$'), 's'),
]
def pluralize(singular, rules=PLURALIZE_RULES):
for line in rules:
re_search, re_sub, replace = line
plural = re_search.search(singular) and re_sub.sub(replace, singular)
if plural: return plural
def OR(a,b):
return a|b
def AND(a,b):
return a&b
if 'google' in drivers:
is_jdbc = False
class GAEDecimalProperty(gae.Property):
"""
GAE decimal implementation
"""
data_type = decimal.Decimal
def __init__(self, precision, scale, **kwargs):
super(GAEDecimalProperty, self).__init__(self, **kwargs)
d = '1.'
for x in range(scale):
d += '0'
self.round = decimal.Decimal(d)
def get_value_for_datastore(self, model_instance):
value = super(GAEDecimalProperty, self).get_value_for_datastore(model_instance)
if value is None or value == '':
return None
else:
return str(value)
def make_value_from_datastore(self, value):
if value is None or value == '':
return None
else:
return decimal.Decimal(value).quantize(self.round)
def validate(self, value):
value = super(GAEDecimalProperty, self).validate(value)
if value is None or isinstance(value, decimal.Decimal):
return value
elif isinstance(value, basestring):
return decimal.Decimal(value)
raise gae.BadValueError("Property %s must be a Decimal or string." % self.name)
###################################################################################
# class that handles connection pooling (all adapters are derived from this one)
###################################################################################
class ConnectionPool(object):
pools = {}
check_active_connection = True
@staticmethod
def set_folder(folder):
thread.folder = folder
# ## this allows gluon to commit/rollback all dbs in this thread
@staticmethod
def close_all_instances(action):
""" to close cleanly databases in a multithreaded environment """
if not hasattr(thread, 'instances'):
return
while thread.instances:
instance = thread.instances.pop()
if action:
getattr(instance, action)()
# ## if you want pools, recycle this connection
really = True
if instance.pool_size:
sql_locker.acquire()
pool = ConnectionPool.pools[instance.uri]
if len(pool) < instance.pool_size:
pool.append(instance.connection)
really = False
sql_locker.release()
if really:
getattr(instance, 'close')()
return
def find_or_make_work_folder(self):
""" this actually does not make the folder. it has to be there """
if hasattr(thread,'folder'):
self.folder = thread.folder
else:
self.folder = thread.folder = ''
# Creating the folder if it does not exist
if False and self.folder and not os.path.exists(self.folder):
os.mkdir(self.folder)
def pool_connection(self, f, cursor=True):
"""
this function defines: self.connection and self.cursor (iff cursor is True)
if self.pool_size>0 it will try pull the connection from the pool
if the connection is not active (closed by db server) it will loop
if not self.pool_size or no active connections in pool makes a new one
"""
if not self.pool_size:
self.connection = f()
self.cursor = cursor and self.connection.cursor()
else:
uri = self.uri
while True:
sql_locker.acquire()
if not uri in ConnectionPool.pools:
ConnectionPool.pools[uri] = []
if ConnectionPool.pools[uri]:
self.connection = ConnectionPool.pools[uri].pop()
sql_locker.release()
self.cursor = cursor and self.connection.cursor()
try:
if self.cursor and self.check_active_connection:
self.execute('SELECT 1;')
break
except:
pass
else:
sql_locker.release()
self.connection = f()
self.cursor = cursor and self.connection.cursor()
break
if not hasattr(thread,'instances'):
thread.instances = []
thread.instances.append(self)
###################################################################################
# this is a generic adapter that does nothing; all others are derived from this one
###################################################################################
class BaseAdapter(ConnectionPool):
driver = None
maxcharlength = MAXCHARLENGTH
commit_on_alter_table = False
support_distributed_transaction = False
uploads_in_blob = False
can_select_for_update = True
types = {
'boolean': 'CHAR(1)',
'string': 'CHAR(%(length)s)',
'text': 'TEXT',
'password': 'CHAR(%(length)s)',
'blob': 'BLOB',
'upload': 'CHAR(%(length)s)',
'integer': 'INTEGER',
'double': 'DOUBLE',
'decimal': 'DOUBLE',
'date': 'DATE',
'time': 'TIME',
'datetime': 'TIMESTAMP',
'id': 'INTEGER PRIMARY KEY AUTOINCREMENT',
'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'list:integer': 'TEXT',
'list:string': 'TEXT',
'list:reference': 'TEXT',
}
def adapt(self, obj):
return "'%s'" % obj.replace("'", "''")
def integrity_error(self):
return self.driver.IntegrityError
def operational_error(self):
return self.driver.OperationalError
def file_exists(self, filename):
"""
to be used ONLY for files that on GAE may not be on filesystem
"""
return os.path.exists(filename)
def file_open(self, filename, mode='rb', lock=True):
"""
to be used ONLY for files that on GAE may not be on filesystem
"""
if have_portalocker and lock:
fileobj = portalocker.LockedFile(filename,mode)
else:
fileobj = open(filename,mode)
return fileobj
def file_close(self, fileobj):
"""
to be used ONLY for files that on GAE may not be on filesystem
"""
if fileobj:
fileobj.close()
def file_delete(self, filename):
os.unlink(filename)
def __init__(self, db,uri,pool_size=0, folder=None, db_codec='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
self.db = db
self.dbengine = "None"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
class Dummy(object):
lastrowid = 1
def __getattr__(self, value):
return lambda *a, **b: []
self.connection = Dummy()
self.cursor = Dummy()
def sequence_name(self,tablename):
return '%s_sequence' % tablename
def trigger_name(self,tablename):
return '%s_sequence' % tablename
def create_table(self, table,
migrate=True,
fake_migrate=False,
polymodel=None):
fields = []
sql_fields = {}
sql_fields_aux = {}
TFK = {}
tablename = table._tablename
sortable = 0
for field in table:
sortable += 1
k = field.name
if isinstance(field.type,SQLCustomType):
ftype = field.type.native or field.type.type
elif field.type.startswith('reference'):
referenced = field.type[10:].strip()
constraint_name = self.constraint_name(tablename, field.name)
if hasattr(table,'_primarykey'):
rtablename,rfieldname = referenced.split('.')
rtable = table._db[rtablename]
rfield = rtable[rfieldname]
# must be PK reference or unique
if rfieldname in rtable._primarykey or rfield.unique:
ftype = self.types[rfield.type[:9]] % dict(length=rfield.length)
# multicolumn primary key reference?
if not rfield.unique and len(rtable._primarykey)>1 :
# then it has to be a table level FK
if rtablename not in TFK:
TFK[rtablename] = {}
TFK[rtablename][rfieldname] = field.name
else:
ftype = ftype + \
self.types['reference FK'] %dict(\
constraint_name=constraint_name,
table_name=tablename,
field_name=field.name,
foreign_key='%s (%s)'%(rtablename, rfieldname),
on_delete_action=field.ondelete)
else:
# make a guess here for circular references
id_fieldname = referenced in table._db and table._db[referenced]._id.name or 'id'
ftype = self.types[field.type[:9]]\
% dict(table_name=tablename,
field_name=field.name,
constraint_name=constraint_name,
foreign_key=referenced + ('(%s)' % id_fieldname),
on_delete_action=field.ondelete)
elif field.type.startswith('list:reference'):
ftype = self.types[field.type[:14]]
elif field.type.startswith('decimal'):
precision, scale = map(int,field.type[8:-1].split(','))
ftype = self.types[field.type[:7]] % \
dict(precision=precision,scale=scale)
elif not field.type in self.types:
raise SyntaxError, 'Field: unknown field type: %s for %s' % \
(field.type, field.name)
else:
ftype = self.types[field.type]\
% dict(length=field.length)
if not field.type.startswith('id') and not field.type.startswith('reference'):
if field.notnull:
ftype += ' NOT NULL'
else:
ftype += self.ALLOW_NULL()
if field.unique:
ftype += ' UNIQUE'
# add to list of fields
sql_fields[field.name] = dict(sortable=sortable,
type=str(field.type),
sql=ftype)
if isinstance(field.default,(str,int,float)):
# Caveat: sql_fields and sql_fields_aux differ for default values.
# sql_fields is used to trigger migrations and sql_fields_aux
# is used for create tables.
# The reason is that we do not want to trigger a migration simply
# because a default value changes.
not_null = self.NOT_NULL(field.default, field.type)
ftype = ftype.replace('NOT NULL', not_null)
sql_fields_aux[field.name] = dict(sql=ftype)
fields.append('%s %s' % (field.name, ftype))
other = ';'
# backend-specific extensions to fields
if self.dbengine == 'mysql':
if not hasattr(table, "_primarykey"):
fields.append('PRIMARY KEY(%s)' % table._id.name)
other = ' ENGINE=InnoDB CHARACTER SET utf8;'
fields = ',\n '.join(fields)
for rtablename in TFK:
rfields = TFK[rtablename]
pkeys = table._db[rtablename]._primarykey
fkeys = [ rfields[k] for k in pkeys ]
fields = fields + ',\n ' + \
self.types['reference TFK'] %\
dict(table_name=tablename,
field_name=', '.join(fkeys),
foreign_table=rtablename,
foreign_key=', '.join(pkeys),
on_delete_action=field.ondelete)
if hasattr(table,'_primarykey'):
query = '''CREATE TABLE %s(\n %s,\n %s) %s''' % \
(tablename, fields, self.PRIMARY_KEY(', '.join(table._primarykey)),other)
else:
query = '''CREATE TABLE %s(\n %s\n)%s''' % \
(tablename, fields, other)
if self.uri.startswith('sqlite:///'):
path_encoding = sys.getfilesystemencoding() or locale.getdefaultlocale()[1] or 'utf8'
dbpath = self.uri[9:self.uri.rfind('/')].decode('utf8').encode(path_encoding)
else:
dbpath = self.folder
if not migrate:
return query
elif self.uri.startswith('sqlite:memory'):
table._dbt = None
elif isinstance(migrate, str):
table._dbt = os.path.join(dbpath, migrate)
else:
table._dbt = os.path.join(dbpath, '%s_%s.table' \
% (table._db._uri_hash, tablename))
if table._dbt:
table._loggername = os.path.join(dbpath, 'sql.log')
logfile = self.file_open(table._loggername, 'a')
else:
logfile = None
if not table._dbt or not self.file_exists(table._dbt):
if table._dbt:
logfile.write('timestamp: %s\n'
% datetime.datetime.today().isoformat())
logfile.write(query + '\n')
if not fake_migrate:
self.create_sequence_and_triggers(query,table)
table._db.commit()
if table._dbt:
tfile = self.file_open(table._dbt, 'w')
cPickle.dump(sql_fields, tfile)
self.file_close(tfile)
if fake_migrate:
logfile.write('faked!\n')
else:
logfile.write('success!\n')
else:
tfile = self.file_open(table._dbt, 'r')
try:
sql_fields_old = cPickle.load(tfile)
except EOFError:
self.file_close(tfile)
self.file_close(logfile)
raise RuntimeError, 'File %s appears corrupted' % table._dbt
self.file_close(tfile)
if sql_fields != sql_fields_old:
self.migrate_table(table,
sql_fields, sql_fields_old,
sql_fields_aux, logfile,
fake_migrate=fake_migrate)
self.file_close(logfile)
return query
def migrate_table(
self,
table,
sql_fields,
sql_fields_old,
sql_fields_aux,
logfile,
fake_migrate=False,
):
tablename = table._tablename
def fix(item):
k,v=item
if not isinstance(v,dict):
v=dict(type='unkown',sql=v)
return k.lower(),v
### make sure all field names are lower case to avoid conflicts
sql_fields = dict(map(fix,sql_fields.items()))
sql_fields_old = dict(map(fix,sql_fields_old.items()))
sql_fields_aux = dict(map(fix,sql_fields_aux.items()))
keys = sql_fields.keys()
for key in sql_fields_old:
if not key in keys:
keys.append(key)
if self.dbengine == 'mssql':
new_add = '; ALTER TABLE %s ADD ' % tablename
else:
new_add = ', ADD '
metadata_change = False
sql_fields_current = copy.copy(sql_fields_old)
for key in keys:
query = None
if not key in sql_fields_old:
sql_fields_current[key] = sql_fields[key]
query = ['ALTER TABLE %s ADD %s %s;' % \
(tablename, key,
sql_fields_aux[key]['sql'].replace(', ', new_add))]
metadata_change = True
elif self.dbengine == 'sqlite':
if key in sql_fields:
sql_fields_current[key] = sql_fields[key]
metadata_change = True
elif not key in sql_fields:
del sql_fields_current[key]
if not self.dbengine in ('firebird',):
query = ['ALTER TABLE %s DROP COLUMN %s;' % (tablename, key)]
else:
query = ['ALTER TABLE %s DROP %s;' % (tablename, key)]
metadata_change = True
elif sql_fields[key]['sql'] != sql_fields_old[key]['sql'] \
and not isinstance(table[key].type, SQLCustomType) \
and not (table[key].type.startswith('reference') and \
sql_fields[key]['sql'].startswith('INT,') and \
sql_fields_old[key]['sql'].startswith('INT NOT NULL,')):
sql_fields_current[key] = sql_fields[key]
t = tablename
tt = sql_fields_aux[key]['sql'].replace(', ', new_add)
if not self.dbengine in ('firebird',):
query = ['ALTER TABLE %s ADD %s__tmp %s;' % (t, key, tt),
'UPDATE %s SET %s__tmp=%s;' % (t, key, key),
'ALTER TABLE %s DROP COLUMN %s;' % (t, key),
'ALTER TABLE %s ADD %s %s;' % (t, key, tt),
'UPDATE %s SET %s=%s__tmp;' % (t, key, key),
'ALTER TABLE %s DROP COLUMN %s__tmp;' % (t, key)]
else:
query = ['ALTER TABLE %s ADD %s__tmp %s;' % (t, key, tt),
'UPDATE %s SET %s__tmp=%s;' % (t, key, key),
'ALTER TABLE %s DROP %s;' % (t, key),
'ALTER TABLE %s ADD %s %s;' % (t, key, tt),
'UPDATE %s SET %s=%s__tmp;' % (t, key, key),
'ALTER TABLE %s DROP %s__tmp;' % (t, key)]
metadata_change = True
elif sql_fields[key]['type'] != sql_fields_old[key]['type']:
sql_fields_current[key] = sql_fields[key]
metadata_change = True
if query:
logfile.write('timestamp: %s\n'
% datetime.datetime.today().isoformat())
table._db['_lastsql'] = '\n'.join(query)
for sub_query in query:
logfile.write(sub_query + '\n')
if not fake_migrate:
self.execute(sub_query)
# Caveat: mysql, oracle and firebird do not allow multiple alter table
# in one transaction so we must commit partial transactions and
# update table._dbt after alter table.
if table._db._adapter.commit_on_alter_table:
table._db.commit()
tfile = self.file_open(table._dbt, 'w')
cPickle.dump(sql_fields_current, tfile)
self.file_close(tfile)
logfile.write('success!\n')
else:
logfile.write('faked!\n')
elif metadata_change:
tfile = self.file_open(table._dbt, 'w')
cPickle.dump(sql_fields_current, tfile)
self.file_close(tfile)
if metadata_change and \
not (query and self.dbengine in ('mysql','oracle','firebird')):
table._db.commit()
tfile = self.file_open(table._dbt, 'w')
cPickle.dump(sql_fields_current, tfile)
self.file_close(tfile)
def LOWER(self, first):
return 'LOWER(%s)' % self.expand(first)
def UPPER(self, first):
return 'UPPER(%s)' % self.expand(first)
def EXTRACT(self, first, what):
return "EXTRACT(%s FROM %s)" % (what, self.expand(first))
def AGGREGATE(self, first, what):
return "%s(%s)" % (what, self.expand(first))
def JOIN(self):
return 'JOIN'
def LEFT_JOIN(self):
return 'LEFT JOIN'
def RANDOM(self):
return 'Random()'
def NOT_NULL(self, default, field_type):
return 'NOT NULL DEFAULT %s' % self.represent(default,field_type)
def COALESCE(self, first, second):
expressions = [self.expand(first)]+[self.expand(e) for e in second]
return 'COALESCE(%s)' % ','.join(expressions)
def COALESCE_ZERO(self, first):
return 'COALESCE(%s,0)' % self.expand(first)
def RAW(self, first):
return first
def ALLOW_NULL(self):
return ''
def SUBSTRING(self, field, parameters):
return 'SUBSTR(%s,%s,%s)' % (self.expand(field), parameters[0], parameters[1])
def PRIMARY_KEY(self, key):
return 'PRIMARY KEY(%s)' % key
def _drop(self, table, mode):
return ['DROP TABLE %s;' % table]
def drop(self, table, mode=''):
if table._dbt:
logfile = self.file_open(table._loggername, 'a')
queries = self._drop(table, mode)
for query in queries:
if table._dbt:
logfile.write(query + '\n')
self.execute(query)
table._db.commit()
del table._db[table._tablename]
del table._db.tables[table._db.tables.index(table._tablename)]
table._db._update_referenced_by(table._tablename)
if table._dbt:
self.file_delete(table._dbt)
logfile.write('success!\n')
def _insert(self, table, fields):
keys = ','.join(f.name for f,v in fields)
values = ','.join(self.expand(v,f.type) for f,v in fields)
return 'INSERT INTO %s(%s) VALUES (%s);' % (table, keys, values)
def insert(self, table, fields):
query = self._insert(table,fields)
try:
self.execute(query)
except Exception, e:
if isinstance(e,self.integrity_error_class()):
return None
raise e
if hasattr(table,'_primarykey'):
return dict([(k[0].name, k[1]) for k in fields \
if k[0].name in table._primarykey])
id = self.lastrowid(table)
if not isinstance(id,int):
return id
rid = Reference(id)
(rid._table, rid._record) = (table, None)
return rid
def bulk_insert(self, table, items):
return [self.insert(table,item) for item in items]
def NOT(self, first):
return '(NOT %s)' % self.expand(first)
def AND(self, first, second):
return '(%s AND %s)' % (self.expand(first), self.expand(second))
def OR(self, first, second):
return '(%s OR %s)' % (self.expand(first), self.expand(second))
def BELONGS(self, first, second):
if isinstance(second, str):
return '(%s IN (%s))' % (self.expand(first), second[:-1])
elif second==[] or second==():
return '(1=0)'
items = ','.join(self.expand(item, first.type) for item in second)
return '(%s IN (%s))' % (self.expand(first), items)
def REGEXP(self, first, second):
"regular expression operator"
raise NotImplementedError
def LIKE(self, first, second):
"case sensitive like operator"
raise NotImplementedError
def ILIKE(self, first, second):
"case in-sensitive like operator"
return '(%s LIKE %s)' % (self.expand(first), self.expand(second, 'string'))
def STARTSWITH(self, first, second):
return '(%s LIKE %s)' % (self.expand(first), self.expand(second+'%', 'string'))
def ENDSWITH(self, first, second):
return '(%s LIKE %s)' % (self.expand(first), self.expand('%'+second, 'string'))
def CONTAINS(self, first, second):
if first.type in ('string', 'text'):
key = '%'+str(second).replace('%','%%')+'%'
elif first.type.startswith('list:'):
key = '%|'+str(second).replace('|','||').replace('%','%%')+'|%'
return '(%s LIKE %s)' % (self.expand(first),self.expand(key,'string'))
def EQ(self, first, second=None):
if second is None:
return '(%s IS NULL)' % self.expand(first)
return '(%s = %s)' % (self.expand(first), self.expand(second, first.type))
def NE(self, first, second=None):
if second is None:
return '(%s IS NOT NULL)' % self.expand(first)
return '(%s <> %s)' % (self.expand(first), self.expand(second, first.type))
def LT(self,first,second=None):
if second is None:
raise RuntimeError, "Cannot compare %s < None" % first
return '(%s < %s)' % (self.expand(first),self.expand(second,first.type))
def LE(self,first,second=None):
if second is None:
raise RuntimeError, "Cannot compare %s <= None" % first
return '(%s <= %s)' % (self.expand(first),self.expand(second,first.type))
def GT(self,first,second=None):
if second is None:
raise RuntimeError, "Cannot compare %s > None" % first
return '(%s > %s)' % (self.expand(first),self.expand(second,first.type))
def GE(self,first,second=None):
if second is None:
raise RuntimeError, "Cannot compare %s >= None" % first
return '(%s >= %s)' % (self.expand(first),self.expand(second,first.type))
def ADD(self, first, second):
return '(%s + %s)' % (self.expand(first), self.expand(second, first.type))
def SUB(self, first, second):
return '(%s - %s)' % (self.expand(first), self.expand(second, first.type))
def MUL(self, first, second):
return '(%s * %s)' % (self.expand(first), self.expand(second, first.type))
def DIV(self, first, second):
return '(%s / %s)' % (self.expand(first), self.expand(second, first.type))
def MOD(self, first, second):
return '(%s %% %s)' % (self.expand(first), self.expand(second, first.type))
def AS(self, first, second):
return '%s AS %s' % (self.expand(first), second)
def ON(self, first, second):
return '%s ON %s' % (self.expand(first), self.expand(second))
def INVERT(self, first):
return '%s DESC' % self.expand(first)
def COMMA(self, first, second):
return '%s, %s' % (self.expand(first), self.expand(second))
def expand(self, expression, field_type=None):
if isinstance(expression, Field):
return str(expression)
elif isinstance(expression, (Expression, Query)):
if not expression.second is None:
return expression.op(expression.first, expression.second)
elif not expression.first is None:
return expression.op(expression.first)
elif not isinstance(expression.op, str):
return expression.op()
else:
return '(%s)' % expression.op
elif field_type:
return str(self.represent(expression,field_type))
elif isinstance(expression,(list,tuple)):
return ','.join(self.represent(item,field_type) for item in expression)
else:
return str(expression)
def alias(self, table, alias):
"""
Given a table object, makes a new table object
with alias name.
"""
other = copy.copy(table)
other['_ot'] = other._tablename
other['ALL'] = SQLALL(other)
other['_tablename'] = alias
for fieldname in other.fields:
other[fieldname] = copy.copy(other[fieldname])
other[fieldname]._tablename = alias
other[fieldname].tablename = alias
other[fieldname].table = other
table._db[alias] = other
return other
def _truncate(self, table, mode=''):
tablename = table._tablename
return ['TRUNCATE TABLE %s %s;' % (tablename, mode or '')]
def truncate(self, table, mode= ' '):
# Prepare functions "write_to_logfile" and "close_logfile"
if table._dbt:
logfile = self.file_open(table._loggername, 'a')
else:
class Logfile(object):
def write(self, value):
pass
def close(self):
pass
logfile = Logfile()
try:
queries = table._db._adapter._truncate(table, mode)
for query in queries:
logfile.write(query + '\n')
self.execute(query)
table._db.commit()
logfile.write('success!\n')
finally:
logfile.close()
def _update(self, tablename, query, fields):
if query:
if use_common_filters(query):
query = self.common_filter(query, [tablename])
sql_w = ' WHERE ' + self.expand(query)
else:
sql_w = ''
sql_v = ','.join(['%s=%s' % (field.name, self.expand(value, field.type)) \
for (field, value) in fields])
return 'UPDATE %s SET %s%s;' % (tablename, sql_v, sql_w)
def update(self, tablename, query, fields):
sql = self._update(tablename, query, fields)
self.execute(sql)
try:
return self.cursor.rowcount
except:
return None
def _delete(self, tablename, query):
if query:
if use_common_filters(query):
query = self.common_filter(query, [tablename])
sql_w = ' WHERE ' + self.expand(query)
else:
sql_w = ''
return 'DELETE FROM %s%s;' % (tablename, sql_w)
def delete(self, tablename, query):
sql = self._delete(tablename, query)
### special code to handle CASCADE in SQLite
db = self.db
table = db[tablename]
if self.dbengine=='sqlite' and table._referenced_by:
deleted = [x[table._id.name] for x in db(query).select(table._id)]
### end special code to handle CASCADE in SQLite
self.execute(sql)
try:
counter = self.cursor.rowcount
except:
counter = None
### special code to handle CASCADE in SQLite
if self.dbengine=='sqlite' and counter:
for tablename,fieldname in table._referenced_by:
f = db[tablename][fieldname]
if f.type=='reference '+table._tablename and f.ondelete=='CASCADE':
db(db[tablename][fieldname].belongs(deleted)).delete()
### end special code to handle CASCADE in SQLite
return counter
def get_table(self, query):
tablenames = self.tables(query)
if len(tablenames)==1:
return tablenames[0]
elif len(tablenames)<1:
raise RuntimeError, "No table selected"
else:
raise RuntimeError, "Too many tables selected"
def expand_all(self, fields, tablenames):
new_fields = []
for item in fields:
if isinstance(item,SQLALL):
new_fields += item.table
else:
new_fields.append(item)
# ## if no fields specified take them all from the requested tables
if not new_fields:
for table in tablenames:
for field in self.db[table]:
new_fields.append(field)
return new_fields
def _select(self, query, fields, attributes):
for key in set(attributes.keys())-set(('orderby', 'groupby', 'limitby',
'required', 'cache', 'left',
'distinct', 'having', 'join',
'for_update')):
raise SyntaxError, 'invalid select attribute: %s' % key
tablenames = self.tables(query)
for field in fields:
if isinstance(field, basestring) and regex_table_field.match(field):
tn,fn = field.split('.')
field = self.db[tn][fn]
for tablename in self.tables(field):
if not tablename in tablenames:
tablenames.append(tablename)
if use_common_filters(query):
query = self.common_filter(query,tablenames)
if len(tablenames) < 1:
raise SyntaxError, 'Set: no tables selected'
sql_f = ', '.join(map(self.expand, fields))
self._colnames = [c.strip() for c in sql_f.split(', ')]
if query:
sql_w = ' WHERE ' + self.expand(query)
else:
sql_w = ''
sql_o = ''
sql_s = ''
left = attributes.get('left', False)
inner_join = attributes.get('join', False)
distinct = attributes.get('distinct', False)
groupby = attributes.get('groupby', False)
orderby = attributes.get('orderby', False)
having = attributes.get('having', False)
limitby = attributes.get('limitby', False)
for_update = attributes.get('for_update', False)
if self.can_select_for_update is False and for_update is True:
raise SyntaxError, 'invalid select attribute: for_update'
if distinct is True:
sql_s += 'DISTINCT'
elif distinct:
sql_s += 'DISTINCT ON (%s)' % distinct
if inner_join:
icommand = self.JOIN()
if not isinstance(inner_join, (tuple, list)):
inner_join = [inner_join]
ijoint = [t._tablename for t in inner_join if not isinstance(t,Expression)]
ijoinon = [t for t in inner_join if isinstance(t, Expression)]
itables_to_merge={} #issue 490
[itables_to_merge.update(dict.fromkeys(self.tables(t))) for t in ijoinon] # issue 490
ijoinont = [t.first._tablename for t in ijoinon]
[itables_to_merge.pop(t) for t in ijoinont if t in itables_to_merge] #issue 490
iimportant_tablenames = ijoint + ijoinont + itables_to_merge.keys() # issue 490
iexcluded = [t for t in tablenames if not t in iimportant_tablenames]
if left:
join = attributes['left']
command = self.LEFT_JOIN()
if not isinstance(join, (tuple, list)):
join = [join]
joint = [t._tablename for t in join if not isinstance(t, Expression)]
joinon = [t for t in join if isinstance(t, Expression)]
#patch join+left patch (solves problem with ordering in left joins)
tables_to_merge={}
[tables_to_merge.update(dict.fromkeys(self.tables(t))) for t in joinon]
joinont = [t.first._tablename for t in joinon]
[tables_to_merge.pop(t) for t in joinont if t in tables_to_merge]
important_tablenames = joint + joinont + tables_to_merge.keys()
excluded = [t for t in tablenames if not t in important_tablenames ]
def alias(t):
return str(self.db[t])
if inner_join and not left:
sql_t = ', '.join([alias(t) for t in iexcluded + itables_to_merge.keys()]) # issue 490
for t in ijoinon:
sql_t += ' %s %s' % (icommand, str(t))
elif not inner_join and left:
sql_t = ', '.join([alias(t) for t in excluded + tables_to_merge.keys()])
if joint:
sql_t += ' %s %s' % (command, ','.join([t for t in joint]))
for t in joinon:
sql_t += ' %s %s' % (command, str(t))
elif inner_join and left:
all_tables_in_query = set(important_tablenames + \
iimportant_tablenames + \
tablenames) # issue 490
tables_in_joinon = set(joinont + ijoinont) # issue 490
tables_not_in_joinon = all_tables_in_query.difference(tables_in_joinon) # issue 490
sql_t = ','.join([alias(t) for t in tables_not_in_joinon]) # issue 490
for t in ijoinon:
sql_t += ' %s %s' % (icommand, str(t))
if joint:
sql_t += ' %s %s' % (command, ','.join([t for t in joint]))
for t in joinon:
sql_t += ' %s %s' % (command, str(t))
else:
sql_t = ', '.join(alias(t) for t in tablenames)
if groupby:
if isinstance(groupby, (list, tuple)):
groupby = xorify(groupby)
sql_o += ' GROUP BY %s' % self.expand(groupby)
if having:
sql_o += ' HAVING %s' % attributes['having']
if orderby:
if isinstance(orderby, (list, tuple)):
orderby = xorify(orderby)
if str(orderby) == '<random>':
sql_o += ' ORDER BY %s' % self.RANDOM()
else:
sql_o += ' ORDER BY %s' % self.expand(orderby)
if limitby:
if not orderby and tablenames:
sql_o += ' ORDER BY %s' % ', '.join(['%s.%s'%(t,x) for t in tablenames for x in ((hasattr(self.db[t], '_primarykey') and self.db[t]._primarykey) or [self.db[t]._id.name])])
# oracle does not support limitby
sql = self.select_limitby(sql_s, sql_f, sql_t, sql_w, sql_o, limitby)
if for_update and self.can_select_for_update is True:
sql = sql.rstrip(';') + ' FOR UPDATE;'
return sql
def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby):
if limitby:
(lmin, lmax) = limitby
sql_o += ' LIMIT %i OFFSET %i' % (lmax - lmin, lmin)
return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o)
def select(self, query, fields, attributes):
"""
Always returns a Rows object, possibly empty.
"""
def response(sql):
self.execute(sql)
return self.cursor.fetchall()
sql = self._select(query, fields, attributes)
if attributes.get('cache', None):
(cache_model, time_expire) = attributes['cache']
del attributes['cache']
key = self.uri + '/' + sql
key = (len(key)<=200) and key or hashlib.md5(key).hexdigest()
rows = cache_model(key, lambda: response(sql), time_expire)
else:
rows = response(sql)
if isinstance(rows,tuple):
rows = list(rows)
limitby = attributes.get('limitby', None) or (0,)
rows = self.rowslice(rows,limitby[0],None)
return self.parse(rows,fields,self._colnames)
def _count(self, query, distinct=None):
tablenames = self.tables(query)
if query:
if use_common_filters(query):
query = self.common_filter(query, tablenames)
sql_w = ' WHERE ' + self.expand(query)
else:
sql_w = ''
sql_t = ','.join(tablenames)
if distinct:
if isinstance(distinct,(list, tuple)):
distinct = xorify(distinct)
sql_d = self.expand(distinct)
return 'SELECT count(DISTINCT %s) FROM %s%s;' % (sql_d, sql_t, sql_w)
return 'SELECT count(*) FROM %s%s;' % (sql_t, sql_w)
def count(self, query, distinct=None):
self.execute(self._count(query, distinct))
return self.cursor.fetchone()[0]
def tables(self, query):
tables = set()
if isinstance(query, Field):
tables.add(query.tablename)
elif isinstance(query, (Expression, Query)):
if not query.first is None:
tables = tables.union(self.tables(query.first))
if not query.second is None:
tables = tables.union(self.tables(query.second))
return list(tables)
def commit(self):
return self.connection.commit()
def rollback(self):
return self.connection.rollback()
def close(self):
return self.connection.close()
def distributed_transaction_begin(self, key):
return
def prepare(self, key):
self.connection.prepare()
def commit_prepared(self, key):
self.connection.commit()
def rollback_prepared(self, key):
self.connection.rollback()
def concat_add(self, table):
return ', ADD '
def constraint_name(self, table, fieldname):
return '%s_%s__constraint' % (table,fieldname)
def create_sequence_and_triggers(self, query, table, **args):
self.execute(query)
def log_execute(self, *a, **b):
self.db._lastsql = a[0]
t0 = time.time()
ret = self.cursor.execute(*a, **b)
self.db._timings.append((a[0],time.time()-t0))
del self.db._timings[:-TIMINGSSIZE]
return ret
def execute(self, *a, **b):
return self.log_execute(*a, **b)
def represent(self, obj, fieldtype):
if isinstance(obj, CALLABLETYPES):
obj = obj()
if isinstance(fieldtype, SQLCustomType):
return fieldtype.encoder(obj)
if isinstance(obj, (Expression, Field)):
return str(obj)
if fieldtype.startswith('list:'):
if not obj:
obj = []
elif not isinstance(obj, (list, tuple)):
obj = [int(obj)]
elif fieldtype.startswith('list:string'):
obj = [str(item) for item in obj]
else:
obj = [int(item) for item in obj]
if isinstance(obj, (list, tuple)):
obj = bar_encode(obj)
if obj is None:
return 'NULL'
if obj == '' and not fieldtype[:2] in ['st', 'te', 'pa', 'up']:
return 'NULL'
r = self.represent_exceptions(obj, fieldtype)
if not r is None:
return r
if fieldtype == 'boolean':
if obj and not str(obj)[:1].upper() in ['F', '0']:
return "'T'"
else:
return "'F'"
if fieldtype == 'id' or fieldtype == 'integer':
return str(int(obj))
if fieldtype.startswith('decimal'):
return str(obj)
elif fieldtype.startswith('reference'): # reference
if fieldtype.find('.')>0:
return repr(obj)
elif isinstance(obj, (Row, Reference)):
return str(obj['id'])
return str(int(obj))
elif fieldtype == 'double':
return repr(float(obj))
if isinstance(obj, unicode):
obj = obj.encode(self.db_codec)
if fieldtype == 'blob':
obj = base64.b64encode(str(obj))
elif fieldtype == 'date':
if isinstance(obj, (datetime.date, datetime.datetime)):
obj = obj.isoformat()[:10]
else:
obj = str(obj)
elif fieldtype == 'datetime':
if isinstance(obj, datetime.datetime):
obj = obj.isoformat()[:19].replace('T',' ')
elif isinstance(obj, datetime.date):
obj = obj.isoformat()[:10]+' 00:00:00'
else:
obj = str(obj)
elif fieldtype == 'time':
if isinstance(obj, datetime.time):
obj = obj.isoformat()[:10]
else:
obj = str(obj)
if not isinstance(obj,str):
obj = str(obj)
try:
obj.decode(self.db_codec)
except:
obj = obj.decode('latin1').encode(self.db_codec)
return self.adapt(obj)
def represent_exceptions(self, obj, fieldtype):
return None
def lastrowid(self, table):
return None
def integrity_error_class(self):
return type(None)
def rowslice(self, rows, minimum=0, maximum=None):
""" By default this function does nothing; overload when db does not do slicing. """
return rows
def parse_value(self, value, field_type, blob_decode=True):
if field_type != 'blob' and isinstance(value, str):
try:
value = value.decode(self.db._db_codec)
except Exception:
pass
if isinstance(value, unicode):
value = value.encode('utf-8')
elif isinstance(field_type, SQLCustomType):
value = field_type.decoder(value)
if not isinstance(field_type, str) or value is None:
return value
elif field_type in ('string', 'text', 'password', 'upload'):
return value
elif field_type == 'blob' and not blob_decode:
return value
else:
key = regex_type.match(field_type).group(0)
return self.parsemap[key](value,field_type)
def parse_reference(self, value, field_type):
referee = field_type[10:].strip()
if not '.' in referee:
value = Reference(value)
value._table, value._record = self.db[referee], None
return value
def parse_boolean(self, value, field_type):
return value == True or str(value)[:1].lower() == 't'
def parse_date(self, value, field_type):
if not isinstance(value, (datetime.date,datetime.datetime)):
(y, m, d) = map(int, str(value)[:10].strip().split('-'))
value = datetime.date(y, m, d)
return value
def parse_time(self, value, field_type):
if not isinstance(value, datetime.time):
time_items = map(int,str(value)[:8].strip().split(':')[:3])
if len(time_items) == 3:
(h, mi, s) = time_items
else:
(h, mi, s) = time_items + [0]
value = datetime.time(h, mi, s)
return value
def parse_datetime(self, value, field_type):
if not isinstance(value, datetime.datetime):
(y, m, d) = map(int,str(value)[:10].strip().split('-'))
time_items = map(int,str(value)[11:19].strip().split(':')[:3])
if len(time_items) == 3:
(h, mi, s) = time_items
else:
(h, mi, s) = time_items + [0]
value = datetime.datetime(y, m, d, h, mi, s)
return value
def parse_blob(self, value, field_type):
return base64.b64decode(str(value))
def parse_decimal(self, value, field_type):
decimals = int(field_type[8:-1].split(',')[-1])
if self.dbengine == 'sqlite':
value = ('%.' + str(decimals) + 'f') % value
if not isinstance(value, decimal.Decimal):
value = decimal.Decimal(str(value))
return value
def parse_list_integers(self, value, field_type):
if not self.dbengine=='google:datastore':
value = bar_decode_integer(value)
return value
def parse_list_references(self, value, field_type):
if not self.dbengine=='google:datastore':
value = bar_decode_integer(value)
return [self.parse_reference(r, field_type[5:]) for r in value]
def parse_list_strings(self, value, field_type):
if not self.dbengine=='google:datastore':
value = bar_decode_string(value)
return value
def parse_id(self, value, field_type):
return int(value)
def parse_integer(self, value, field_type):
return int(value)
def parse_double(self, value, field_type):
return float(value)
def build_parsemap(self):
self.parsemap = {
'id':self.parse_id,
'integer':self.parse_integer,
'double':self.parse_double,
'reference':self.parse_reference,
'boolean':self.parse_boolean,
'date':self.parse_date,
'time':self.parse_time,
'datetime':self.parse_datetime,
'blob':self.parse_blob,
'decimal':self.parse_decimal,
'list:integer':self.parse_list_integers,
'list:reference':self.parse_list_references,
'list:string':self.parse_list_strings,
}
def parse(self, rows, fields, colnames, blob_decode=True):
self.build_parsemap()
db = self.db
virtualtables = []
new_rows = []
for (i,row) in enumerate(rows):
new_row = Row()
for j,colname in enumerate(colnames):
value = row[j]
if not regex_table_field.match(colnames[j]):
if not '_extra' in new_row:
new_row['_extra'] = Row()
new_row['_extra'][colnames[j]] = \
self.parse_value(value, fields[j].type,blob_decode)
new_column_name = \
regex_select_as_parser.search(colnames[j])
if not new_column_name is None:
column_name = new_column_name.groups(0)
setattr(new_row,column_name[0],value)
else:
(tablename, fieldname) = colname.split('.')
table = db[tablename]
field = table[fieldname]
if not tablename in new_row:
colset = new_row[tablename] = Row()
if tablename not in virtualtables:
virtualtables.append(tablename)
else:
colset = new_row[tablename]
colset[fieldname] = value = \
self.parse_value(value,field.type,blob_decode)
if field.type == 'id':
id = value
colset.update_record = lambda _ = (colset, table, id), **a: update_record(_, a)
colset.delete_record = lambda t = table, i = id: t._db(t._id==i).delete()
for (referee_table, referee_name) in table._referenced_by:
s = db[referee_table][referee_name]
referee_link = db._referee_name and \
db._referee_name % dict(table=referee_table,field=referee_name)
if referee_link and not referee_link in colset:
colset[referee_link] = Set(db, s == id)
new_rows.append(new_row)
rowsobj = Rows(db, new_rows, colnames, rawrows=rows)
for tablename in virtualtables:
### new style virtual fields
table = db[tablename]
fields_virtual = [(f,v) for (f,v) in table.items() if isinstance(v,FieldVirtual)]
fields_lazy = [(f,v) for (f,v) in table.items() if isinstance(v,FieldLazy)]
if fields_virtual or fields_lazy:
for row in rowsobj.records:
box = row[tablename]
for f,v in fields_virtual:
box[f] = v.f(row)
for f,v in fields_lazy:
box[f] = (v.handler or VirtualCommand)(v.f,row)
### old style virtual fields
for item in table.virtualfields:
try:
rowsobj = rowsobj.setvirtualfields(**{tablename:item})
except KeyError:
# to avoid breaking virtualfields when partial select
pass
return rowsobj
def common_filter(self, query, tablenames):
tenant_fieldname = self.db._request_tenant
for tablename in tablenames:
table = self.db[tablename]
# deal with user provided filters
if table._common_filter != None:
query = query & table._common_filter(query)
# deal with multi_tenant filters
if tenant_fieldname in table:
default = table[tenant_fieldname].default
if not default is None:
newquery = table[tenant_fieldname] == default
if query is None:
query = newquery
else:
query = query & newquery
return query
###################################################################################
# List of all the available adapters; they all extend BaseAdapter.
###################################################################################
class SQLiteAdapter(BaseAdapter):
driver = globals().get('sqlite3', None)
can_select_for_update = None # support ourselves with BEGIN TRANSACTION
def EXTRACT(self,field,what):
return "web2py_extract('%s',%s)" % (what, self.expand(field))
@staticmethod
def web2py_extract(lookup, s):
table = {
'year': (0, 4),
'month': (5, 7),
'day': (8, 10),
'hour': (11, 13),
'minute': (14, 16),
'second': (17, 19),
}
try:
(i, j) = table[lookup]
return int(s[i:j])
except:
return None
@staticmethod
def web2py_regexp(expression, item):
return re.compile(expression).search(item) is not None
def __init__(self, db, uri, pool_size=0, folder=None, db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "sqlite"
self.uri = uri
self.pool_size = 0
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
path_encoding = sys.getfilesystemencoding() or locale.getdefaultlocale()[1] or 'utf8'
if uri.startswith('sqlite:memory'):
dbpath = ':memory:'
else:
dbpath = uri.split('://')[1]
if dbpath[0] != '/':
dbpath = os.path.join(self.folder.decode(path_encoding).encode('utf8'), dbpath)
if not 'check_same_thread' in driver_args:
driver_args['check_same_thread'] = False
if not 'detect_types' in driver_args:
driver_args['detect_types'] = self.driver.PARSE_DECLTYPES
def connect(dbpath=dbpath, driver_args=driver_args):
return self.driver.Connection(dbpath, **driver_args)
self.pool_connection(connect)
self.connection.create_function('web2py_extract', 2,
SQLiteAdapter.web2py_extract)
self.connection.create_function("REGEXP", 2,
SQLiteAdapter.web2py_regexp)
def _truncate(self, table, mode=''):
tablename = table._tablename
return ['DELETE FROM %s;' % tablename,
"DELETE FROM sqlite_sequence WHERE name='%s';" % tablename]
def lastrowid(self, table):
return self.cursor.lastrowid
def REGEXP(self,first,second):
return '(%s REGEXP %s)' % (self.expand(first),
self.expand(second,'string'))
def _select(self, query, fields, attributes):
"""
Simulate SELECT ... FOR UPDATE with BEGIN IMMEDIATE TRANSACTION.
Note that the entire database, rather than one record, is locked
(it will be locked eventually anyway by the following UPDATE).
"""
sql = super(SQLiteAdapter, self)._select(query, fields, attributes)
if attributes.get('for_update', False):
sql = 'BEGIN IMMEDIATE TRANSACTION; ' + sql
return sql
class JDBCSQLiteAdapter(SQLiteAdapter):
driver = globals().get('zxJDBC', None)
def __init__(self, db, uri, pool_size=0, folder=None, db_codec='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "sqlite"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
path_encoding = sys.getfilesystemencoding() or locale.getdefaultlocale()[1] or 'utf8'
if uri.startswith('sqlite:memory'):
dbpath = ':memory:'
else:
dbpath = uri.split('://')[1]
if dbpath[0] != '/':
dbpath = os.path.join(self.folder.decode(path_encoding).encode('utf8'), dbpath)
def connect(dbpath=dbpath,driver_args=driver_args):
return self.driver.connect(java.sql.DriverManager.getConnection('jdbc:sqlite:'+dbpath), **driver_args)
self.pool_connection(connect)
# FIXME http://www.zentus.com/sqlitejdbc/custom_functions.html for UDFs
self.connection.create_function('web2py_extract', 2, SQLiteAdapter.web2py_extract)
def execute(self, a):
return self.log_execute(a)
class MySQLAdapter(BaseAdapter):
driver = globals().get('pymysql',None)
maxcharlength = 255
commit_on_alter_table = True
support_distributed_transaction = True
types = {
'boolean': 'CHAR(1)',
'string': 'VARCHAR(%(length)s)',
'text': 'LONGTEXT',
'password': 'VARCHAR(%(length)s)',
'blob': 'LONGBLOB',
'upload': 'VARCHAR(%(length)s)',
'integer': 'INT',
'double': 'DOUBLE',
'decimal': 'NUMERIC(%(precision)s,%(scale)s)',
'date': 'DATE',
'time': 'TIME',
'datetime': 'DATETIME',
'id': 'INT AUTO_INCREMENT NOT NULL',
'reference': 'INT, INDEX %(field_name)s__idx (%(field_name)s), FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'list:integer': 'LONGTEXT',
'list:string': 'LONGTEXT',
'list:reference': 'LONGTEXT',
}
def RANDOM(self):
return 'RAND()'
def SUBSTRING(self,field,parameters):
return 'SUBSTRING(%s,%s,%s)' % (self.expand(field), parameters[0], parameters[1])
def _drop(self,table,mode):
# breaks db integrity but without this mysql does not drop table
return ['SET FOREIGN_KEY_CHECKS=0;','DROP TABLE %s;' % table,'SET FOREIGN_KEY_CHECKS=1;']
def distributed_transaction_begin(self,key):
self.execute('XA START;')
def prepare(self,key):
self.execute("XA END;")
self.execute("XA PREPARE;")
def commit_prepared(self,ley):
self.execute("XA COMMIT;")
def rollback_prepared(self,key):
self.execute("XA ROLLBACK;")
def concat_add(self,table):
return '; ALTER TABLE %s ADD ' % table
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "mysql"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
uri = uri.split('://')[1]
m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^?]+)(\?set_encoding=(?P<charset>\w+))?$').match(uri)
if not m:
raise SyntaxError, \
"Invalid URI string in DAL: %s" % self.uri
user = credential_decoder(m.group('user'))
if not user:
raise SyntaxError, 'User required'
password = credential_decoder(m.group('password'))
if not password:
password = ''
host = m.group('host')
if not host:
raise SyntaxError, 'Host name required'
db = m.group('db')
if not db:
raise SyntaxError, 'Database name required'
port = int(m.group('port') or '3306')
charset = m.group('charset') or 'utf8'
driver_args.update(dict(db=db,
user=credential_decoder(user),
passwd=credential_decoder(password),
host=host,
port=port,
charset=charset))
def connect(driver_args=driver_args):
return self.driver.connect(**driver_args)
self.pool_connection(connect)
self.execute('SET FOREIGN_KEY_CHECKS=1;')
self.execute("SET sql_mode='NO_BACKSLASH_ESCAPES';")
def lastrowid(self,table):
self.execute('select last_insert_id();')
return int(self.cursor.fetchone()[0])
class PostgreSQLAdapter(BaseAdapter):
driver = None
drivers = {'psycopg2': globals().get('psycopg2', None),
'pg8000': globals().get('pg8000', None), }
support_distributed_transaction = True
types = {
'boolean': 'CHAR(1)',
'string': 'VARCHAR(%(length)s)',
'text': 'TEXT',
'password': 'VARCHAR(%(length)s)',
'blob': 'BYTEA',
'upload': 'VARCHAR(%(length)s)',
'integer': 'INTEGER',
'double': 'FLOAT8',
'decimal': 'NUMERIC(%(precision)s,%(scale)s)',
'date': 'DATE',
'time': 'TIME',
'datetime': 'TIMESTAMP',
'id': 'SERIAL PRIMARY KEY',
'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'list:integer': 'TEXT',
'list:string': 'TEXT',
'list:reference': 'TEXT',
}
def adapt(self,obj):
return psycopg2_adapt(obj).getquoted()
def sequence_name(self,table):
return '%s_id_Seq' % table
def RANDOM(self):
return 'RANDOM()'
def ADD(self, first, second):
t = first.type
if t in ('text','string','password','upload','blob'):
return '(%s || %s)' % (self.expand(first), self.expand(second, t))
else:
return '(%s + %s)' % (self.expand(first), self.expand(second, t))
def distributed_transaction_begin(self,key):
return
def prepare(self,key):
self.execute("PREPARE TRANSACTION '%s';" % key)
def commit_prepared(self,key):
self.execute("COMMIT PREPARED '%s';" % key)
def rollback_prepared(self,key):
self.execute("ROLLBACK PREPARED '%s';" % key)
def create_sequence_and_triggers(self, query, table, **args):
# following lines should only be executed if table._sequence_name does not exist
# self.execute('CREATE SEQUENCE %s;' % table._sequence_name)
# self.execute("ALTER TABLE %s ALTER COLUMN %s SET DEFAULT NEXTVAL('%s');" \
# % (table._tablename, table._fieldname, table._sequence_name))
self.execute(query)
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.drivers.get('psycopg2') and not self.drivers.get('pg8000'):
raise RuntimeError, "Unable to import any drivers (psycopg2 or pg8000)"
self.db = db
self.dbengine = "postgres"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
library, uri = uri.split('://')[:2]
m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:@/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^\?]+)(\?sslmode=(?P<sslmode>.+))?$').match(uri)
if not m:
raise SyntaxError, "Invalid URI string in DAL"
user = credential_decoder(m.group('user'))
if not user:
raise SyntaxError, 'User required'
password = credential_decoder(m.group('password'))
if not password:
password = ''
host = m.group('host')
if not host:
raise SyntaxError, 'Host name required'
db = m.group('db')
if not db:
raise SyntaxError, 'Database name required'
port = m.group('port') or '5432'
sslmode = m.group('sslmode')
if sslmode:
msg = ("dbname='%s' user='%s' host='%s' "
"port=%s password='%s' sslmode='%s'") \
% (db, user, host, port, password, sslmode)
else:
msg = ("dbname='%s' user='%s' host='%s' "
"port=%s password='%s'") \
% (db, user, host, port, password)
# choose diver according uri
if library == "postgres":
if self.drivers.get('psycopg2'):
self.driver = self.drivers['psycopg2']
elif self.drivers.get('pg8000'):
self.driver = drivers.get('pg8000')
elif library == "postgres:psycopg2":
self.driver = self.drivers.get('psycopg2')
elif library == "postgres:pg8000":
self.driver = self.drivers.get('pg8000')
if not self.driver:
raise RuntimeError, "%s is not available" % library
self.__version__ = "%s %s" % (self.driver.__name__, self.driver.__version__)
def connect(msg=msg,driver_args=driver_args):
return self.driver.connect(msg,**driver_args)
self.pool_connection(connect)
self.connection.set_client_encoding('UTF8')
self.execute("SET standard_conforming_strings=on;")
def lastrowid(self,table):
self.execute("select currval('%s')" % table._sequence_name)
return int(self.cursor.fetchone()[0])
def LIKE(self,first,second):
return '(%s LIKE %s)' % (self.expand(first),
self.expand(second,'string'))
def ILIKE(self,first,second):
return '(%s ILIKE %s)' % (self.expand(first),
self.expand(second,'string'))
def REGEXP(self,first,second):
return '(%s ~ %s)' % (self.expand(first),
self.expand(second,'string'))
def STARTSWITH(self,first,second):
return '(%s ILIKE %s)' % (self.expand(first),
self.expand(second+'%','string'))
def ENDSWITH(self,first,second):
return '(%s ILIKE %s)' % (self.expand(first),
self.expand('%'+second,'string'))
def CONTAINS(self,first,second):
if first.type in ('string','text'):
key = '%'+str(second).replace('%','%%')+'%'
elif first.type.startswith('list:'):
key = '%|'+str(second).replace('|','||').replace('%','%%')+'|%'
return '(%s ILIKE %s)' % (self.expand(first),self.expand(key,'string'))
class JDBCPostgreSQLAdapter(PostgreSQLAdapter):
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "postgres"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
uri = uri.split('://')[1]
m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>.+)$').match(uri)
if not m:
raise SyntaxError, "Invalid URI string in DAL"
user = credential_decoder(m.group('user'))
if not user:
raise SyntaxError, 'User required'
password = credential_decoder(m.group('password'))
if not password:
password = ''
host = m.group('host')
if not host:
raise SyntaxError, 'Host name required'
db = m.group('db')
if not db:
raise SyntaxError, 'Database name required'
port = m.group('port') or '5432'
msg = ('jdbc:postgresql://%s:%s/%s' % (host, port, db), user, password)
def connect(msg=msg,driver_args=driver_args):
return self.driver.connect(*msg,**driver_args)
self.pool_connection(connect)
self.connection.set_client_encoding('UTF8')
self.execute('BEGIN;')
self.execute("SET CLIENT_ENCODING TO 'UNICODE';")
class OracleAdapter(BaseAdapter):
driver = globals().get('cx_Oracle',None)
commit_on_alter_table = False
types = {
'boolean': 'CHAR(1)',
'string': 'VARCHAR2(%(length)s)',
'text': 'CLOB',
'password': 'VARCHAR2(%(length)s)',
'blob': 'CLOB',
'upload': 'VARCHAR2(%(length)s)',
'integer': 'INT',
'double': 'FLOAT',
'decimal': 'NUMERIC(%(precision)s,%(scale)s)',
'date': 'DATE',
'time': 'CHAR(8)',
'datetime': 'DATE',
'id': 'NUMBER PRIMARY KEY',
'reference': 'NUMBER, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s',
'list:integer': 'CLOB',
'list:string': 'CLOB',
'list:reference': 'CLOB',
}
def sequence_name(self,tablename):
return '%s_sequence' % tablename
def trigger_name(self,tablename):
return '%s_trigger' % tablename
def LEFT_JOIN(self):
return 'LEFT OUTER JOIN'
def RANDOM(self):
return 'dbms_random.value'
def NOT_NULL(self,default,field_type):
return 'DEFAULT %s NOT NULL' % self.represent(default,field_type)
def _drop(self,table,mode):
sequence_name = table._sequence_name
return ['DROP TABLE %s %s;' % (table, mode), 'DROP SEQUENCE %s;' % sequence_name]
def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby):
if limitby:
(lmin, lmax) = limitby
if len(sql_w) > 1:
sql_w_row = sql_w + ' AND w_row > %i' % lmin
else:
sql_w_row = 'WHERE w_row > %i' % lmin
return 'SELECT %s %s FROM (SELECT w_tmp.*, ROWNUM w_row FROM (SELECT %s FROM %s%s%s) w_tmp WHERE ROWNUM<=%i) %s %s %s;' % (sql_s, sql_f, sql_f, sql_t, sql_w, sql_o, lmax, sql_t, sql_w_row, sql_o)
return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o)
def constraint_name(self, tablename, fieldname):
constraint_name = BaseAdapter.constraint_name(self, tablename, fieldname)
if len(constraint_name)>30:
constraint_name = '%s_%s__constraint' % (tablename[:10], fieldname[:7])
return constraint_name
def represent_exceptions(self, obj, fieldtype):
if fieldtype == 'blob':
obj = base64.b64encode(str(obj))
return ":CLOB('%s')" % obj
elif fieldtype == 'date':
if isinstance(obj, (datetime.date, datetime.datetime)):
obj = obj.isoformat()[:10]
else:
obj = str(obj)
return "to_date('%s','yyyy-mm-dd')" % obj
elif fieldtype == 'datetime':
if isinstance(obj, datetime.datetime):
obj = obj.isoformat()[:19].replace('T',' ')
elif isinstance(obj, datetime.date):
obj = obj.isoformat()[:10]+' 00:00:00'
else:
obj = str(obj)
return "to_date('%s','yyyy-mm-dd hh24:mi:ss')" % obj
return None
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "oracle"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
uri = uri.split('://')[1]
if not 'threaded' in driver_args:
driver_args['threaded']=True
def connect(uri=uri,driver_args=driver_args):
return self.driver.connect(uri,**driver_args)
self.pool_connection(connect)
self.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';")
self.execute("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS';")
oracle_fix = re.compile("[^']*('[^']*'[^']*)*\:(?P<clob>CLOB\('([^']+|'')*'\))")
def execute(self, command, args=None):
args = args or []
i = 1
while True:
m = self.oracle_fix.match(command)
if not m:
break
command = command[:m.start('clob')] + str(i) + command[m.end('clob'):]
args.append(m.group('clob')[6:-2].replace("''", "'"))
i += 1
if command[-1:]==';':
command = command[:-1]
return self.log_execute(command, args)
def create_sequence_and_triggers(self, query, table, **args):
tablename = table._tablename
sequence_name = table._sequence_name
trigger_name = table._trigger_name
self.execute(query)
self.execute('CREATE SEQUENCE %s START WITH 1 INCREMENT BY 1 NOMAXVALUE;' % sequence_name)
self.execute('CREATE OR REPLACE TRIGGER %s BEFORE INSERT ON %s FOR EACH ROW BEGIN SELECT %s.nextval INTO :NEW.id FROM DUAL; END;\n' % (trigger_name, tablename, sequence_name))
def lastrowid(self,table):
sequence_name = table._sequence_name
self.execute('SELECT %s.currval FROM dual;' % sequence_name)
return int(self.cursor.fetchone()[0])
class MSSQLAdapter(BaseAdapter):
driver = globals().get('pyodbc',None)
types = {
'boolean': 'BIT',
'string': 'VARCHAR(%(length)s)',
'text': 'TEXT',
'password': 'VARCHAR(%(length)s)',
'blob': 'IMAGE',
'upload': 'VARCHAR(%(length)s)',
'integer': 'INT',
'double': 'FLOAT',
'decimal': 'NUMERIC(%(precision)s,%(scale)s)',
'date': 'DATETIME',
'time': 'CHAR(8)',
'datetime': 'DATETIME',
'id': 'INT IDENTITY PRIMARY KEY',
'reference': 'INT NULL, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s',
'list:integer': 'TEXT',
'list:string': 'TEXT',
'list:reference': 'TEXT',
}
def EXTRACT(self,field,what):
return "DATEPART(%s,%s)" % (what, self.expand(field))
def LEFT_JOIN(self):
return 'LEFT OUTER JOIN'
def RANDOM(self):
return 'NEWID()'
def ALLOW_NULL(self):
return ' NULL'
def SUBSTRING(self,field,parameters):
return 'SUBSTRING(%s,%s,%s)' % (self.expand(field), parameters[0], parameters[1])
def PRIMARY_KEY(self,key):
return 'PRIMARY KEY CLUSTERED (%s)' % key
def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby):
if limitby:
(lmin, lmax) = limitby
sql_s += ' TOP %i' % lmax
return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o)
def represent_exceptions(self, obj, fieldtype):
if fieldtype == 'boolean':
if obj and not str(obj)[0].upper() == 'F':
return '1'
else:
return '0'
return None
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}, fake_connect=False):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "mssql"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
# ## read: http://bytes.com/groups/python/460325-cx_oracle-utf8
uri = uri.split('://')[1]
if '@' not in uri:
try:
m = re.compile('^(?P<dsn>.+)$').match(uri)
if not m:
raise SyntaxError, \
'Parsing uri string(%s) has no result' % self.uri
dsn = m.group('dsn')
if not dsn:
raise SyntaxError, 'DSN required'
except SyntaxError, e:
logger.error('NdGpatch error')
raise e
# was cnxn = 'DSN=%s' % dsn
cnxn = dsn
else:
m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^\?]+)(\?(?P<urlargs>.*))?$').match(uri)
if not m:
raise SyntaxError, \
"Invalid URI string in DAL: %s" % uri
user = credential_decoder(m.group('user'))
if not user:
raise SyntaxError, 'User required'
password = credential_decoder(m.group('password'))
if not password:
password = ''
host = m.group('host')
if not host:
raise SyntaxError, 'Host name required'
db = m.group('db')
if not db:
raise SyntaxError, 'Database name required'
port = m.group('port') or '1433'
# Parse the optional url name-value arg pairs after the '?'
# (in the form of arg1=value1&arg2=value2&...)
# Default values (drivers like FreeTDS insist on uppercase parameter keys)
argsdict = { 'DRIVER':'{SQL Server}' }
urlargs = m.group('urlargs') or ''
argpattern = re.compile('(?P<argkey>[^=]+)=(?P<argvalue>[^&]*)')
for argmatch in argpattern.finditer(urlargs):
argsdict[str(argmatch.group('argkey')).upper()] = argmatch.group('argvalue')
urlargs = ';'.join(['%s=%s' % (ak, av) for (ak, av) in argsdict.items()])
cnxn = 'SERVER=%s;PORT=%s;DATABASE=%s;UID=%s;PWD=%s;%s' \
% (host, port, db, user, password, urlargs)
def connect(cnxn=cnxn,driver_args=driver_args):
return self.driver.connect(cnxn,**driver_args)
if not fake_connect:
self.pool_connection(connect)
def lastrowid(self,table):
#self.execute('SELECT @@IDENTITY;')
self.execute('SELECT SCOPE_IDENTITY();')
return int(self.cursor.fetchone()[0])
def integrity_error_class(self):
return pyodbc.IntegrityError
def rowslice(self,rows,minimum=0,maximum=None):
if maximum is None:
return rows[minimum:]
return rows[minimum:maximum]
class MSSQL2Adapter(MSSQLAdapter):
types = {
'boolean': 'CHAR(1)',
'string': 'NVARCHAR(%(length)s)',
'text': 'NTEXT',
'password': 'NVARCHAR(%(length)s)',
'blob': 'IMAGE',
'upload': 'NVARCHAR(%(length)s)',
'integer': 'INT',
'double': 'FLOAT',
'decimal': 'NUMERIC(%(precision)s,%(scale)s)',
'date': 'DATETIME',
'time': 'CHAR(8)',
'datetime': 'DATETIME',
'id': 'INT IDENTITY PRIMARY KEY',
'reference': 'INT, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s',
'list:integer': 'NTEXT',
'list:string': 'NTEXT',
'list:reference': 'NTEXT',
}
def represent(self, obj, fieldtype):
value = BaseAdapter.represent(self, obj, fieldtype)
if (fieldtype == 'string' or fieldtype == 'text') and value[:1]=="'":
value = 'N'+value
return value
def execute(self,a):
return self.log_execute(a.decode('utf8'))
class FireBirdAdapter(BaseAdapter):
driver = globals().get('pyodbc',None)
commit_on_alter_table = False
support_distributed_transaction = True
types = {
'boolean': 'CHAR(1)',
'string': 'VARCHAR(%(length)s)',
'text': 'BLOB SUB_TYPE 1',
'password': 'VARCHAR(%(length)s)',
'blob': 'BLOB SUB_TYPE 0',
'upload': 'VARCHAR(%(length)s)',
'integer': 'INTEGER',
'double': 'DOUBLE PRECISION',
'decimal': 'DECIMAL(%(precision)s,%(scale)s)',
'date': 'DATE',
'time': 'TIME',
'datetime': 'TIMESTAMP',
'id': 'INTEGER PRIMARY KEY',
'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'list:integer': 'BLOB SUB_TYPE 1',
'list:string': 'BLOB SUB_TYPE 1',
'list:reference': 'BLOB SUB_TYPE 1',
}
def sequence_name(self,tablename):
return 'genid_%s' % tablename
def trigger_name(self,tablename):
return 'trg_id_%s' % tablename
def RANDOM(self):
return 'RAND()'
def NOT_NULL(self,default,field_type):
return 'DEFAULT %s NOT NULL' % self.represent(default,field_type)
def SUBSTRING(self,field,parameters):
return 'SUBSTRING(%s from %s for %s)' % (self.expand(field), parameters[0], parameters[1])
def _drop(self,table,mode):
sequence_name = table._sequence_name
return ['DROP TABLE %s %s;' % (table, mode), 'DROP GENERATOR %s;' % sequence_name]
def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby):
if limitby:
(lmin, lmax) = limitby
sql_s += ' FIRST %i SKIP %i' % (lmax - lmin, lmin)
return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o)
def _truncate(self,table,mode = ''):
return ['DELETE FROM %s;' % table._tablename,
'SET GENERATOR %s TO 0;' % table._sequence_name]
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if adapter_args.has_key('driver_name'):
if adapter_args['driver_name'] == 'kinterbasdb':
self.driver = kinterbasdb
elif adapter_args['driver_name'] == 'firebirdsql':
self.driver = firebirdsql
else:
self.driver = kinterbasdb
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "firebird"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
uri = uri.split('://')[1]
m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>.+?)(\?set_encoding=(?P<charset>\w+))?$').match(uri)
if not m:
raise SyntaxError, "Invalid URI string in DAL: %s" % uri
user = credential_decoder(m.group('user'))
if not user:
raise SyntaxError, 'User required'
password = credential_decoder(m.group('password'))
if not password:
password = ''
host = m.group('host')
if not host:
raise SyntaxError, 'Host name required'
port = int(m.group('port') or 3050)
db = m.group('db')
if not db:
raise SyntaxError, 'Database name required'
charset = m.group('charset') or 'UTF8'
driver_args.update(dict(dsn='%s/%s:%s' % (host,port,db),
user = credential_decoder(user),
password = credential_decoder(password),
charset = charset))
def connect(driver_args=driver_args):
return self.driver.connect(**driver_args)
self.pool_connection(connect)
def create_sequence_and_triggers(self, query, table, **args):
tablename = table._tablename
sequence_name = table._sequence_name
trigger_name = table._trigger_name
self.execute(query)
self.execute('create generator %s;' % sequence_name)
self.execute('set generator %s to 0;' % sequence_name)
self.execute('create trigger %s for %s active before insert position 0 as\nbegin\nif(new.id is null) then\nbegin\nnew.id = gen_id(%s, 1);\nend\nend;' % (trigger_name, tablename, sequence_name))
def lastrowid(self,table):
sequence_name = table._sequence_name
self.execute('SELECT gen_id(%s, 0) FROM rdb$database' % sequence_name)
return int(self.cursor.fetchone()[0])
class FireBirdEmbeddedAdapter(FireBirdAdapter):
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if adapter_args.has_key('driver_name'):
if adapter_args['driver_name'] == 'kinterbasdb':
self.driver = kinterbasdb
elif adapter_args['driver_name'] == 'firebirdsql':
self.driver = firebirdsql
else:
self.driver = kinterbasdb
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "firebird"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
uri = uri.split('://')[1]
m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<path>[^\?]+)(\?set_encoding=(?P<charset>\w+))?$').match(uri)
if not m:
raise SyntaxError, \
"Invalid URI string in DAL: %s" % self.uri
user = credential_decoder(m.group('user'))
if not user:
raise SyntaxError, 'User required'
password = credential_decoder(m.group('password'))
if not password:
password = ''
pathdb = m.group('path')
if not pathdb:
raise SyntaxError, 'Path required'
charset = m.group('charset')
if not charset:
charset = 'UTF8'
host = ''
driver_args.update(dict(host=host,
database=pathdb,
user=credential_decoder(user),
password=credential_decoder(password),
charset=charset))
#def connect(driver_args=driver_args):
# return kinterbasdb.connect(**driver_args)
def connect(driver_args=driver_args):
return self.driver.connect(**driver_args)
self.pool_connection(connect)
class InformixAdapter(BaseAdapter):
driver = globals().get('informixdb',None)
types = {
'boolean': 'CHAR(1)',
'string': 'VARCHAR(%(length)s)',
'text': 'BLOB SUB_TYPE 1',
'password': 'VARCHAR(%(length)s)',
'blob': 'BLOB SUB_TYPE 0',
'upload': 'VARCHAR(%(length)s)',
'integer': 'INTEGER',
'double': 'FLOAT',
'decimal': 'NUMERIC(%(precision)s,%(scale)s)',
'date': 'DATE',
'time': 'CHAR(8)',
'datetime': 'DATETIME',
'id': 'SERIAL',
'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference FK': 'REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s CONSTRAINT FK_%(table_name)s_%(field_name)s',
'reference TFK': 'FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s CONSTRAINT TFK_%(table_name)s_%(field_name)s',
'list:integer': 'BLOB SUB_TYPE 1',
'list:string': 'BLOB SUB_TYPE 1',
'list:reference': 'BLOB SUB_TYPE 1',
}
def RANDOM(self):
return 'Random()'
def NOT_NULL(self,default,field_type):
return 'DEFAULT %s NOT NULL' % self.represent(default,field_type)
def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby):
if limitby:
(lmin, lmax) = limitby
fetch_amt = lmax - lmin
dbms_version = int(self.connection.dbms_version.split('.')[0])
if lmin and (dbms_version >= 10):
# Requires Informix 10.0+
sql_s += ' SKIP %d' % (lmin, )
if fetch_amt and (dbms_version >= 9):
# Requires Informix 9.0+
sql_s += ' FIRST %d' % (fetch_amt, )
return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o)
def represent_exceptions(self, obj, fieldtype):
if fieldtype == 'date':
if isinstance(obj, (datetime.date, datetime.datetime)):
obj = obj.isoformat()[:10]
else:
obj = str(obj)
return "to_date('%s','%%Y-%%m-%%d')" % obj
elif fieldtype == 'datetime':
if isinstance(obj, datetime.datetime):
obj = obj.isoformat()[:19].replace('T',' ')
elif isinstance(obj, datetime.date):
obj = obj.isoformat()[:10]+' 00:00:00'
else:
obj = str(obj)
return "to_date('%s','%%Y-%%m-%%d %%H:%%M:%%S')" % obj
return None
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "informix"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
uri = uri.split('://')[1]
m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>.+)$').match(uri)
if not m:
raise SyntaxError, \
"Invalid URI string in DAL: %s" % self.uri
user = credential_decoder(m.group('user'))
if not user:
raise SyntaxError, 'User required'
password = credential_decoder(m.group('password'))
if not password:
password = ''
host = m.group('host')
if not host:
raise SyntaxError, 'Host name required'
db = m.group('db')
if not db:
raise SyntaxError, 'Database name required'
user = credential_decoder(user)
password = credential_decoder(password)
dsn = '%s@%s' % (db,host)
driver_args.update(dict(user=user,password=password,autocommit=True))
def connect(dsn=dsn,driver_args=driver_args):
return self.driver.connect(dsn,**driver_args)
self.pool_connection(connect)
def execute(self,command):
if command[-1:]==';':
command = command[:-1]
return self.log_execute(command)
def lastrowid(self,table):
return self.cursor.sqlerrd[1]
def integrity_error_class(self):
return informixdb.IntegrityError
class DB2Adapter(BaseAdapter):
driver = globals().get('pyodbc',None)
types = {
'boolean': 'CHAR(1)',
'string': 'VARCHAR(%(length)s)',
'text': 'CLOB',
'password': 'VARCHAR(%(length)s)',
'blob': 'BLOB',
'upload': 'VARCHAR(%(length)s)',
'integer': 'INT',
'double': 'DOUBLE',
'decimal': 'NUMERIC(%(precision)s,%(scale)s)',
'date': 'DATE',
'time': 'TIME',
'datetime': 'TIMESTAMP',
'id': 'INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY NOT NULL',
'reference': 'INT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s',
'list:integer': 'CLOB',
'list:string': 'CLOB',
'list:reference': 'CLOB',
}
def LEFT_JOIN(self):
return 'LEFT OUTER JOIN'
def RANDOM(self):
return 'RAND()'
def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby):
if limitby:
(lmin, lmax) = limitby
sql_o += ' FETCH FIRST %i ROWS ONLY' % lmax
return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o)
def represent_exceptions(self, obj, fieldtype):
if fieldtype == 'blob':
obj = base64.b64encode(str(obj))
return "BLOB('%s')" % obj
elif fieldtype == 'datetime':
if isinstance(obj, datetime.datetime):
obj = obj.isoformat()[:19].replace('T','-').replace(':','.')
elif isinstance(obj, datetime.date):
obj = obj.isoformat()[:10]+'-00.00.00'
return "'%s'" % obj
return None
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "db2"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
cnxn = uri.split('://', 1)[1]
def connect(cnxn=cnxn,driver_args=driver_args):
return self.driver.connect(cnxn,**driver_args)
self.pool_connection(connect)
def execute(self,command):
if command[-1:]==';':
command = command[:-1]
return self.log_execute(command)
def lastrowid(self,table):
self.execute('SELECT DISTINCT IDENTITY_VAL_LOCAL() FROM %s;' % table)
return int(self.cursor.fetchone()[0])
def rowslice(self,rows,minimum=0,maximum=None):
if maximum is None:
return rows[minimum:]
return rows[minimum:maximum]
class TeradataAdapter(BaseAdapter):
driver = globals().get('pyodbc',None)
types = {
'boolean': 'CHAR(1)',
'string': 'VARCHAR(%(length)s)',
'text': 'CLOB',
'password': 'VARCHAR(%(length)s)',
'blob': 'BLOB',
'upload': 'VARCHAR(%(length)s)',
'integer': 'INT',
'double': 'DOUBLE',
'decimal': 'NUMERIC(%(precision)s,%(scale)s)',
'date': 'DATE',
'time': 'TIME',
'datetime': 'TIMESTAMP',
'id': 'INTEGER GENERATED ALWAYS AS IDENTITY', # Teradata Specific
# Modified Constraint syntax for Teradata.
'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s)',
'list:integer': 'CLOB',
'list:string': 'CLOB',
'list:reference': 'CLOB',
}
def LEFT_JOIN(self):
return 'LEFT OUTER JOIN'
def create_table(self, table,
migrate=True,
fake_migrate=False,
polymodel=None):
fields = []
sql_fields = {}
sql_fields_aux = {}
TFK = {}
tablename = table._tablename
sortable = 0
for field in table:
sortable += 1
k = field.name
if isinstance(field.type,SQLCustomType):
ftype = field.type.native or field.type.type
elif field.type.startswith('reference'):
referenced = field.type[10:].strip()
constraint_name = self.constraint_name(tablename, field.name)
if hasattr(table,'_primarykey'):
rtablename,rfieldname = referenced.split('.')
rtable = table._db[rtablename]
rfield = rtable[rfieldname]
# must be PK reference or unique
if rfieldname in rtable._primarykey or rfield.unique:
ftype = self.types[rfield.type[:9]] % dict(length=rfield.length)
# multicolumn primary key reference?
if not rfield.unique and len(rtable._primarykey)>1 :
# then it has to be a table level FK
if rtablename not in TFK:
TFK[rtablename] = {}
TFK[rtablename][rfieldname] = field.name
else:
ftype = ftype + \
self.types['reference FK'] %dict(\
constraint_name=constraint_name,
table_name=tablename,
field_name=field.name,
foreign_key='%s (%s)'%(rtablename, rfieldname),
on_delete_action=field.ondelete)
else:
# make a guess here for circular references
id_fieldname = referenced in table._db and table._db[referenced]._id.name or 'id'
ftype = self.types[field.type[:9]]\
% dict(table_name=tablename,
field_name=field.name,
constraint_name=constraint_name,
foreign_key=referenced + ('(%s)' % id_fieldname),
on_delete_action=field.ondelete)
elif field.type.startswith('list:reference'):
ftype = self.types[field.type[:14]]
elif field.type.startswith('decimal'):
precision, scale = map(int,field.type[8:-1].split(','))
ftype = self.types[field.type[:7]] % \
dict(precision=precision,scale=scale)
elif not field.type in self.types:
raise SyntaxError, 'Field: unknown field type: %s for %s' % \
(field.type, field.name)
else:
ftype = self.types[field.type]\
% dict(length=field.length)
if not field.type.startswith('id') and not field.type.startswith('reference'):
if field.notnull:
ftype += ' NOT NULL'
else:
ftype += self.ALLOW_NULL()
if field.unique:
ftype += ' UNIQUE'
# add to list of fields
sql_fields[field.name] = dict(sortable=sortable,
type=str(field.type),
sql=ftype)
if isinstance(field.default,(str,int,float)):
# Caveat: sql_fields and sql_fields_aux differ for default values.
# sql_fields is used to trigger migrations and sql_fields_aux
# is used for create tables.
# The reason is that we do not want to trigger a migration simply
# because a default value changes.
not_null = self.NOT_NULL(field.default, field.type)
ftype = ftype.replace('NOT NULL', not_null)
sql_fields_aux[field.name] = dict(sql=ftype)
fields.append('%s %s' % (field.name, ftype))
other = ';'
fields = ',\n '.join(fields)
for rtablename in TFK:
rfields = TFK[rtablename]
pkeys = table._db[rtablename]._primarykey
fkeys = [ rfields[k] for k in pkeys ]
fields = fields + ',\n ' + \
self.types['reference TFK'] %\
dict(table_name=tablename,
field_name=', '.join(fkeys),
foreign_table=rtablename,
foreign_key=', '.join(pkeys),
on_delete_action=field.ondelete)
if hasattr(table,'_primarykey'):
query = '''CREATE TABLE %s(\n %s,\n %s) %s''' % \
(tablename, fields, self.PRIMARY_KEY(', '.join(table._primarykey)),other)
else:
query = '''CREATE TABLE %s(\n %s\n)%s''' % \
(tablename, fields, other)
if self.uri.startswith('sqlite:///'):
path_encoding = sys.getfilesystemencoding() or locale.getdefaultlocale()[1] or 'utf8'
dbpath = self.uri[9:self.uri.rfind('/')].decode('utf8').encode(path_encoding)
else:
dbpath = self.folder
if not migrate:
return query
elif self.uri.startswith('sqlite:memory'):
table._dbt = None
elif isinstance(migrate, str):
table._dbt = os.path.join(dbpath, migrate)
else:
table._dbt = os.path.join(dbpath, '%s_%s.table' \
% (table._db._uri_hash, tablename))
if table._dbt:
table._loggername = os.path.join(dbpath, 'sql.log')
logfile = self.file_open(table._loggername, 'a')
else:
logfile = None
if not table._dbt or not self.file_exists(table._dbt):
if table._dbt:
logfile.write('timestamp: %s\n'
% datetime.datetime.today().isoformat())
logfile.write(query + '\n')
if not fake_migrate:
self.create_sequence_and_triggers(query,table)
table._db.commit()
if table._dbt:
tfile = self.file_open(table._dbt, 'w')
cPickle.dump(sql_fields, tfile)
self.file_close(tfile)
if fake_migrate:
logfile.write('faked!\n')
else:
logfile.write('success!\n')
else:
tfile = self.file_open(table._dbt, 'r')
try:
sql_fields_old = cPickle.load(tfile)
except EOFError:
self.file_close(tfile)
self.file_close(logfile)
raise RuntimeError, 'File %s appears corrupted' % table._dbt
self.file_close(tfile)
if sql_fields != sql_fields_old:
self.migrate_table(table,
sql_fields, sql_fields_old,
sql_fields_aux, logfile,
fake_migrate=fake_migrate)
self.file_close(logfile)
return query
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "teradata"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
cnxn = uri.split('://', 1)[1]
def connect(cnxn=cnxn,driver_args=driver_args):
return self.driver.connect(cnxn,**driver_args)
self.pool_connection(connect)
# Similar to MSSQL, Teradata can't specify a range (for Pageby)
def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby):
if limitby:
(lmin, lmax) = limitby
sql_s += ' TOP %i' % lmax
return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o)
INGRES_SEQNAME='ii***lineitemsequence' # NOTE invalid database object name
# (ANSI-SQL wants this form of name
# to be a delimited identifier)
class IngresAdapter(BaseAdapter):
driver = globals().get('ingresdbi',None)
types = {
'boolean': 'CHAR(1)',
'string': 'VARCHAR(%(length)s)',
'text': 'CLOB',
'password': 'VARCHAR(%(length)s)', ## Not sure what this contains utf8 or nvarchar. Or even bytes?
'blob': 'BLOB',
'upload': 'VARCHAR(%(length)s)', ## FIXME utf8 or nvarchar... or blob? what is this type?
'integer': 'INTEGER4', # or int8...
'double': 'FLOAT8',
'decimal': 'NUMERIC(%(precision)s,%(scale)s)',
'date': 'ANSIDATE',
'time': 'TIME WITHOUT TIME ZONE',
'datetime': 'TIMESTAMP WITHOUT TIME ZONE',
'id': 'integer4 not null unique with default next value for %s' % INGRES_SEQNAME,
'reference': 'integer4, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', ## FIXME TODO
'list:integer': 'CLOB',
'list:string': 'CLOB',
'list:reference': 'CLOB',
}
def LEFT_JOIN(self):
return 'LEFT OUTER JOIN'
def RANDOM(self):
return 'RANDOM()'
def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby):
if limitby:
(lmin, lmax) = limitby
fetch_amt = lmax - lmin
if fetch_amt:
sql_s += ' FIRST %d ' % (fetch_amt, )
if lmin:
# Requires Ingres 9.2+
sql_o += ' OFFSET %d' % (lmin, )
return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o)
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "ingres"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
connstr = self._uri.split(':', 1)[1]
# Simple URI processing
connstr = connstr.lstrip()
while connstr.startswith('/'):
connstr = connstr[1:]
database_name=connstr # Assume only (local) dbname is passed in
vnode = '(local)'
servertype = 'ingres'
trace = (0, None) # No tracing
driver_args.update(dict(database=database_name,
vnode=vnode,
servertype=servertype,
trace=trace))
def connect(driver_args=driver_args):
return self.driver.connect(**driver_args)
self.pool_connection(connect)
def create_sequence_and_triggers(self, query, table, **args):
# post create table auto inc code (if needed)
# modify table to btree for performance....
# Older Ingres releases could use rule/trigger like Oracle above.
if hasattr(table,'_primarykey'):
modify_tbl_sql = 'modify %s to btree unique on %s' % \
(table._tablename,
', '.join(["'%s'" % x for x in table.primarykey]))
self.execute(modify_tbl_sql)
else:
tmp_seqname='%s_iisq' % table._tablename
query=query.replace(INGRES_SEQNAME, tmp_seqname)
self.execute('create sequence %s' % tmp_seqname)
self.execute(query)
self.execute('modify %s to btree unique on %s' % (table._tablename, 'id'))
def lastrowid(self,table):
tmp_seqname='%s_iisq' % table
self.execute('select current value for %s' % tmp_seqname)
return int(self.cursor.fetchone()[0]) # don't really need int type cast here...
def integrity_error_class(self):
return ingresdbi.IntegrityError
class IngresUnicodeAdapter(IngresAdapter):
types = {
'boolean': 'CHAR(1)',
'string': 'NVARCHAR(%(length)s)',
'text': 'NCLOB',
'password': 'NVARCHAR(%(length)s)', ## Not sure what this contains utf8 or nvarchar. Or even bytes?
'blob': 'BLOB',
'upload': 'VARCHAR(%(length)s)', ## FIXME utf8 or nvarchar... or blob? what is this type?
'integer': 'INTEGER4', # or int8...
'double': 'FLOAT8',
'decimal': 'NUMERIC(%(precision)s,%(scale)s)',
'date': 'ANSIDATE',
'time': 'TIME WITHOUT TIME ZONE',
'datetime': 'TIMESTAMP WITHOUT TIME ZONE',
'id': 'integer4 not null unique with default next value for %s'% INGRES_SEQNAME,
'reference': 'integer4, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', ## FIXME TODO
'list:integer': 'NCLOB',
'list:string': 'NCLOB',
'list:reference': 'NCLOB',
}
class SAPDBAdapter(BaseAdapter):
driver = globals().get('sapdb',None)
support_distributed_transaction = False
types = {
'boolean': 'CHAR(1)',
'string': 'VARCHAR(%(length)s)',
'text': 'LONG',
'password': 'VARCHAR(%(length)s)',
'blob': 'LONG',
'upload': 'VARCHAR(%(length)s)',
'integer': 'INT',
'double': 'FLOAT',
'decimal': 'FIXED(%(precision)s,%(scale)s)',
'date': 'DATE',
'time': 'TIME',
'datetime': 'TIMESTAMP',
'id': 'INT PRIMARY KEY',
'reference': 'INT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
'list:integer': 'LONG',
'list:string': 'LONG',
'list:reference': 'LONG',
}
def sequence_name(self,table):
return '%s_id_Seq' % table
def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby):
if limitby:
(lmin, lmax) = limitby
if len(sql_w) > 1:
sql_w_row = sql_w + ' AND w_row > %i' % lmin
else:
sql_w_row = 'WHERE w_row > %i' % lmin
return '%s %s FROM (SELECT w_tmp.*, ROWNO w_row FROM (SELECT %s FROM %s%s%s) w_tmp WHERE ROWNO=%i) %s %s %s;' % (sql_s, sql_f, sql_f, sql_t, sql_w, sql_o, lmax, sql_t, sql_w_row, sql_o)
return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o)
def create_sequence_and_triggers(self, query, table, **args):
# following lines should only be executed if table._sequence_name does not exist
self.execute('CREATE SEQUENCE %s;' % table._sequence_name)
self.execute("ALTER TABLE %s ALTER COLUMN %s SET DEFAULT NEXTVAL('%s');" \
% (table._tablename, table._id.name, table._sequence_name))
self.execute(query)
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "sapdb"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
uri = uri.split('://')[1]
m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:@/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^\?]+)(\?sslmode=(?P<sslmode>.+))?$').match(uri)
if not m:
raise SyntaxError, "Invalid URI string in DAL"
user = credential_decoder(m.group('user'))
if not user:
raise SyntaxError, 'User required'
password = credential_decoder(m.group('password'))
if not password:
password = ''
host = m.group('host')
if not host:
raise SyntaxError, 'Host name required'
db = m.group('db')
if not db:
raise SyntaxError, 'Database name required'
def connect(user=user, password=password, database=db,
host=host, driver_args=driver_args):
return self.driver.Connection(user, password, database,
host, **driver_args)
self.pool_connection(connect)
def lastrowid(self,table):
self.execute("select %s.NEXTVAL from dual" % table._sequence_name)
return int(self.cursor.fetchone()[0])
class CubridAdapter(MySQLAdapter):
driver = globals().get('cubriddb', None)
def __init__(self, db, uri, pool_size=0, folder=None, db_codec='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
if not self.driver:
raise RuntimeError, "Unable to import driver"
self.db = db
self.dbengine = "cubrid"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.find_or_make_work_folder()
uri = uri.split('://')[1]
m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^?]+)(\?set_encoding=(?P<charset>\w+))?$').match(uri)
if not m:
raise SyntaxError, \
"Invalid URI string in DAL: %s" % self.uri
user = credential_decoder(m.group('user'))
if not user:
raise SyntaxError, 'User required'
password = credential_decoder(m.group('password'))
if not password:
password = ''
host = m.group('host')
if not host:
raise SyntaxError, 'Host name required'
db = m.group('db')
if not db:
raise SyntaxError, 'Database name required'
port = int(m.group('port') or '30000')
charset = m.group('charset') or 'utf8'
user = credential_decoder(user)
passwd = credential_decoder(password)
def connect(host=host,port=port,db=db,
user=user,passwd=password,driver_args=driver_args):
return self.driver.connect(host,port,db,user,passwd,**driver_args)
self.pool_connection(connect)
self.execute('SET FOREIGN_KEY_CHECKS=1;')
self.execute("SET sql_mode='NO_BACKSLASH_ESCAPES';")
######## GAE MySQL ##########
class DatabaseStoredFile:
web2py_filesystem = False
def escape(self,obj):
return self.db._adapter.escape(obj)
def __init__(self,db,filename,mode):
if db._adapter.dbengine != 'mysql':
raise RuntimeError, "only MySQL can store metadata .table files in database for now"
self.db = db
self.filename = filename
self.mode = mode
if not self.web2py_filesystem:
self.db.executesql("CREATE TABLE IF NOT EXISTS web2py_filesystem (path VARCHAR(512), content LONGTEXT, PRIMARY KEY(path) ) ENGINE=InnoDB;")
DatabaseStoredFile.web2py_filesystem = True
self.p=0
self.data = ''
if mode in ('r','rw','a'):
query = "SELECT content FROM web2py_filesystem WHERE path='%s'" \
% filename
rows = self.db.executesql(query)
if rows:
self.data = rows[0][0]
elif os.path.exists(filename):
datafile = open(filename, 'r')
try:
self.data = datafile.read()
finally:
datafile.close()
elif mode in ('r','rw'):
raise RuntimeError, "File %s does not exist" % filename
def read(self, bytes):
data = self.data[self.p:self.p+bytes]
self.p += len(data)
return data
def readline(self):
i = self.data.find('\n',self.p)+1
if i>0:
data, self.p = self.data[self.p:i], i
else:
data, self.p = self.data[self.p:], len(self.data)
return data
def write(self,data):
self.data += data
def close(self):
self.db.executesql("DELETE FROM web2py_filesystem WHERE path='%s'" \
% self.filename)
query = "INSERT INTO web2py_filesystem(path,content) VALUES ('%s','%s')"\
% (self.filename, self.data.replace("'","''"))
self.db.executesql(query)
self.db.commit()
@staticmethod
def exists(db, filename):
if os.path.exists(filename):
return True
query = "SELECT path FROM web2py_filesystem WHERE path='%s'" % filename
if db.executesql(query):
return True
return False
class UseDatabaseStoredFile:
def file_exists(self, filename):
return DatabaseStoredFile.exists(self.db,filename)
def file_open(self, filename, mode='rb', lock=True):
return DatabaseStoredFile(self.db,filename,mode)
def file_close(self, fileobj):
fileobj.close()
def file_delete(self,filename):
query = "DELETE FROM web2py_filesystem WHERE path='%s'" % filename
self.db.executesql(query)
self.db.commit()
class GoogleSQLAdapter(UseDatabaseStoredFile,MySQLAdapter):
def __init__(self, db, uri='google:sql://realm:domain/database',
pool_size=0, folder=None, db_codec='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
self.db = db
self.dbengine = "mysql"
self.uri = uri
self.pool_size = pool_size
self.folder = folder
self.db_codec = db_codec
self.folder = folder or '$HOME/'+thread.folder.split('/applications/',1)[1]
m = re.compile('^(?P<instance>.*)/(?P<db>.*)$').match(self.uri[len('google:sql://'):])
if not m:
raise SyntaxError, "Invalid URI string in SQLDB: %s" % self._uri
instance = credential_decoder(m.group('instance'))
db = credential_decoder(m.group('db'))
driver_args['instance'] = instance
createdb = adapter_args.get('createdb',True)
if not createdb:
driver_args['database'] = db
def connect(driver_args=driver_args):
return rdbms.connect(**driver_args)
self.pool_connection(connect)
if createdb:
# self.execute('DROP DATABASE %s' % db)
self.execute('CREATE DATABASE IF NOT EXISTS %s' % db)
self.execute('USE %s' % db)
self.execute("SET FOREIGN_KEY_CHECKS=1;")
self.execute("SET sql_mode='NO_BACKSLASH_ESCAPES';")
class NoSQLAdapter(BaseAdapter):
can_select_for_update = False
@staticmethod
def to_unicode(obj):
if isinstance(obj, str):
return obj.decode('utf8')
elif not isinstance(obj, unicode):
return unicode(obj)
return obj
def represent(self, obj, fieldtype):
if isinstance(obj, CALLABLETYPES):
obj = obj()
if isinstance(fieldtype, SQLCustomType):
return fieldtype.encoder(obj)
if isinstance(obj, (Expression, Field)):
raise SyntaxError, "non supported on GAE"
if self.dbengine == 'google:datastore':
if isinstance(fieldtype, gae.Property):
return obj
is_string = isinstance(fieldtype,str)
is_list = is_string and fieldtype.startswith('list:')
if is_list:
if not obj:
obj = []
if not isinstance(obj, (list, tuple)):
obj = [obj]
if obj == '' and not \
(is_string and fieldtype[:2] in ['st','te','pa','up']):
return None
if not obj is None:
if isinstance(obj, list) and not is_list:
obj = [self.represent(o, fieldtype) for o in obj]
elif fieldtype in ('integer','id'):
obj = long(obj)
elif fieldtype == 'double':
obj = float(obj)
elif is_string and fieldtype.startswith('reference'):
if isinstance(obj, (Row, Reference)):
obj = obj['id']
obj = long(obj)
elif fieldtype == 'boolean':
if obj and not str(obj)[0].upper() == 'F':
obj = True
else:
obj = False
elif fieldtype == 'date':
if not isinstance(obj, datetime.date):
(y, m, d) = map(int,str(obj).strip().split('-'))
obj = datetime.date(y, m, d)
elif isinstance(obj,datetime.datetime):
(y, m, d) = (obj.year, obj.month, obj.day)
obj = datetime.date(y, m, d)
elif fieldtype == 'time':
if not isinstance(obj, datetime.time):
time_items = map(int,str(obj).strip().split(':')[:3])
if len(time_items) == 3:
(h, mi, s) = time_items
else:
(h, mi, s) = time_items + [0]
obj = datetime.time(h, mi, s)
elif fieldtype == 'datetime':
if not isinstance(obj, datetime.datetime):
(y, m, d) = map(int,str(obj)[:10].strip().split('-'))
time_items = map(int,str(obj)[11:].strip().split(':')[:3])
while len(time_items)<3:
time_items.append(0)
(h, mi, s) = time_items
obj = datetime.datetime(y, m, d, h, mi, s)
elif fieldtype == 'blob':
pass
elif is_string and fieldtype.startswith('list:string'):
return map(self.to_unicode,obj)
elif is_list:
return map(int,obj)
else:
obj = self.to_unicode(obj)
return obj
def _insert(self,table,fields):
return 'insert %s in %s' % (fields, table)
def _count(self,query,distinct=None):
return 'count %s' % repr(query)
def _select(self,query,fields,attributes):
return 'select %s where %s' % (repr(fields), repr(query))
def _delete(self,tablename, query):
return 'delete %s where %s' % (repr(tablename),repr(query))
def _update(self,tablename,query,fields):
return 'update %s (%s) where %s' % (repr(tablename),
repr(fields),repr(query))
def commit(self):
"""
remember: no transactions on many NoSQL
"""
pass
def rollback(self):
"""
remember: no transactions on many NoSQL
"""
pass
def close(self):
"""
remember: no transactions on many NoSQL
"""
pass
# these functions should never be called!
def OR(self,first,second): raise SyntaxError, "Not supported"
def AND(self,first,second): raise SyntaxError, "Not supported"
def AS(self,first,second): raise SyntaxError, "Not supported"
def ON(self,first,second): raise SyntaxError, "Not supported"
def STARTSWITH(self,first,second=None): raise SyntaxError, "Not supported"
def ENDSWITH(self,first,second=None): raise SyntaxError, "Not supported"
def ADD(self,first,second): raise SyntaxError, "Not supported"
def SUB(self,first,second): raise SyntaxError, "Not supported"
def MUL(self,first,second): raise SyntaxError, "Not supported"
def DIV(self,first,second): raise SyntaxError, "Not supported"
def LOWER(self,first): raise SyntaxError, "Not supported"
def UPPER(self,first): raise SyntaxError, "Not supported"
def EXTRACT(self,first,what): raise SyntaxError, "Not supported"
def AGGREGATE(self,first,what): raise SyntaxError, "Not supported"
def LEFT_JOIN(self): raise SyntaxError, "Not supported"
def RANDOM(self): raise SyntaxError, "Not supported"
def SUBSTRING(self,field,parameters): raise SyntaxError, "Not supported"
def PRIMARY_KEY(self,key): raise SyntaxError, "Not supported"
def ILIKE(self,first,second): raise SyntaxError, "Not supported"
def drop(self,table,mode): raise SyntaxError, "Not supported"
def alias(self,table,alias): raise SyntaxError, "Not supported"
def migrate_table(self,*a,**b): raise SyntaxError, "Not supported"
def distributed_transaction_begin(self,key): raise SyntaxError, "Not supported"
def prepare(self,key): raise SyntaxError, "Not supported"
def commit_prepared(self,key): raise SyntaxError, "Not supported"
def rollback_prepared(self,key): raise SyntaxError, "Not supported"
def concat_add(self,table): raise SyntaxError, "Not supported"
def constraint_name(self, table, fieldname): raise SyntaxError, "Not supported"
def create_sequence_and_triggers(self, query, table, **args): pass
def log_execute(self,*a,**b): raise SyntaxError, "Not supported"
def execute(self,*a,**b): raise SyntaxError, "Not supported"
def represent_exceptions(self, obj, fieldtype): raise SyntaxError, "Not supported"
def lastrowid(self,table): raise SyntaxError, "Not supported"
def integrity_error_class(self): raise SyntaxError, "Not supported"
def rowslice(self,rows,minimum=0,maximum=None): raise SyntaxError, "Not supported"
class GAEF(object):
def __init__(self,name,op,value,apply):
self.name=name=='id' and '__key__' or name
self.op=op
self.value=value
self.apply=apply
def __repr__(self):
return '(%s %s %s:%s)' % (self.name, self.op, repr(self.value), type(self.value))
class GoogleDatastoreAdapter(NoSQLAdapter):
uploads_in_blob = True
types = {}
def file_exists(self, filename): pass
def file_open(self, filename, mode='rb', lock=True): pass
def file_close(self, fileobj): pass
def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
self.types.update({
'boolean': gae.BooleanProperty,
'string': (lambda: gae.StringProperty(multiline=True)),
'text': gae.TextProperty,
'password': gae.StringProperty,
'blob': gae.BlobProperty,
'upload': gae.StringProperty,
'integer': gae.IntegerProperty,
'double': gae.FloatProperty,
'decimal': GAEDecimalProperty,
'date': gae.DateProperty,
'time': gae.TimeProperty,
'datetime': gae.DateTimeProperty,
'id': None,
'reference': gae.IntegerProperty,
'list:string': (lambda: gae.StringListProperty(default=None)),
'list:integer': (lambda: gae.ListProperty(int,default=None)),
'list:reference': (lambda: gae.ListProperty(int,default=None)),
})
self.db = db
self.uri = uri
self.dbengine = 'google:datastore'
self.folder = folder
db['_lastsql'] = ''
self.db_codec = 'UTF-8'
self.pool_size = 0
match = re.compile('.*://(?P<namespace>.+)').match(uri)
if match:
namespace_manager.set_namespace(match.group('namespace'))
def create_table(self,table,migrate=True,fake_migrate=False, polymodel=None):
myfields = {}
for k in table.fields:
if isinstance(polymodel,Table) and k in polymodel.fields():
continue
field = table[k]
attr = {}
if isinstance(field.type, SQLCustomType):
ftype = self.types[field.type.native or field.type.type](**attr)
elif isinstance(field.type, gae.Property):
ftype = field.type
elif field.type.startswith('id'):
continue
elif field.type.startswith('decimal'):
precision, scale = field.type[7:].strip('()').split(',')
precision = int(precision)
scale = int(scale)
ftype = GAEDecimalProperty(precision, scale, **attr)
elif field.type.startswith('reference'):
if field.notnull:
attr = dict(required=True)
referenced = field.type[10:].strip()
ftype = self.types[field.type[:9]](referenced)
elif field.type.startswith('list:reference'):
if field.notnull:
attr = dict(required=True)
referenced = field.type[15:].strip()
ftype = self.types[field.type[:14]](**attr)
elif field.type.startswith('list:'):
ftype = self.types[field.type](**attr)
elif not field.type in self.types\
or not self.types[field.type]:
raise SyntaxError, 'Field: unknown field type: %s' % field.type
else:
ftype = self.types[field.type](**attr)
myfields[field.name] = ftype
if not polymodel:
table._tableobj = classobj(table._tablename, (gae.Model, ), myfields)
elif polymodel==True:
table._tableobj = classobj(table._tablename, (PolyModel, ), myfields)
elif isinstance(polymodel,Table):
table._tableobj = classobj(table._tablename, (polymodel._tableobj, ), myfields)
else:
raise SyntaxError, "polymodel must be None, True, a table or a tablename"
return None
def expand(self,expression,field_type=None):
if isinstance(expression,Field):
if expression.type in ('text','blob'):
raise SyntaxError, 'AppEngine does not index by: %s' % expression.type
return expression.name
elif isinstance(expression, (Expression, Query)):
if not expression.second is None:
return expression.op(expression.first, expression.second)
elif not expression.first is None:
return expression.op(expression.first)
else:
return expression.op()
elif field_type:
return self.represent(expression,field_type)
elif isinstance(expression,(list,tuple)):
return ','.join([self.represent(item,field_type) for item in expression])
else:
return str(expression)
### TODO from gql.py Expression
def AND(self,first,second):
a = self.expand(first)
b = self.expand(second)
if b[0].name=='__key__' and a[0].name!='__key__':
return b+a
return a+b
def EQ(self,first,second=None):
if isinstance(second, Key):
return [GAEF(first.name,'=',second,lambda a,b:a==b)]
return [GAEF(first.name,'=',self.represent(second,first.type),lambda a,b:a==b)]
def NE(self,first,second=None):
if first.type != 'id':
return [GAEF(first.name,'!=',self.represent(second,first.type),lambda a,b:a!=b)]
else:
second = Key.from_path(first._tablename, long(second))
return [GAEF(first.name,'!=',second,lambda a,b:a!=b)]
def LT(self,first,second=None):
if first.type != 'id':
return [GAEF(first.name,'<',self.represent(second,first.type),lambda a,b:a<b)]
else:
second = Key.from_path(first._tablename, long(second))
return [GAEF(first.name,'<',second,lambda a,b:a<b)]
def LE(self,first,second=None):
if first.type != 'id':
return [GAEF(first.name,'<=',self.represent(second,first.type),lambda a,b:a<=b)]
else:
second = Key.from_path(first._tablename, long(second))
return [GAEF(first.name,'<=',second,lambda a,b:a<=b)]
def GT(self,first,second=None):
if first.type != 'id' or second==0 or second == '0':
return [GAEF(first.name,'>',self.represent(second,first.type),lambda a,b:a>b)]
else:
second = Key.from_path(first._tablename, long(second))
return [GAEF(first.name,'>',second,lambda a,b:a>b)]
def GE(self,first,second=None):
if first.type != 'id':
return [GAEF(first.name,'>=',self.represent(second,first.type),lambda a,b:a>=b)]
else:
second = Key.from_path(first._tablename, long(second))
return [GAEF(first.name,'>=',second,lambda a,b:a>=b)]
def INVERT(self,first):
return '-%s' % first.name
def COMMA(self,first,second):
return '%s, %s' % (self.expand(first),self.expand(second))
def BELONGS(self,first,second=None):
if not isinstance(second,(list, tuple)):
raise SyntaxError, "Not supported"
if first.type != 'id':
return [GAEF(first.name,'in',self.represent(second,first.type),lambda a,b:a in b)]
else:
second = [Key.from_path(first._tablename, i) for i in second]
return [GAEF(first.name,'in',second,lambda a,b:a in b)]
def CONTAINS(self,first,second):
if not first.type.startswith('list:'):
raise SyntaxError, "Not supported"
return [GAEF(first.name,'=',self.expand(second,first.type[5:]),lambda a,b:a in b)]
def NOT(self,first):
nops = { self.EQ: self.NE,
self.NE: self.EQ,
self.LT: self.GE,
self.GT: self.LE,
self.LE: self.GT,
self.GE: self.LT}
if not isinstance(first,Query):
raise SyntaxError, "Not suported"
nop = nops.get(first.op,None)
if not nop:
raise SyntaxError, "Not suported %s" % first.op.__name__
first.op = nop
return self.expand(first)
def truncate(self,table,mode):
self.db(table._id > 0).delete()
def select_raw(self,query,fields=None,attributes=None):
fields = fields or []
attributes = attributes or {}
new_fields = []
for item in fields:
if isinstance(item,SQLALL):
new_fields += item.table
else:
new_fields.append(item)
fields = new_fields
if query:
tablename = self.get_table(query)
elif fields:
tablename = fields[0].tablename
query = fields[0].table._id>0
else:
raise SyntaxError, "Unable to determine a tablename"
if query:
if use_common_filters(query):
query = self.common_filter(query,[tablename])
tableobj = self.db[tablename]._tableobj
items = tableobj.all()
filters = self.expand(query)
for filter in filters:
if filter.name=='__key__' and filter.op=='>' and filter.value==0:
continue
elif filter.name=='__key__' and filter.op=='=':
if filter.value==0:
items = []
elif isinstance(filter.value, Key):
item = tableobj.get(filter.value)
items = (item and [item]) or []
else:
item = tableobj.get_by_id(filter.value)
items = (item and [item]) or []
elif isinstance(items,list): # i.e. there is a single record!
items = [i for i in items if filter.apply(getattr(item,filter.name),
filter.value)]
else:
if filter.name=='__key__': items.order('__key__')
items = items.filter('%s %s' % (filter.name,filter.op),filter.value)
if not isinstance(items,list):
if attributes.get('left', None):
raise SyntaxError, 'Set: no left join in appengine'
if attributes.get('groupby', None):
raise SyntaxError, 'Set: no groupby in appengine'
orderby = attributes.get('orderby', False)
if orderby:
### THIS REALLY NEEDS IMPROVEMENT !!!
if isinstance(orderby, (list, tuple)):
orderby = xorify(orderby)
if isinstance(orderby,Expression):
orderby = self.expand(orderby)
orders = orderby.split(', ')
for order in orders:
order={'-id':'-__key__','id':'__key__'}.get(order,order)
items = items.order(order)
if attributes.get('limitby', None):
(lmin, lmax) = attributes['limitby']
(limit, offset) = (lmax - lmin, lmin)
items = items.fetch(limit, offset=offset)
fields = self.db[tablename].fields
return (items, tablename, fields)
def select(self,query,fields,attributes):
(items, tablename, fields) = self.select_raw(query,fields,attributes)
# self.db['_lastsql'] = self._select(query,fields,attributes)
rows = [
[t=='id' and (int(item.key().id()) if item.key().id() else
item.key().name()) or getattr(item, t) for t in fields]
for item in items]
colnames = ['%s.%s' % (tablename, t) for t in fields]
return self.parse(rows, fields, colnames, False)
def count(self,query,distinct=None):
if distinct:
raise RuntimeError, "COUNT DISTINCT not supported"
(items, tablename, fields) = self.select_raw(query)
# self.db['_lastsql'] = self._count(query)
try:
return len(items)
except TypeError:
return items.count(limit=None)
def delete(self,tablename, query):
"""
This function was changed on 2010-05-04 because according to
http://code.google.com/p/googleappengine/issues/detail?id=3119
GAE no longer support deleting more than 1000 records.
"""
# self.db['_lastsql'] = self._delete(tablename,query)
(items, tablename, fields) = self.select_raw(query)
# items can be one item or a query
if not isinstance(items,list):
counter = items.count(limit=None)
leftitems = items.fetch(1000)
while len(leftitems):
gae.delete(leftitems)
leftitems = items.fetch(1000)
else:
counter = len(items)
gae.delete(items)
return counter
def update(self,tablename,query,update_fields):
# self.db['_lastsql'] = self._update(tablename,query,update_fields)
(items, tablename, fields) = self.select_raw(query)
counter = 0
for item in items:
for field, value in update_fields:
setattr(item, field.name, self.represent(value,field.type))
item.put()
counter += 1
logger.info(str(counter))
return counter
def insert(self,table,fields):
dfields=dict((f.name,self.represent(v,f.type)) for f,v in fields)
# table._db['_lastsql'] = self._insert(table,fields)
tmp = table._tableobj(**dfields)
tmp.put()
rid = Reference(tmp.key().id())
(rid._table, rid._record) = (table, None)
return rid
def bulk_insert(self,table,items):
parsed_items = []
for item in items:
dfields=dict((f.name,self.represent(v,f.type)) for f,v in item)
parsed_items.append(table._tableobj(**dfields))
gae.put(parsed_items)
return True
def uuid2int(uuidv):
return uuid.UUID(uuidv).int
def int2uuid(n):
return str(uuid.UUID(int=n))
class CouchDBAdapter(NoSQLAdapter):
uploads_in_blob = True
types = {
'boolean': bool,
'string': str,
'text': str,
'password': str,
'blob': str,
'upload': str,
'integer': long,
'double': float,
'date': datetime.date,
'time': datetime.time,
'datetime': datetime.datetime,
'id': long,
'reference': long,
'list:string': list,
'list:integer': list,
'list:reference': list,
}
def file_exists(self, filename): pass
def file_open(self, filename, mode='rb', lock=True): pass
def file_close(self, fileobj): pass
def expand(self,expression,field_type=None):
if isinstance(expression,Field):
if expression.type=='id':
return "%s._id" % expression.tablename
return BaseAdapter.expand(self,expression,field_type)
def AND(self,first,second):
return '(%s && %s)' % (self.expand(first),self.expand(second))
def OR(self,first,second):
return '(%s || %s)' % (self.expand(first),self.expand(second))
def EQ(self,first,second):
if second is None:
return '(%s == null)' % self.expand(first)
return '(%s == %s)' % (self.expand(first),self.expand(second,first.type))
def NE(self,first,second):
if second is None:
return '(%s != null)' % self.expand(first)
return '(%s != %s)' % (self.expand(first),self.expand(second,first.type))
def COMMA(self,first,second):
return '%s + %s' % (self.expand(first),self.expand(second))
def represent(self, obj, fieldtype):
value = NoSQLAdapter.represent(self, obj, fieldtype)
if fieldtype=='id':
return repr(str(int(value)))
elif fieldtype in ('date','time','datetime','boolean'):
return serializers.json(value)
return repr(not isinstance(value,unicode) and value or value.encode('utf8'))
def __init__(self,db,uri='couchdb://127.0.0.1:5984',
pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
self.db = db
self.uri = uri
self.dbengine = 'couchdb'
self.folder = folder
db['_lastsql'] = ''
self.db_codec = 'UTF-8'
self.pool_size = pool_size
url='http://'+uri[10:]
def connect(url=url,driver_args=driver_args):
return couchdb.Server(url,**driver_args)
self.pool_connection(connect,cursor=False)
def create_table(self, table, migrate=True, fake_migrate=False, polymodel=None):
if migrate:
try:
self.connection.create(table._tablename)
except:
pass
def insert(self,table,fields):
id = uuid2int(web2py_uuid())
ctable = self.connection[table._tablename]
values = dict((k.name,self.represent(v,k.type)) for k,v in fields)
values['_id'] = str(id)
ctable.save(values)
return id
def _select(self,query,fields,attributes):
if not isinstance(query,Query):
raise SyntaxError, "Not Supported"
for key in set(attributes.keys())-set(('orderby','groupby','limitby',
'required','cache','left',
'distinct','having')):
raise SyntaxError, 'invalid select attribute: %s' % key
new_fields=[]
for item in fields:
if isinstance(item,SQLALL):
new_fields += item.table
else:
new_fields.append(item)
def uid(fd):
return fd=='id' and '_id' or fd
def get(row,fd):
return fd=='id' and int(row['_id']) or row.get(fd,None)
fields = new_fields
tablename = self.get_table(query)
fieldnames = [f.name for f in (fields or self.db[tablename])]
colnames = ['%s.%s' % (tablename,k) for k in fieldnames]
fields = ','.join(['%s.%s' % (tablename,uid(f)) for f in fieldnames])
fn="function(%(t)s){if(%(query)s)emit(%(order)s,[%(fields)s]);}" %\
dict(t=tablename,
query=self.expand(query),
order='%s._id' % tablename,
fields=fields)
return fn, colnames
def select(self,query,fields,attributes):
if not isinstance(query,Query):
raise SyntaxError, "Not Supported"
fn, colnames = self._select(query,fields,attributes)
tablename = colnames[0].split('.')[0]
ctable = self.connection[tablename]
rows = [cols['value'] for cols in ctable.query(fn)]
return self.parse(rows, fields, colnames, False)
def delete(self,tablename,query):
if not isinstance(query,Query):
raise SyntaxError, "Not Supported"
if query.first.type=='id' and query.op==self.EQ:
id = query.second
tablename = query.first.tablename
assert(tablename == query.first.tablename)
ctable = self.connection[tablename]
try:
del ctable[str(id)]
return 1
except couchdb.http.ResourceNotFound:
return 0
else:
tablename = self.get_table(query)
rows = self.select(query,[self.db[tablename]._id],{})
ctable = self.connection[tablename]
for row in rows:
del ctable[str(row.id)]
return len(rows)
def update(self,tablename,query,fields):
if not isinstance(query,Query):
raise SyntaxError, "Not Supported"
if query.first.type=='id' and query.op==self.EQ:
id = query.second
tablename = query.first.tablename
ctable = self.connection[tablename]
try:
doc = ctable[str(id)]
for key,value in fields:
doc[key.name] = self.represent(value,self.db[tablename][key.name].type)
ctable.save(doc)
return 1
except couchdb.http.ResourceNotFound:
return 0
else:
tablename = self.get_table(query)
rows = self.select(query,[self.db[tablename]._id],{})
ctable = self.connection[tablename]
table = self.db[tablename]
for row in rows:
doc = ctable[str(row.id)]
for key,value in fields:
doc[key.name] = self.represent(value,table[key.name].type)
ctable.save(doc)
return len(rows)
def count(self,query,distinct=None):
if distinct:
raise RuntimeError, "COUNT DISTINCT not supported"
if not isinstance(query,Query):
raise SyntaxError, "Not Supported"
tablename = self.get_table(query)
rows = self.select(query,[self.db[tablename]._id],{})
return len(rows)
def cleanup(text):
"""
validates that the given text is clean: only contains [0-9a-zA-Z_]
"""
if re.compile('[^0-9a-zA-Z_]').findall(text):
raise SyntaxError, \
'only [0-9a-zA-Z_] allowed in table and field names, received %s' \
% text
return text
class MongoDBAdapter(NoSQLAdapter):
uploads_in_blob = True
types = {
'boolean': bool,
'string': str,
'text': str,
'password': str,
'blob': str,
'upload': str,
'integer': long,
'double': float,
'date': datetime.date,
'time': datetime.time,
'datetime': datetime.datetime,
'id': long,
'reference': long,
'list:string': list,
'list:integer': list,
'list:reference': list,
}
def __init__(self,db,uri='mongodb://127.0.0.1:5984/db',
pool_size=0,folder=None,db_codec ='UTF-8',
credential_decoder=lambda x:x, driver_args={},
adapter_args={}):
m=None
try:
#Since version 2
import pymongo.uri_parser
m = pymongo.uri_parser.parse_uri(uri)
except ImportError:
try:
#before version 2 of pymongo
import pymongo.connection
m = pymongo.connection._parse_uri(uri)
except ImportError:
raise ImportError("Uriparser for mongodb is not available")
except:
raise SyntaxError("This type of uri is not supported by the mongodb uri parser")
self.db = db
self.uri = uri
self.dbengine = 'mongodb'
self.folder = folder
db['_lastsql'] = ''
self.db_codec = 'UTF-8'
self.pool_size = pool_size
#this is the minimum amount of replicates that it should wait for on insert/update
self.minimumreplication = adapter_args.get('minimumreplication',0)
#by default alle insert and selects are performand asynchronous, but now the default is
#synchronous, except when overruled by either this default or function parameter
self.safe = adapter_args.get('safe',True)
if isinstance(m,tuple):
m = {"database" : m[1]}
if m.get('database')==None:
raise SyntaxError("Database is required!")
def connect(uri=self.uri,m=m):
try:
return pymongo.Connection(uri)[m.get('database')]
except pymongo.errors.ConnectionFailure, inst:
raise SyntaxError, "The connection to " + uri + " could not be made"
except Exception, inst:
if inst == "cannot specify database without a username and password":
raise SyntaxError("You are probebly running version 1.1 of pymongo which contains a bug which requires authentication. Update your pymongo.")
else:
raise SyntaxError("This is not an official Mongodb uri (http://www.mongodb.org/display/DOCS/Connections) Error : %s" % inst)
self.pool_connection(connect,cursor=False)
def represent(self, obj, fieldtype):
value = NoSQLAdapter.represent(self, obj, fieldtype)
if fieldtype =='date':
if value == None:
return value
t = datetime.time(0, 0, 0)#this piece of data can be stripped of based on the fieldtype
return datetime.datetime.combine(value, t) #mongodb doesn't has a date object and so it must datetime, string or integer
elif fieldtype == 'time':
if value == None:
return value
d = datetime.date(2000, 1, 1) #this piece of data can be stripped of based on the fieldtype
return datetime.datetime.combine(d, value) #mongodb doesn't has a time object and so it must datetime, string or integer
elif fieldtype == 'list:string' or fieldtype == 'list:integer' or fieldtype == 'list:reference':
return value #raise SyntaxError, "Not Supported"
return value
#Safe determines whether a asynchronious request is done or a synchronious action is done
#For safety, we use by default synchronious requests
def insert(self,table,fields,safe=None):
if safe==None:
safe=self.safe
ctable = self.connection[table._tablename]
values = dict((k.name,self.represent(v,table[k.name].type)) for k,v in fields)
ctable.insert(values,safe=safe)
return int(str(values['_id']), 16)
def create_table(self, table, migrate=True, fake_migrate=False, polymodel=None, isCapped=False):
if isCapped:
raise RuntimeError, "Not implemented"
else:
pass
def count(self,query,distinct=None,snapshot=True):
if distinct:
raise RuntimeError, "COUNT DISTINCT not supported"
if not isinstance(query,Query):
raise SyntaxError, "Not Supported"
tablename = self.get_table(query)
return int(self.select(query,[self.db[tablename]._id],{},count=True,snapshot=snapshot)['count'])
#Maybe it would be faster if we just implemented the pymongo .count() function which is probably quicker?
# therefor call __select() connection[table].find(query).count() Since this will probably reduce the return set?
def expand(self, expression, field_type=None):
import pymongo.objectid
#if isinstance(expression,Field):
# if expression.type=='id':
# return {_id}"
if isinstance(expression, Query):
print "in expand and this is a query"
# any query using 'id':=
# set name as _id (as per pymongo/mongodb primary key)
# convert second arg to an objectid field (if its not already)
# if second arg is 0 convert to objectid
if isinstance(expression.first,Field) and expression.first.type == 'id':
expression.first.name = '_id'
if expression.second != 0 and not isinstance(expression.second,pymongo.objectid.ObjectId):
if isinstance(expression.second,int):
try:
#Cause the reference field is by default an integer and therefor this must be an integer to be able to work with other databases
expression.second = pymongo.objectid.ObjectId(("%X" % expression.second))
except:
raise SyntaxError, 'The second argument must by an integer that can represent an objectid.'
else:
try:
#But a direct id is also possible
expression.second = pymongo.objectid.ObjectId(expression.second)
except:
raise SyntaxError, 'second argument must be of type bson.objectid.ObjectId or an objectid representable integer'
elif expression.second == 0:
expression.second = pymongo.objectid.ObjectId('000000000000000000000000')
return expression.op(expression.first, expression.second)
if isinstance(expression, Field):
if expression.type=='id':
return "_id"
else:
return expression.name
#return expression
elif isinstance(expression, (Expression, Query)):
if not expression.second is None:
return expression.op(expression.first, expression.second)
elif not expression.first is None:
return expression.op(expression.first)
elif not isinstance(expression.op, str):
return expression.op()
else:
return expression.op
elif field_type:
return str(self.represent(expression,field_type))
elif isinstance(expression,(list,tuple)):
return ','.join(self.represent(item,field_type) for item in expression)
else:
return expression
def _select(self,query,fields,attributes):
from pymongo import son
for key in set(attributes.keys())-set(('limitby','orderby')):
raise SyntaxError, 'invalid select attribute: %s' % key
new_fields=[]
mongosort_list = []
# try an orderby attribute
orderby = attributes.get('orderby', False)
limitby = attributes.get('limitby', False)
#distinct = attributes.get('distinct', False)
if orderby:
#print "in if orderby %s" % orderby
if isinstance(orderby, (list, tuple)):
print "in xorify"
orderby = xorify(orderby)
# !!!! need to add 'random'
for f in self.expand(orderby).split(','):
if f.startswith('-'):
mongosort_list.append((f[1:],-1))
else:
mongosort_list.append((f,1))
print "mongosort_list = %s" % mongosort_list
if limitby:
# a tuple
limitby_skip,limitby_limit = limitby
else:
limitby_skip = 0
limitby_limit = 0
#if distinct:
#print "in distinct %s" % distinct
mongofields_dict = son.SON()
mongoqry_dict = {}
for item in fields:
if isinstance(item,SQLALL):
new_fields += item.table
else:
new_fields.append(item)
fields = new_fields
if isinstance(query,Query):
tablename = self.get_table(query)
elif len(fields) != 0:
tablename = fields[0].tablename
else:
raise SyntaxError, "The table name could not be found in the query nor from the select statement."
fieldnames = [f for f in (fields or self.db[tablename])] # ie table.field
mongoqry_dict = self.expand(query)
for f in fieldnames:
mongofields_dict[f.name] = 1 # ie field=1
return tablename, mongoqry_dict, mongofields_dict, mongosort_list, limitby_limit, limitby_skip
# need to define all the 'sql' methods gt,lt etc....
def select(self,query,fields,attributes,count=False,snapshot=False):
withId=False
tablename, mongoqry_dict , mongofields_dict, mongosort_list, limitby_limit, limitby_skip = self._select(query,fields,attributes)
for key in mongofields_dict.keys():
if key == 'id':
withId = True
break;
try:
print "mongoqry_dict=%s" % mongoqry_dict
except:
pass
print "mongofields_dict=%s" % mongofields_dict
ctable = self.connection[tablename]
if count:
return {'count' : ctable.find(mongoqry_dict,mongofields_dict,skip=limitby_skip, limit=limitby_limit, sort=mongosort_list,snapshot=snapshot).count()}
else:
mongo_list_dicts = ctable.find(mongoqry_dict,mongofields_dict,skip=limitby_skip, limit=limitby_limit, sort=mongosort_list,snapshot=snapshot) # pymongo cursor object
print "mongo_list_dicts=%s" % mongo_list_dicts
#if mongo_list_dicts.count() > 0: #
#colnames = mongo_list_dicts[0].keys() # assuming all docs have same "shape", grab colnames from first dictionary (aka row)
#else:
#colnames = mongofields_dict.keys()
#print "colnames = %s" % colnames
#rows = [row.values() for row in mongo_list_dicts]
rows = []
for record in mongo_list_dicts:
row=[]
for column in record:
if withId and (column == '_id'):
if isinstance(record[column],pymongo.objectid.ObjectId):
row.append( int(str(record[column]),16))
else:
#in case of alternative key
row.append( record[column] )
elif not (column == '_id'):
row.append(record[column])
rows.append(row)
#else the id is not supposed to be included. Work around error. mongo always sends key:(
return self.parse(rows,fields,mongofields_dict.keys(),False)
def INVERT(self,first):
#print "in invert first=%s" % first
return '-%s' % self.expand(first)
def drop(self, table, mode=''):
ctable = self.connection[table._tablename]
ctable.drop()
def truncate(self,table,mode,safe=None):
if safe==None:
safe=self.safe
ctable = self.connection[table._tablename]
ctable.remove(None, safe=True)
#the update function should return a string
def oupdate(self,tablename,query,fields):
if not isinstance(query,Query):
raise SyntaxError, "Not Supported"
filter = None
if query:
filter = self.expand(query)
f_v = []
modify = { '$set' : dict(((k.name,self.represent(v,k.type)) for k,v in fields)) }
return modify,filter
#TODO implement update
#TODO implement set operator
#TODO implement find and modify
#todo implement complex update
def update(self,tablename,query,fields,safe=None):
if safe==None:
safe=self.safe
#return amount of adjusted rows or zero, but no exceptions related not finding the result
if not isinstance(query,Query):
raise RuntimeError, "Not implemented"
amount = self.count(query,False)
modify,filter = self.oupdate(tablename,query,fields)
try:
if safe:
return self.connection[tablename].update(filter,modify,multi=True,safe=safe).n
else:
amount =self.count(query)
self.connection[tablename].update(filter,modify,multi=True,safe=safe)
return amount
except:
#TODO Reverse update query to verifiy that the query succeded
return 0
"""
An special update operator that enables the update of specific field
return a dict
"""
#this function returns a dict with the where clause and update fields
def _update(self,tablename,query,fields):
return str(self.oupdate(tablename,query,fields))
def bulk_insert(self, table, items):
return [self.insert(table,item) for item in items]
#TODO This will probably not work:(
def NOT(self, first):
result = {}
result["$not"] = self.expand(first)
return result
def AND(self,first,second):
f = self.expand(first)
s = self.expand(second)
f.update(s)
return f
def OR(self,first,second):
# pymongo expects: .find( {'$or' : [{'name':'1'}, {'name':'2'}] } )
result = {}
f = self.expand(first)
s = self.expand(second)
result['$or'] = [f,s]
return result
def BELONGS(self, first, second):
if isinstance(second, str):
return {self.expand(first) : {"$in" : [ second[:-1]]} }
elif second==[] or second==():
return {1:0}
items = [self.expand(item, first.type) for item in second]
return {self.expand(first) : {"$in" : items} }
def LIKE(self, first, second):
#escaping regex operators?
return {self.expand(first) : ('%s' % self.expand(second, 'string').replace('%','/'))}
def STARTSWITH(self, first, second):
#escaping regex operators?
return {self.expand(first) : ('/^%s/' % self.expand(second, 'string'))}
def ENDSWITH(self, first, second):
#escaping regex operators?
return {self.expand(first) : ('/%s^/' % self.expand(second, 'string'))}
def CONTAINS(self, first, second):
#There is a technical difference, but mongodb doesn't support that, but the result will be the same
return {self.expand(first) : ('/%s/' % self.expand(second, 'string'))}
def EQ(self,first,second):
result = {}
#if second is None:
#return '(%s == null)' % self.expand(first)
#return '(%s == %s)' % (self.expand(first),self.expand(second,first.type))
result[self.expand(first)] = self.expand(second)
return result
def NE(self, first, second=None):
print "in NE"
result = {}
result[self.expand(first)] = {'$ne': self.expand(second)}
return result
def LT(self,first,second=None):
if second is None:
raise RuntimeError, "Cannot compare %s < None" % first
print "in LT"
result = {}
result[self.expand(first)] = {'$lt': self.expand(second)}
return result
def LE(self,first,second=None):
if second is None:
raise RuntimeError, "Cannot compare %s <= None" % first
print "in LE"
result = {}
result[self.expand(first)] = {'$lte': self.expand(second)}
return result
def GT(self,first,second):
print "in GT"
#import pymongo.objectid
result = {}
#if expanded_first == '_id':
#if expanded_second != 0 and not isinstance(second,pymongo.objectid.ObjectId):
#raise SyntaxError, 'second argument must be of type bson.objectid.ObjectId'
#elif expanded_second == 0:
#expanded_second = pymongo.objectid.ObjectId('000000000000000000000000')
result[self.expand(first)] = {'$gt': self.expand(second)}
return result
def GE(self,first,second=None):
if second is None:
raise RuntimeError, "Cannot compare %s >= None" % first
print "in GE"
result = {}
result[self.expand(first)] = {'$gte': self.expand(second)}
return result
def ADD(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '%s + %s' % (self.expand(first), self.expand(second, first.type))
def SUB(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '(%s - %s)' % (self.expand(first), self.expand(second, first.type))
def MUL(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '(%s * %s)' % (self.expand(first), self.expand(second, first.type))
def DIV(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '(%s / %s)' % (self.expand(first), self.expand(second, first.type))
def MOD(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '(%s %% %s)' % (self.expand(first), self.expand(second, first.type))
def AS(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '%s AS %s' % (self.expand(first), second)
#We could implement an option that simulates a full featured SQL database. But I think the option should be set explicit or implemented as another library.
def ON(self, first, second):
raise NotImplementedError, "This is not possible in NoSQL, but can be simulated with a wrapper."
return '%s ON %s' % (self.expand(first), self.expand(second))
def COMMA(self, first, second):
return '%s, %s' % (self.expand(first), self.expand(second))
def bulk_insert(self, table, items):
return [self.insert(table,item) for item in items]
#TODO This will probably not work:(
def NOT(self, first):
result = {}
result["$not"] = self.expand(first)
return result
def AND(self,first,second):
f = self.expand(first)
s = self.expand(second)
f.update(s)
return f
def OR(self,first,second):
# pymongo expects: .find( {'$or' : [{'name':'1'}, {'name':'2'}] } )
result = {}
f = self.expand(first)
s = self.expand(second)
result['$or'] = [f,s]
return result
def BELONGS(self, first, second):
if isinstance(second, str):
return {self.expand(first) : {"$in" : [ second[:-1]]} }
elif second==[] or second==():
return {1:0}
items = [self.expand(item, first.type) for item in second]
return {self.expand(first) : {"$in" : items} }
#TODO verify full compatibilty with official SQL Like operator
def LIKE(self, first, second):
import re
return {self.expand(first) : {'$regex' : re.escape(self.expand(second, 'string')).replace('%','.*')}}
#TODO verify full compatibilty with official SQL Like operator
def STARTSWITH(self, first, second):
#TODO Solve almost the same problem as with endswith
import re
return {self.expand(first) : {'$regex' : '^' + re.escape(self.expand(second, 'string'))}}
#TODO verify full compatibilty with official SQL Like operator
def ENDSWITH(self, first, second):
#escaping regex operators?
#TODO if searched for a name like zsa_corbitt and the function is endswith('a') then this is also returned. Aldo it end with a t
import re
return {self.expand(first) : {'$regex' : re.escape(self.expand(second, 'string')) + '$'}}
#TODO verify full compatibilty with official oracle contains operator
def CONTAINS(self, first, second):
#There is a technical difference, but mongodb doesn't support that, but the result will be the same
#TODO contains operators need to be transformed to Regex
return {self.expand(first) : {' $regex' : ".*" + re.escape(self.expand(second, 'string')) + ".*"}}
def EQ(self,first,second):
result = {}
#if second is None:
#return '(%s == null)' % self.expand(first)
#return '(%s == %s)' % (self.expand(first),self.expand(second,first.type))
result[self.expand(first)] = self.expand(second)
return result
def NE(self, first, second=None):
print "in NE"
result = {}
result[self.expand(first)] = {'$ne': self.expand(second)}
return result
def LT(self,first,second=None):
if second is None:
raise RuntimeError, "Cannot compare %s < None" % first
print "in LT"
result = {}
result[self.expand(first)] = {'$lt': self.expand(second)}
return result
def LE(self,first,second=None):
if second is None:
raise RuntimeError, "Cannot compare %s <= None" % first
print "in LE"
result = {}
result[self.expand(first)] = {'$lte': self.expand(second)}
return result
def GT(self,first,second):
print "in GT"
#import pymongo.objectid
result = {}
#if expanded_first == '_id':
#if expanded_second != 0 and not isinstance(second,pymongo.objectid.ObjectId):
#raise SyntaxError, 'second argument must be of type bson.objectid.ObjectId'
#elif expanded_second == 0:
#expanded_second = pymongo.objectid.ObjectId('000000000000000000000000')
result[self.expand(first)] = {'$gt': self.expand(second)}
return result
def GE(self,first,second=None):
if second is None:
raise RuntimeError, "Cannot compare %s >= None" % first
print "in GE"
result = {}
result[self.expand(first)] = {'$gte': self.expand(second)}
return result
#TODO javascript has math
def ADD(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '%s + %s' % (self.expand(first), self.expand(second, first.type))
#TODO javascript has math
def SUB(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '(%s - %s)' % (self.expand(first), self.expand(second, first.type))
#TODO javascript has math
def MUL(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '(%s * %s)' % (self.expand(first), self.expand(second, first.type))
#TODO javascript has math
def DIV(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '(%s / %s)' % (self.expand(first), self.expand(second, first.type))
#TODO javascript has math
def MOD(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '(%s %% %s)' % (self.expand(first), self.expand(second, first.type))
#TODO javascript can do this
def AS(self, first, second):
raise NotImplementedError, "This must yet be replaced with javescript in order to accomplish this. Sorry"
return '%s AS %s' % (self.expand(first), second)
#We could implement an option that simulates a full featured SQL database. But I think the option should be set explicit or implemented as another library.
def ON(self, first, second):
raise NotImplementedError, "This is not possible in NoSQL, but can be simulated with a wrapper."
return '%s ON %s' % (self.expand(first), self.expand(second))
#TODO is this used in mongodb?
def COMMA(self, first, second):
return '%s, %s' % (self.expand(first), self.expand(second))
class IMAPAdapter(NoSQLAdapter):
""" IMAP server adapter
This class is intended as an interface with
email IMAP servers to perform simple queries in the
web2py DAL query syntax, so email read, search and
other related IMAP mail services (as those implemented
by brands like Google(r), and Yahoo!(r)
can be managed from web2py applications.
The code uses examples by Yuji Tomita on this post:
http://yuji.wordpress.com/2011/06/22/python-imaplib-imap-example-with-gmail/#comment-1137
and is based in docs for Python imaplib, python email
and email IETF's (i.e. RFC2060 and RFC3501)
This adapter was tested with a small set of operations with Gmail(r). Other
services requests could raise command syntax and response data issues.
It creates its table and field names "statically",
meaning that the developer should leave the table and field
definitions to the DAL instance by calling the adapter's
.define_tables() method. The tables are defined with the
IMAP server mailbox list information.
Here is a list of supported fields:
Field Type Description
################################################################
uid string
answered boolean Flag
created date
content list:string A list of text or html parts
to string
cc string
bcc string
size integer the amount of octets of the message*
deleted boolean Flag
draft boolean Flag
flagged boolean Flag
sender string
recent boolean Flag
seen boolean Flag
subject string
mime string The mime header declaration
email string The complete RFC822 message**
attachments list:string Each non text decoded part as string
*At the application side it is measured as the length of the RFC822
message string
WARNING: As row id's are mapped to email sequence numbers,
make sure your imap client web2py app does not delete messages
during select or update actions, to prevent
updating or deleting different messages.
Sequence numbers change whenever the mailbox is updated.
To avoid this sequence numbers issues, it is recommended the use
of uid fields in query references (although the update and delete
in separate actions rule still applies).
# This is the code recommended to start imap support
# at the app's model:
imapdb = DAL("imap://user:password@server:port", pool_size=1) # port 993 for ssl
imapdb.define_tables()
Here is an (incomplete) list of possible imap commands:
# Count today's unseen messages
# smaller than 6000 octets from the
# inbox mailbox
q = imapdb.INBOX.seen == False
q &= imapdb.INBOX.created == datetime.date.today()
q &= imapdb.INBOX.size < 6000
unread = imapdb(q).count()
# Fetch last query messages
rows = imapdb(q).select()
# it is also possible to filter query select results with limitby and
# sequences of mailbox fields
set.select(<fields sequence>, limitby=(<int>, <int>))
# Mark last query messages as seen
messages = [row.uid for row in rows]
seen = imapdb(imapdb.INBOX.uid.belongs(messages)).update(seen=True)
# Delete messages in the imap database that have mails from mr. Gumby
deleted = 0
for mailbox in imapdb.tables
deleted += imapdb(imapdb[mailbox].sender.contains("gumby")).delete()
# It is possible also to mark messages for deletion instead of ereasing them
# directly with set.update(deleted=True)
"""
types = {
'string': str,
'text': str,
'date': datetime.date,
'datetime': datetime.datetime,
'id': long,
'boolean': bool,
'integer': int,
'blob': str,
'list:string': str,
}
dbengine = 'imap'
driver = globals().get('imaplib',None)
def __init__(self,
db,
uri,
pool_size=0,
folder=None,
db_codec ='UTF-8',
credential_decoder=lambda x:x,
driver_args={},
adapter_args={}):
# db uri: user@example.com:password@imap.server.com:123
# TODO: max size adapter argument for preventing large mail transfers
uri = uri.split("://")[1]
self.db = db
self.uri = uri
self.pool_size=pool_size
self.folder = folder
self.db_codec = db_codec
self.credential_decoder = credential_decoder
self.driver_args = driver_args
self.adapter_args = adapter_args
self.mailbox_size = None
self.charset = sys.getfilesystemencoding()
# imap class
self.imap4 = None
""" MESSAGE is an identifier for sequence number"""
self.flags = ['\\Deleted', '\\Draft', '\\Flagged',
'\\Recent', '\\Seen', '\\Answered']
self.search_fields = {
'id': 'MESSAGE', 'created': 'DATE',
'uid': 'UID', 'sender': 'FROM',
'to': 'TO', 'cc': 'CC',
'bcc': 'BCC', 'content': 'TEXT',
'size': 'SIZE', 'deleted': '\\Deleted',
'draft': '\\Draft', 'flagged': '\\Flagged',
'recent': '\\Recent', 'seen': '\\Seen',
'subject': 'SUBJECT', 'answered': '\\Answered',
'mime': None, 'email': None,
'attachments': None
}
db['_lastsql'] = ''
m = re.compile('^(?P<user>[^:]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:@/]+)(\:(?P<port>[0-9]+))?$').match(uri)
user = m.group('user')
password = m.group('password')
host = m.group('host')
port = int(m.group('port'))
over_ssl = False
if port==993:
over_ssl = True
driver_args.update(dict(host=host,port=port, password=password, user=user))
def connect(driver_args=driver_args):
# it is assumed sucessful authentication alLways
# TODO: support direct connection and login tests
if over_ssl:
self.imap4 = self.driver.IMAP4_SSL
else:
self.imap4 = self.driver.IMAP4
connection = self.imap4(driver_args["host"], driver_args["port"])
data = connection.login(driver_args["user"], driver_args["password"])
# print "Connected to remote server"
# print data
# static mailbox list
connection.mailbox_names = None
# dummy cursor function
connection.cursor = lambda : True
return connection
self.pool_connection(connect)
self.db.define_tables = self.define_tables
def pool_connection(self, f, cursor=True):
"""
IMAP4 Pool connection method
imap connection lacks of self cursor command.
A custom command should be provided as a replacement
for connection pooling to prevent uncaught remote session
closing
"""
# print "Pool Connection"
if not self.pool_size:
self.connection = f()
self.cursor = cursor and self.connection.cursor()
else:
uri = self.uri
# print "uri", self.uri
while True:
sql_locker.acquire()
if not uri in ConnectionPool.pools:
ConnectionPool.pools[uri] = []
if ConnectionPool.pools[uri]:
self.connection = ConnectionPool.pools[uri].pop()
sql_locker.release()
self.cursor = cursor and self.connection.cursor()
# print "self.cursor", self.cursor
if self.cursor and self.check_active_connection:
try:
# check if connection is alive or close it
result, data = self.connection.list()
# print "Checked connection"
# print result, data
# self.execute('SELECT 1;')
except:
# Possible connection reset error
# TODO: read exception class
# print "Re-connecting to IMAP server"
self.connection = f()
break
else:
sql_locker.release()
self.connection = f()
self.cursor = cursor and self.connection.cursor()
break
if not hasattr(thread,'instances'):
thread.instances = []
thread.instances.append(self)
def get_last_message(self, tablename):
last_message = None
# request mailbox list to the server
# if needed
if not isinstance(self.connection.mailbox_names, dict):
self.get_mailboxes()
try:
result = self.connection.select(self.connection.mailbox_names[tablename])
last_message = int(result[1][0])
except (IndexError, ValueError, TypeError, KeyError), e:
logger.debug("Error retrieving the last mailbox sequence number. %s" % str(e))
return last_message
def get_uid_bounds(self, tablename):
if not isinstance(self.connection.mailbox_names, dict):
self.get_mailboxes()
# fetch first and last messages
# return (first, last) messages uid's
last_message = self.get_last_message(tablename)
result, data = self.connection.uid("search", None, "(ALL)")
uid_list = data[0].strip().split()
if len(uid_list) <= 0:
return None
else:
return (uid_list[0], uid_list[-1])
def convert_date(self, date, add=None):
if add is None:
add = datetime.timedelta()
""" Convert a date object to a string
with d-Mon-Y style for IMAP or the inverse
case
add <timedelta> adds to the date object
"""
months = [None, "Jan","Feb","Mar","Apr","May","Jun",
"Jul", "Aug","Sep","Oct","Nov","Dec"]
if isinstance(date, basestring):
# Prevent unexpected date response format
try:
dayname, datestring = date.split(",")
except (ValueError):
logger.debug("Could not parse date text: %s" % date)
return None
date_list = datestring.strip().split()
year = int(date_list[2])
month = months.index(date_list[1])
day = int(date_list[0])
hms = [int(value) for value in date_list[3].split(":")]
return datetime.datetime(year, month, day,
hms[0], hms[1], hms[2]) + add
elif isinstance(date, (datetime.datetime, datetime.date)):
return (date + add).strftime("%d-%b-%Y")
else:
return None
def encode_text(self, text, charset, errors="replace"):
""" convert text for mail to unicode"""
if text is None:
text = ""
else:
if isinstance(text, str):
if charset is not None:
text = unicode(text, charset, errors)
else:
text = unicode(text, "utf-8", errors)
else:
raise Exception("Unsupported mail text type %s" % type(text))
return text.encode("utf-8")
def get_charset(self, message):
charset = message.get_content_charset()
return charset
def reset_mailboxes(self):
self.connection.mailbox_names = None
self.get_mailboxes()
def get_mailboxes(self):
""" Query the mail database for mailbox names """
mailboxes_list = self.connection.list()
self.connection.mailbox_names = dict()
mailboxes = list()
for item in mailboxes_list[1]:
item = item.strip()
if not "NOSELECT" in item.upper():
sub_items = item.split("\"")
sub_items = [sub_item for sub_item in sub_items if len(sub_item.strip()) > 0]
mailbox = sub_items[len(sub_items) - 1]
# remove unwanted characters and store original names
mailbox_name = mailbox.replace("[", "").replace("]", "").replace("/", "_")
mailboxes.append(mailbox_name)
self.connection.mailbox_names[mailbox_name] = mailbox
# print "Mailboxes query", mailboxes
return mailboxes
def get_query_mailbox(self, query):
nofield = True
tablename = None
attr = query
while nofield:
if hasattr(attr, "first"):
attr = attr.first
if isinstance(attr, Field):
return attr.tablename
elif isinstance(attr, Query):
pass
else:
return None
else:
return None
return tablename
def is_flag(self, flag):
if self.search_fields.get(flag, None) in self.flags:
return True
else:
return False
def define_tables(self):
"""
Auto create common IMAP fileds
This function creates fields definitions "statically"
meaning that custom fields as in other adapters should
not be supported and definitions handled on a service/mode
basis (local syntax for Gmail(r), Ymail(r)
"""
if not isinstance(self.connection.mailbox_names, dict):
self.get_mailboxes()
mailboxes = self.connection.mailbox_names.keys()
for mailbox_name in mailboxes:
self.db.define_table("%s" % mailbox_name,
Field("uid", "string", writable=False),
Field("answered", "boolean"),
Field("created", "datetime", writable=False),
Field("content", "list:string", writable=False),
Field("to", "string", writable=False),
Field("cc", "string", writable=False),
Field("bcc", "string", writable=False),
Field("size", "integer", writable=False),
Field("deleted", "boolean"),
Field("draft", "boolean"),
Field("flagged", "boolean"),
Field("sender", "string", writable=False),
Field("recent", "boolean", writable=False),
Field("seen", "boolean"),
Field("subject", "string", writable=False),
Field("mime", "string", writable=False),
Field("email", "string", writable=False, readable=False),
Field("attachments", "list:string", writable=False, readable=False),
)
def create_table(self, *args, **kwargs):
# not implemented
logger.debug("Create table feature is not implemented for %s" % type(self))
def _select(self,query,fields,attributes):
""" Search and Fetch records and return web2py
rows
"""
if use_common_filters(query):
query = self.common_filter(query, [self.get_query_mailbox(query),])
# move this statement elsewhere (upper-level)
import email
import email.header
decode_header = email.header.decode_header
# get records from imap server with search + fetch
# convert results to a dictionary
tablename = None
fetch_results = list()
if isinstance(query, (Expression, Query)):
tablename = self.get_table(query)
mailbox = self.connection.mailbox_names.get(tablename, None)
if isinstance(query, Expression):
pass
elif isinstance(query, Query):
if mailbox is not None:
# select with readonly
selected = self.connection.select(mailbox, True)
self.mailbox_size = int(selected[1][0])
search_query = "(%s)" % str(query).strip()
# print "Query", query
# print "Search query", search_query
search_result = self.connection.uid("search", None, search_query)
# print "Search result", search_result
# print search_result
# Normal IMAP response OK is assumed (change this)
if search_result[0] == "OK":
# For "light" remote server responses just get the first
# ten records (change for non-experimental implementation)
# However, light responses are not guaranteed with this
# approach, just fewer messages.
# TODO: change limitby single to 2-tuple argument
limitby = attributes.get('limitby', None)
messages_set = search_result[1][0].split()
# descending order
messages_set.reverse()
if limitby is not None:
# TODO: asc/desc attributes
messages_set = messages_set[int(limitby[0]):int(limitby[1])]
# Partial fetches are not used since the email
# library does not seem to support it (it converts
# partial messages to mangled message instances)
imap_fields = "(RFC822)"
if len(messages_set) > 0:
# create fetch results object list
# fetch each remote message and store it in memmory
# (change to multi-fetch command syntax for faster
# transactions)
for uid in messages_set:
# fetch the RFC822 message body
typ, data = self.connection.uid("fetch", uid, imap_fields)
if typ == "OK":
fr = {"message": int(data[0][0].split()[0]),
"uid": int(uid),
"email": email.message_from_string(data[0][1]),
"raw_message": data[0][1]
}
fr["multipart"] = fr["email"].is_multipart()
# fetch flags for the message
ftyp, fdata = self.connection.uid("fetch", uid, "(FLAGS)")
if ftyp == "OK":
# print "Raw flags", fdata
fr["flags"] = self.driver.ParseFlags(fdata[0])
# print "Flags", fr["flags"]
fetch_results.append(fr)
else:
# error retrieving the flags for this message
pass
else:
# error retrieving the message body
pass
elif isinstance(query, basestring):
# not implemented
pass
else:
pass
imapqry_dict = {}
imapfields_dict = {}
if len(fields) == 1 and isinstance(fields[0], SQLALL):
allfields = True
elif len(fields) == 0:
allfields = True
else:
allfields = False
if allfields:
fieldnames = ["%s.%s" % (tablename, field) for field in self.search_fields.keys()]
else:
fieldnames = ["%s.%s" % (tablename, field.name) for field in fields]
for k in fieldnames:
imapfields_dict[k] = k
imapqry_list = list()
imapqry_array = list()
for fr in fetch_results:
attachments = []
content = []
size = 0
n = int(fr["message"])
item_dict = dict()
message = fr["email"]
uid = fr["uid"]
charset = self.get_charset(message)
flags = fr["flags"]
raw_message = fr["raw_message"]
# Return messages data mapping static fields
# and fetched results. Mapping should be made
# outside the select function (with auxiliary
# instance methods)
# pending: search flags states trough the email message
# instances for correct output
if "%s.id" % tablename in fieldnames:
item_dict["%s.id" % tablename] = n
if "%s.created" % tablename in fieldnames:
item_dict["%s.created" % tablename] = self.convert_date(message["Date"])
if "%s.uid" % tablename in fieldnames:
item_dict["%s.uid" % tablename] = uid
if "%s.sender" % tablename in fieldnames:
# If there is no encoding found in the message header
# force utf-8 replacing characters (change this to
# module's defaults). Applies to .sender, .to, .cc and .bcc fields
#############################################################################
# TODO: External function to manage encoding and decoding of message strings
#############################################################################
item_dict["%s.sender" % tablename] = self.encode_text(message["From"], charset)
if "%s.to" % tablename in fieldnames:
item_dict["%s.to" % tablename] = self.encode_text(message["To"], charset)
if "%s.cc" % tablename in fieldnames:
if "Cc" in message.keys():
# print "cc field found"
item_dict["%s.cc" % tablename] = self.encode_text(message["Cc"], charset)
else:
item_dict["%s.cc" % tablename] = ""
if "%s.bcc" % tablename in fieldnames:
if "Bcc" in message.keys():
# print "bcc field found"
item_dict["%s.bcc" % tablename] = self.encode_text(message["Bcc"], charset)
else:
item_dict["%s.bcc" % tablename] = ""
if "%s.deleted" % tablename in fieldnames:
item_dict["%s.deleted" % tablename] = "\\Deleted" in flags
if "%s.draft" % tablename in fieldnames:
item_dict["%s.draft" % tablename] = "\\Draft" in flags
if "%s.flagged" % tablename in fieldnames:
item_dict["%s.flagged" % tablename] = "\\Flagged" in flags
if "%s.recent" % tablename in fieldnames:
item_dict["%s.recent" % tablename] = "\\Recent" in flags
if "%s.seen" % tablename in fieldnames:
item_dict["%s.seen" % tablename] = "\\Seen" in flags
if "%s.subject" % tablename in fieldnames:
subject = message["Subject"]
decoded_subject = decode_header(subject)
text = decoded_subject[0][0]
encoding = decoded_subject[0][1]
if encoding in (None, ""):
encoding = charset
item_dict["%s.subject" % tablename] = self.encode_text(text, encoding)
if "%s.answered" % tablename in fieldnames:
item_dict["%s.answered" % tablename] = "\\Answered" in flags
if "%s.mime" % tablename in fieldnames:
item_dict["%s.mime" % tablename] = message.get_content_type()
# Here goes the whole RFC822 body as an email instance
# for controller side custom processing
# The message is stored as a raw string
# >> email.message_from_string(raw string)
# returns a Message object for enhanced object processing
if "%s.email" % tablename in fieldnames:
item_dict["%s.email" % tablename] = self.encode_text(raw_message, charset)
# Size measure as suggested in a Velocity Reviews post
# by Tim Williams: "how to get size of email attachment"
# Note: len() and server RFC822.SIZE reports doesn't match
# To retrieve the server size for representation would add a new
# fetch transaction to the process
for part in message.walk():
if "%s.attachments" % tablename in fieldnames:
if not "text" in part.get_content_maintype():
attachments.append(part.get_payload(decode=True))
if "%s.content" % tablename in fieldnames:
if "text" in part.get_content_maintype():
payload = self.encode_text(part.get_payload(decode=True), charset)
content.append(payload)
if "%s.size" % tablename in fieldnames:
if part is not None:
size += len(str(part))
item_dict["%s.content" % tablename] = bar_encode(content)
item_dict["%s.attachments" % tablename] = bar_encode(attachments)
item_dict["%s.size" % tablename] = size
imapqry_list.append(item_dict)
# extra object mapping for the sake of rows object
# creation (sends an array or lists)
for item_dict in imapqry_list:
imapqry_array_item = list()
for fieldname in fieldnames:
imapqry_array_item.append(item_dict[fieldname])
imapqry_array.append(imapqry_array_item)
return tablename, imapqry_array, fieldnames
def select(self,query,fields,attributes):
tablename, imapqry_array , fieldnames = self._select(query,fields,attributes)
# parse result and return a rows object
colnames = fieldnames
result = self.parse(imapqry_array, fields, colnames)
return result
def update(self, tablename, query, fields):
# print "_update"
if use_common_filters(query):
query = self.common_filter(query, [tablename,])
mark = []
unmark = []
rowcount = 0
query = str(query)
if query:
for item in fields:
field = item[0]
name = field.name
value = item[1]
if self.is_flag(name):
flag = self.search_fields[name]
if (value is not None) and (flag != "\\Recent"):
if value:
mark.append(flag)
else:
unmark.append(flag)
# print "Selecting mailbox ..."
result, data = self.connection.select(self.connection.mailbox_names[tablename])
# print "Retrieving sequence numbers remotely"
string_query = "(%s)" % query
# print "string query", string_query
result, data = self.connection.search(None, string_query)
store_list = [item.strip() for item in data[0].split() if item.strip().isdigit()]
# print "Storing values..."
# change marked flags
for number in store_list:
result = None
if len(mark) > 0:
# print "Marking flags ..."
result, data = self.connection.store(number, "+FLAGS", "(%s)" % " ".join(mark))
if len(unmark) > 0:
# print "Unmarking flags ..."
result, data = self.connection.store(number, "-FLAGS", "(%s)" % " ".join(unmark))
if result == "OK":
rowcount += 1
return rowcount
def count(self,query,distinct=None):
counter = 0
tablename = self.get_query_mailbox(query)
if query and tablename is not None:
if use_common_filters(query):
query = self.common_filter(query, [tablename,])
# print "Selecting mailbox ..."
result, data = self.connection.select(self.connection.mailbox_names[tablename])
# print "Retrieving sequence numbers remotely"
string_query = "(%s)" % query
result, data = self.connection.search(None, string_query)
store_list = [item.strip() for item in data[0].split() if item.strip().isdigit()]
counter = len(store_list)
return counter
def delete(self, tablename, query):
counter = 0
if query:
# print "Selecting mailbox ..."
if use_common_filters(query):
query = self.common_filter(query, [tablename,])
result, data = self.connection.select(self.connection.mailbox_names[tablename])
# print "Retrieving sequence numbers remotely"
string_query = "(%s)" % query
result, data = self.connection.search(None, string_query)
store_list = [item.strip() for item in data[0].split() if item.strip().isdigit()]
for number in store_list:
result, data = self.connection.store(number, "+FLAGS", "(\\Deleted)")
# print "Deleting message", result, data
if result == "OK":
counter += 1
if counter > 0:
# print "Ereasing permanently"
result, data = self.connection.expunge()
return counter
def BELONGS(self, first, second):
result = None
name = self.search_fields[first.name]
if name == "MESSAGE":
values = [str(val) for val in second if str(val).isdigit()]
result = "%s" % ",".join(values).strip()
elif name == "UID":
values = [str(val) for val in second if str(val).isdigit()]
result = "UID %s" % ",".join(values).strip()
else:
raise Exception("Operation not supported")
# result = "(%s %s)" % (self.expand(first), self.expand(second))
return result
def CONTAINS(self, first, second):
result = None
name = self.search_fields[first.name]
if name in ("FROM", "TO", "SUBJECT", "TEXT"):
result = "%s \"%s\"" % (name, self.expand(second))
else:
if first.name in ("cc", "bcc"):
result = "%s \"%s\"" % (first.name.upper(), self.expand(second))
elif first.name == "mime":
result = "HEADER Content-Type \"%s\"" % self.expand(second)
else:
raise Exception("Operation not supported")
return result
def GT(self, first, second):
result = None
name = self.search_fields[first.name]
if name == "MESSAGE":
last_message = self.get_last_message(first.tablename)
result = "%d:%d" % (int(self.expand(second)) + 1, last_message)
elif name == "UID":
# GT and LT may not return
# expected sets depending on
# the uid format implemented
try:
pedestal, threshold = self.get_uid_bounds(first.tablename)
except TypeError, e:
logger.debug("Error requesting uid bounds: %s", str(e))
return ""
try:
lower_limit = int(self.expand(second)) + 1
except (ValueError, TypeError), e:
raise Exception("Operation not supported (non integer UID)")
result = "UID %s:%s" % (lower_limit, threshold)
elif name == "DATE":
result = "SINCE %s" % self.convert_date(second, add=datetime.timedelta(1))
elif name == "SIZE":
result = "LARGER %s" % self.expand(second)
else:
raise Exception("Operation not supported")
return result
def GE(self, first, second):
result = None
name = self.search_fields[first.name]
if name == "MESSAGE":
last_message = self.get_last_message(first.tablename)
result = "%s:%s" % (self.expand(second), last_message)
elif name == "UID":
# GT and LT may not return
# expected sets depending on
# the uid format implemented
try:
pedestal, threshold = self.get_uid_bounds(first.tablename)
except TypeError, e:
logger.debug("Error requesting uid bounds: %s", str(e))
return ""
lower_limit = self.expand(second)
result = "UID %s:%s" % (lower_limit, threshold)
elif name == "DATE":
result = "SINCE %s" % self.convert_date(second)
else:
raise Exception("Operation not supported")
return result
def LT(self, first, second):
result = None
name = self.search_fields[first.name]
if name == "MESSAGE":
result = "%s:%s" % (1, int(self.expand(second)) - 1)
elif name == "UID":
try:
pedestal, threshold = self.get_uid_bounds(first.tablename)
except TypeError, e:
logger.debug("Error requesting uid bounds: %s", str(e))
return ""
try:
upper_limit = int(self.expand(second)) - 1
except (ValueError, TypeError), e:
raise Exception("Operation not supported (non integer UID)")
result = "UID %s:%s" % (pedestal, upper_limit)
elif name == "DATE":
result = "BEFORE %s" % self.convert_date(second)
elif name == "SIZE":
result = "SMALLER %s" % self.expand(second)
else:
raise Exception("Operation not supported")
return result
def LE(self, first, second):
result = None
name = self.search_fields[first.name]
if name == "MESSAGE":
result = "%s:%s" % (1, self.expand(second))
elif name == "UID":
try:
pedestal, threshold = self.get_uid_bounds(first.tablename)
except TypeError, e:
logger.debug("Error requesting uid bounds: %s", str(e))
return ""
upper_limit = int(self.expand(second))
result = "UID %s:%s" % (pedestal, upper_limit)
elif name == "DATE":
result = "BEFORE %s" % self.convert_date(second, add=datetime.timedelta(1))
else:
raise Exception("Operation not supported")
return result
def NE(self, first, second):
result = self.NOT(self.EQ(first, second))
result = result.replace("NOT NOT", "").strip()
return result
def EQ(self,first,second):
name = self.search_fields[first.name]
result = None
if name is not None:
if name == "MESSAGE":
# query by message sequence number
result = "%s" % self.expand(second)
elif name == "UID":
result = "UID %s" % self.expand(second)
elif name == "DATE":
result = "ON %s" % self.convert_date(second)
elif name in self.flags:
if second:
result = "%s" % (name.upper()[1:])
else:
result = "NOT %s" % (name.upper()[1:])
else:
raise Exception("Operation not supported")
else:
raise Exception("Operation not supported")
return result
def AND(self, first, second):
result = "%s %s" % (self.expand(first), self.expand(second))
return result
def OR(self, first, second):
result = "OR %s %s" % (self.expand(first), self.expand(second))
return "%s" % result.replace("OR OR", "OR")
def NOT(self, first):
result = "NOT %s" % self.expand(first)
return result
########################################################################
# end of adapters
########################################################################
ADAPTERS = {
'sqlite': SQLiteAdapter,
'sqlite:memory': SQLiteAdapter,
'mysql': MySQLAdapter,
'postgres': PostgreSQLAdapter,
'postgres:psycopg2': PostgreSQLAdapter,
'postgres:pg8000': PostgreSQLAdapter,
'oracle': OracleAdapter,
'mssql': MSSQLAdapter,
'mssql2': MSSQL2Adapter,
'db2': DB2Adapter,
'teradata': TeradataAdapter,
'informix': InformixAdapter,
'firebird': FireBirdAdapter,
'firebird_embedded': FireBirdAdapter,
'ingres': IngresAdapter,
'ingresu': IngresUnicodeAdapter,
'sapdb': SAPDBAdapter,
'cubrid': CubridAdapter,
'jdbc:sqlite': JDBCSQLiteAdapter,
'jdbc:sqlite:memory': JDBCSQLiteAdapter,
'jdbc:postgres': JDBCPostgreSQLAdapter,
'gae': GoogleDatastoreAdapter, # discouraged, for backward compatibility
'google:datastore': GoogleDatastoreAdapter,
'google:sql': GoogleSQLAdapter,
'couchdb': CouchDBAdapter,
'mongodb': MongoDBAdapter,
'imap': IMAPAdapter
}
def sqlhtml_validators(field):
"""
Field type validation, using web2py's validators mechanism.
makes sure the content of a field is in line with the declared
fieldtype
"""
if not have_validators:
return []
field_type, field_length = field.type, field.length
if isinstance(field_type, SQLCustomType):
if hasattr(field_type, 'validator'):
return field_type.validator
else:
field_type = field_type.type
elif not isinstance(field_type,str):
return []
requires=[]
def ff(r,id):
row=r(id)
if not row:
return id
elif hasattr(r, '_format') and isinstance(r._format,str):
return r._format % row
elif hasattr(r, '_format') and callable(r._format):
return r._format(row)
else:
return id
if field_type == 'string':
requires.append(validators.IS_LENGTH(field_length))
elif field_type == 'text':
requires.append(validators.IS_LENGTH(field_length))
elif field_type == 'password':
requires.append(validators.IS_LENGTH(field_length))
elif field_type == 'double':
requires.append(validators.IS_FLOAT_IN_RANGE(-1e100, 1e100))
elif field_type == 'integer':
requires.append(validators.IS_INT_IN_RANGE(-1e100, 1e100))
elif field_type.startswith('decimal'):
requires.append(validators.IS_DECIMAL_IN_RANGE(-10**10, 10**10))
elif field_type == 'date':
requires.append(validators.IS_DATE())
elif field_type == 'time':
requires.append(validators.IS_TIME())
elif field_type == 'datetime':
requires.append(validators.IS_DATETIME())
elif field.db and field_type.startswith('reference') and \
field_type.find('.') < 0 and \
field_type[10:] in field.db.tables:
referenced = field.db[field_type[10:]]
def repr_ref(id, row=None, r=referenced, f=ff): return f(r, id)
field.represent = field.represent or repr_ref
if hasattr(referenced, '_format') and referenced._format:
requires = validators.IS_IN_DB(field.db,referenced._id,
referenced._format)
if field.unique:
requires._and = validators.IS_NOT_IN_DB(field.db,field)
if field.tablename == field_type[10:]:
return validators.IS_EMPTY_OR(requires)
return requires
elif field.db and field_type.startswith('list:reference') and \
field_type.find('.') < 0 and \
field_type[15:] in field.db.tables:
referenced = field.db[field_type[15:]]
def list_ref_repr(ids, row=None, r=referenced, f=ff):
if not ids:
return None
refs = r._db(r._id.belongs(ids)).select(r._id)
return (refs and ', '.join(str(f(r,ref.id)) for ref in refs) or '')
field.represent = field.represent or list_ref_repr
if hasattr(referenced, '_format') and referenced._format:
requires = validators.IS_IN_DB(field.db,referenced._id,
referenced._format,multiple=True)
else:
requires = validators.IS_IN_DB(field.db,referenced._id,
multiple=True)
if field.unique:
requires._and = validators.IS_NOT_IN_DB(field.db,field)
return requires
elif field_type.startswith('list:'):
def repr_list(values,row=None): return', '.join(str(v) for v in (values or []))
field.represent = field.represent or repr_list
if field.unique:
requires.insert(0,validators.IS_NOT_IN_DB(field.db,field))
sff = ['in', 'do', 'da', 'ti', 'de', 'bo']
if field.notnull and not field_type[:2] in sff:
requires.insert(0, validators.IS_NOT_EMPTY())
elif not field.notnull and field_type[:2] in sff and requires:
requires[-1] = validators.IS_EMPTY_OR(requires[-1])
return requires
def bar_escape(item):
return str(item).replace('|', '||')
def bar_encode(items):
return '|%s|' % '|'.join(bar_escape(item) for item in items if str(item).strip())
def bar_decode_integer(value):
return [int(x) for x in value.split('|') if x.strip()]
def bar_decode_string(value):
return [x.replace('||', '|') for x in string_unpack.split(value[1:-1]) if x.strip()]
class Row(dict):
"""
a dictionary that lets you do d['a'] as well as d.a
this is only used to store a Row
"""
def __getitem__(self, key):
key=str(key)
m = regex_table_field.match(key)
if key in self.get('_extra',{}):
return self._extra[key]
elif m:
try:
return dict.__getitem__(self, m.group(1))[m.group(2)]
except (KeyError,TypeError):
key = m.group(2)
return dict.__getitem__(self, key)
def __call__(self,key):
return self.__getitem__(key)
def __setitem__(self, key, value):
dict.__setitem__(self, str(key), value)
def __getattr__(self, key):
return self[key]
def __setattr__(self, key, value):
self[key] = value
def __repr__(self):
return '<Row ' + dict.__repr__(self) + '>'
def __int__(self):
return dict.__getitem__(self,'id')
def __eq__(self,other):
try:
return self.as_dict() == other.as_dict()
except AttributeError:
return False
def __ne__(self,other):
return not (self == other)
def __copy__(self):
return Row(dict(self))
def as_dict(self,datetime_to_str=False):
SERIALIZABLE_TYPES = (str,unicode,int,long,float,bool,list)
d = dict(self)
for k in copy.copy(d.keys()):
v=d[k]
if d[k] is None:
continue
elif isinstance(v,Row):
d[k]=v.as_dict()
elif isinstance(v,Reference):
d[k]=int(v)
elif isinstance(v,decimal.Decimal):
d[k]=float(v)
elif isinstance(v, (datetime.date, datetime.datetime, datetime.time)):
if datetime_to_str:
d[k] = v.isoformat().replace('T',' ')[:19]
elif not isinstance(v,SERIALIZABLE_TYPES):
del d[k]
return d
def Row_unpickler(data):
return Row(cPickle.loads(data))
def Row_pickler(data):
return Row_unpickler, (cPickle.dumps(data.as_dict(datetime_to_str=False)),)
copy_reg.pickle(Row, Row_pickler, Row_unpickler)
################################################################################
# Everything below should be independent on the specifics of the
# database and should for RDBMs and some NoSQL databases
################################################################################
class SQLCallableList(list):
def __call__(self):
return copy.copy(self)
def smart_query(fields,text):
if not isinstance(fields,(list,tuple)):
fields = [fields]
new_fields = []
for field in fields:
if isinstance(field,Field):
new_fields.append(field)
elif isinstance(field,Table):
for ofield in field:
new_fields.append(ofield)
else:
raise RuntimeError, "fields must be a list of fields"
fields = new_fields
field_map = {}
for field in fields:
n = field.name.lower()
if not n in field_map:
field_map[n] = field
n = str(field).lower()
if not n in field_map:
field_map[n] = field
re_constants = re.compile('(\"[^\"]*?\")|(\'[^\']*?\')')
constants = {}
i = 0
while True:
m = re_constants.search(text)
if not m: break
text = text[:m.start()]+('#%i' % i)+text[m.end():]
constants[str(i)] = m.group()[1:-1]
i+=1
text = re.sub('\s+',' ',text).lower()
for a,b in [('&','and'),
('|','or'),
('~','not'),
('==','='),
('<','<'),
('>','>'),
('<=','<='),
('>=','>='),
('<>','!='),
('=<','<='),
('=>','>='),
('=','='),
(' less or equal than ','<='),
(' greater or equal than ','>='),
(' equal or less than ','<='),
(' equal or greater than ','>='),
(' less or equal ','<='),
(' greater or equal ','>='),
(' equal or less ','<='),
(' equal or greater ','>='),
(' not equal to ','!='),
(' not equal ','!='),
(' equal to ','='),
(' equal ','='),
(' equals ','!='),
(' less than ','<'),
(' greater than ','>'),
(' starts with ','startswith'),
(' ends with ','endswith'),
(' is ','=')]:
if a[0]==' ':
text = text.replace(' is'+a,' %s ' % b)
text = text.replace(a,' %s ' % b)
text = re.sub('\s+',' ',text).lower()
text = re.sub('(?P<a>[\<\>\!\=])\s+(?P<b>[\<\>\!\=])','\g<a>\g<b>',text)
query = field = neg = op = logic = None
for item in text.split():
if field is None:
if item == 'not':
neg = True
elif not neg and not logic and item in ('and','or'):
logic = item
elif item in field_map:
field = field_map[item]
else:
raise RuntimeError, "Invalid syntax"
elif not field is None and op is None:
op = item
elif not op is None:
if item.startswith('#'):
if not item[1:] in constants:
raise RuntimeError, "Invalid syntax"
value = constants[item[1:]]
else:
value = item
if op == '=': op = 'like'
if op == '=': new_query = field==value
elif op == '<': new_query = field<value
elif op == '>': new_query = field>value
elif op == '<=': new_query = field<=value
elif op == '>=': new_query = field>=value
elif op == '!=': new_query = field!=value
elif field.type in ('text','string'):
if op == 'contains': new_query = field.contains(value)
elif op == 'like': new_query = field.like(value)
elif op == 'startswith': new_query = field.startswith(value)
elif op == 'endswith': new_query = field.endswith(value)
else: raise RuntimeError, "Invalid operation"
else: raise RuntimeError, "Invalid operation"
if neg: new_query = ~new_query
if query is None:
query = new_query
elif logic == 'and':
query &= new_query
elif logic == 'or':
query |= new_query
field = op = neg = logic = None
return query
class DAL(dict):
"""
an instance of this class represents a database connection
Example::
db = DAL('sqlite://test.db')
db.define_table('tablename', Field('fieldname1'),
Field('fieldname2'))
"""
@staticmethod
def set_folder(folder):
"""
# ## this allows gluon to set a folder for this thread
# ## <<<<<<<<< Should go away as new DAL replaces old sql.py
"""
BaseAdapter.set_folder(folder)
@staticmethod
def distributed_transaction_begin(*instances):
if not instances:
return
thread_key = '%s.%s' % (socket.gethostname(), threading.currentThread())
keys = ['%s.%i' % (thread_key, i) for (i,db) in instances]
instances = enumerate(instances)
for (i, db) in instances:
if not db._adapter.support_distributed_transaction():
raise SyntaxError, \
'distributed transaction not suported by %s' % db._dbname
for (i, db) in instances:
db._adapter.distributed_transaction_begin(keys[i])
@staticmethod
def distributed_transaction_commit(*instances):
if not instances:
return
instances = enumerate(instances)
thread_key = '%s.%s' % (socket.gethostname(), threading.currentThread())
keys = ['%s.%i' % (thread_key, i) for (i,db) in instances]
for (i, db) in instances:
if not db._adapter.support_distributed_transaction():
raise SyntaxError, \
'distributed transaction not suported by %s' % db._dbanme
try:
for (i, db) in instances:
db._adapter.prepare(keys[i])
except:
for (i, db) in instances:
db._adapter.rollback_prepared(keys[i])
raise RuntimeError, 'failure to commit distributed transaction'
else:
for (i, db) in instances:
db._adapter.commit_prepared(keys[i])
return
def __init__(self, uri='sqlite://dummy.db',
pool_size=0, folder=None,
db_codec='UTF-8', check_reserved=None,
migrate=True, fake_migrate=False,
migrate_enabled=True, fake_migrate_all=False,
decode_credentials=False, driver_args=None,
adapter_args=None, attempts=5, auto_import=False):
"""
Creates a new Database Abstraction Layer instance.
Keyword arguments:
:uri: string that contains information for connecting to a database.
(default: 'sqlite://dummy.db')
:pool_size: How many open connections to make to the database object.
:folder: <please update me>
:db_codec: string encoding of the database (default: 'UTF-8')
:check_reserved: list of adapters to check tablenames and column names
against sql reserved keywords. (Default None)
* 'common' List of sql keywords that are common to all database types
such as "SELECT, INSERT". (recommended)
* 'all' Checks against all known SQL keywords. (not recommended)
<adaptername> Checks against the specific adapters list of keywords
(recommended)
* '<adaptername>_nonreserved' Checks against the specific adapters
list of nonreserved keywords. (if available)
:migrate (defaults to True) sets default migrate behavior for all tables
:fake_migrate (defaults to False) sets default fake_migrate behavior for all tables
:migrate_enabled (defaults to True). If set to False disables ALL migrations
:fake_migrate_all (defaults to False). If sets to True fake migrates ALL tables
:attempts (defaults to 5). Number of times to attempt connecting
"""
if not decode_credentials:
credential_decoder = lambda cred: cred
else:
credential_decoder = lambda cred: urllib.unquote(cred)
if folder:
self.set_folder(folder)
self._uri = uri
self._pool_size = pool_size
self._db_codec = db_codec
self._lastsql = ''
self._timings = []
self._pending_references = {}
self._request_tenant = 'request_tenant'
self._common_fields = []
self._referee_name = '%(table)s'
if not str(attempts).isdigit() or attempts < 0:
attempts = 5
if uri:
uris = isinstance(uri,(list,tuple)) and uri or [uri]
error = ''
connected = False
for k in range(attempts):
for uri in uris:
try:
if is_jdbc and not uri.startswith('jdbc:'):
uri = 'jdbc:'+uri
self._dbname = regex_dbname.match(uri).group()
if not self._dbname in ADAPTERS:
raise SyntaxError, "Error in URI '%s' or database not supported" % self._dbname
# notice that driver args or {} else driver_args
# defaults to {} global, not correct
args = (self,uri,pool_size,folder,
db_codec, credential_decoder,
driver_args or {}, adapter_args or {})
self._adapter = ADAPTERS[self._dbname](*args)
connected = True
break
except SyntaxError:
raise
except Exception, error:
tb = traceback.format_exc()
sys.stderr.write('DEBUG: connect attempt %i, connection error:\n%s' % (k, tb))
if connected:
break
else:
time.sleep(1)
if not connected:
raise RuntimeError, "Failure to connect, tried %d times:\n%s" % (attempts, tb)
else:
args = (self,'None',0,folder,db_codec)
self._adapter = BaseAdapter(*args)
migrate = fake_migrate = False
adapter = self._adapter
self._uri_hash = hashlib.md5(adapter.uri).hexdigest()
self._tables = SQLCallableList()
self.check_reserved = check_reserved
if self.check_reserved:
from reserved_sql_keywords import ADAPTERS as RSK
self.RSK = RSK
self._migrate = migrate
self._fake_migrate = fake_migrate
self._migrate_enabled = migrate_enabled
self._fake_migrate_all = fake_migrate_all
if auto_import:
self.import_table_definitions(adapter.folder)
@property
def tables(self):
return self._tables
def import_table_definitions(self,path,migrate=False,fake_migrate=False):
pattern = os.path.join(path,self._uri_hash+'_*.table')
for filename in glob.glob(pattern):
tfile = self._adapter.file_open(filename, 'r')
try:
sql_fields = cPickle.load(tfile)
name = filename[len(pattern)-7:-6]
mf = [(value['sortable'],Field(key,type=value['type'])) \
for key, value in sql_fields.items()]
mf.sort(lambda a,b: cmp(a[0],b[0]))
self.define_table(name,*[item[1] for item in mf],
**dict(migrate=migrate,fake_migrate=fake_migrate))
finally:
self._adapter.file_close(tfile)
def check_reserved_keyword(self, name):
"""
Validates ``name`` against SQL keywords
Uses self.check_reserve which is a list of
operators to use.
self.check_reserved
['common', 'postgres', 'mysql']
self.check_reserved
['all']
"""
for backend in self.check_reserved:
if name.upper() in self.RSK[backend]:
raise SyntaxError, 'invalid table/column name "%s" is a "%s" reserved SQL keyword' % (name, backend.upper())
def __contains__(self, tablename):
if self.has_key(tablename):
return True
else:
return False
def parse_as_rest(self,patterns,args,vars,queries=None,nested_select=True):
"""
EXAMPLE:
db.define_table('person',Field('name'),Field('info'))
db.define_table('pet',Field('owner',db.person),Field('name'),Field('info'))
@request.restful()
def index():
def GET(*args,**vars):
patterns = [
"/friends[person]",
"/{friend.name.startswith}",
"/{friend.name}/:field",
"/{friend.name}/pets[pet.owner]",
"/{friend.name}/pet[pet.owner]/{pet.name}",
"/{friend.name}/pet[pet.owner]/{pet.name}/:field"
]
parser = db.parse_as_rest(patterns,args,vars)
if parser.status == 200:
return dict(content=parser.response)
else:
raise HTTP(parser.status,parser.error)
def POST(table_name,**vars):
if table_name == 'person':
return db.person.validate_and_insert(**vars)
elif table_name == 'pet':
return db.pet.validate_and_insert(**vars)
else:
raise HTTP(400)
return locals()
"""
db = self
re1 = re.compile('^{[^\.]+\.[^\.]+(\.(lt|gt|le|ge|eq|ne|contains|startswith|year|month|day|hour|minute|second))?(\.not)?}$')
re2 = re.compile('^.+\[.+\]$')
def auto_table(table,base='',depth=0):
patterns = []
for field in db[table].fields:
if base:
tag = '%s/%s' % (base,field.replace('_','-'))
else:
tag = '/%s/%s' % (table.replace('_','-'),field.replace('_','-'))
f = db[table][field]
if not f.readable: continue
if f.type=='id' or 'slug' in field or f.type.startswith('reference'):
tag += '/{%s.%s}' % (table,field)
patterns.append(tag)
patterns.append(tag+'/:field')
elif f.type.startswith('boolean'):
tag += '/{%s.%s}' % (table,field)
patterns.append(tag)
patterns.append(tag+'/:field')
elif f.type.startswith('double') or f.type.startswith('integer'):
tag += '/{%s.%s.ge}/{%s.%s.lt}' % (table,field,table,field)
patterns.append(tag)
patterns.append(tag+'/:field')
elif f.type.startswith('list:'):
tag += '/{%s.%s.contains}' % (table,field)
patterns.append(tag)
patterns.append(tag+'/:field')
elif f.type in ('date','datetime'):
tag+= '/{%s.%s.year}' % (table,field)
patterns.append(tag)
patterns.append(tag+'/:field')
tag+='/{%s.%s.month}' % (table,field)
patterns.append(tag)
patterns.append(tag+'/:field')
tag+='/{%s.%s.day}' % (table,field)
patterns.append(tag)
patterns.append(tag+'/:field')
if f.type in ('datetime','time'):
tag+= '/{%s.%s.hour}' % (table,field)
patterns.append(tag)
patterns.append(tag+'/:field')
tag+='/{%s.%s.minute}' % (table,field)
patterns.append(tag)
patterns.append(tag+'/:field')
tag+='/{%s.%s.second}' % (table,field)
patterns.append(tag)
patterns.append(tag+'/:field')
if depth>0:
for rtable,rfield in db[table]._referenced_by:
tag+='/%s[%s.%s]' % (rtable,rtable,rfield)
patterns.append(tag)
patterns += auto_table(rtable,base=tag,depth=depth-1)
return patterns
if patterns=='auto':
patterns=[]
for table in db.tables:
if not table.startswith('auth_'):
patterns.append('/%s[%s]' % (table,table))
patterns += auto_table(table,base='',depth=1)
else:
i = 0
while i<len(patterns):
pattern = patterns[i]
tokens = pattern.split('/')
if tokens[-1].startswith(':auto') and re2.match(tokens[-1]):
new_patterns = auto_table(tokens[-1][tokens[-1].find('[')+1:-1],
'/'.join(tokens[:-1]))
patterns = patterns[:i]+new_patterns+patterns[i+1:]
i += len(new_patterns)
else:
i += 1
if '/'.join(args) == 'patterns':
return Row({'status':200,'pattern':'list',
'error':None,'response':patterns})
for pattern in patterns:
otable=table=None
if not isinstance(queries,dict):
dbset=db(queries)
i=0
tags = pattern[1:].split('/')
if len(tags)!=len(args):
continue
for tag in tags:
if re1.match(tag):
# print 're1:'+tag
tokens = tag[1:-1].split('.')
table, field = tokens[0], tokens[1]
if not otable or table == otable:
if len(tokens)==2 or tokens[2]=='eq':
query = db[table][field]==args[i]
elif tokens[2]=='ne':
query = db[table][field]!=args[i]
elif tokens[2]=='lt':
query = db[table][field]<args[i]
elif tokens[2]=='gt':
query = db[table][field]>args[i]
elif tokens[2]=='ge':
query = db[table][field]>=args[i]
elif tokens[2]=='le':
query = db[table][field]<=args[i]
elif tokens[2]=='year':
query = db[table][field].year()==args[i]
elif tokens[2]=='month':
query = db[table][field].month()==args[i]
elif tokens[2]=='day':
query = db[table][field].day()==args[i]
elif tokens[2]=='hour':
query = db[table][field].hour()==args[i]
elif tokens[2]=='minute':
query = db[table][field].minutes()==args[i]
elif tokens[2]=='second':
query = db[table][field].seconds()==args[i]
elif tokens[2]=='startswith':
query = db[table][field].startswith(args[i])
elif tokens[2]=='contains':
query = db[table][field].contains(args[i])
else:
raise RuntimeError, "invalid pattern: %s" % pattern
if len(tokens)==4 and tokens[3]=='not':
query = ~query
elif len(tokens)>=4:
raise RuntimeError, "invalid pattern: %s" % pattern
if not otable and isinstance(queries,dict):
dbset = db(queries[table])
dbset=dbset(query)
else:
raise RuntimeError, "missing relation in pattern: %s" % pattern
elif re2.match(tag) and args[i]==tag[:tag.find('[')]:
ref = tag[tag.find('[')+1:-1]
if '.' in ref and otable:
table,field = ref.split('.')
# print table,field
if nested_select:
try:
dbset=db(db[table][field].belongs(dbset._select(db[otable]._id)))
except ValueError:
return Row({'status':400,'pattern':pattern,
'error':'invalid path','response':None})
else:
items = [item.id for item in dbset.select(db[otable]._id)]
dbset=db(db[table][field].belongs(items))
else:
table = ref
if not otable and isinstance(queries,dict):
dbset = db(queries[table])
dbset=dbset(db[table])
elif tag==':field' and table:
# # print 're3:'+tag
field = args[i]
if not field in db[table]: break
try:
item = dbset.select(db[table][field],limitby=(0,1)).first()
except ValueError:
return Row({'status':400,'pattern':pattern,
'error':'invalid path','response':None})
if not item:
return Row({'status':404,'pattern':pattern,
'error':'record not found','response':None})
else:
return Row({'status':200,'response':item[field],
'pattern':pattern})
elif tag != args[i]:
break
otable = table
i += 1
if i==len(tags) and table:
ofields = vars.get('order',db[table]._id.name).split('|')
try:
orderby = [db[table][f] if not f.startswith('~') else ~db[table][f[1:]] for f in ofields]
except KeyError:
return Row({'status':400,'error':'invalid orderby','response':None})
fields = [field for field in db[table] if field.readable]
count = dbset.count()
try:
offset = int(vars.get('offset',None) or 0)
limits = (offset,int(vars.get('limit',None) or 1000)+offset)
except ValueError:
Row({'status':400,'error':'invalid limits','response':None})
if count > limits[1]-limits[0]:
Row({'status':400,'error':'too many records','response':None})
try:
response = dbset.select(limitby=limits,orderby=orderby,*fields)
except ValueError:
return Row({'status':400,'pattern':pattern,
'error':'invalid path','response':None})
return Row({'status':200,'response':response,'pattern':pattern})
return Row({'status':400,'error':'no matching pattern','response':None})
def define_table(
self,
tablename,
*fields,
**args
):
for key in args:
if key not in [
'migrate',
'primarykey',
'fake_migrate',
'format',
'singular',
'plural',
'trigger_name',
'sequence_name',
'common_filter',
'polymodel',
'table_class']:
raise SyntaxError, 'invalid table "%s" attribute: %s' \
% (tablename, key)
if not isinstance(tablename,str):
raise SyntaxError, "missing table name"
tablename = cleanup(tablename)
migrate = self._migrate_enabled and args.get('migrate',
self._migrate)
fake_migrate = self._fake_migrate_all or args.get('fake_migrate',
self._fake_migrate)
table_class = args.get('table_class',Table)
format = args.get('format',None)
trigger_name = args.get('trigger_name', None)
sequence_name = args.get('sequence_name', None)
primarykey =args.get('primarykey',None)
polymodel = args.get('polymodel',None)
singular = args.get('singular',tablename.replace('_',' ').capitalize())
plural = args.get('plural',pluralize(singular.lower()).capitalize())
lowertablename = tablename.lower()
if tablename.startswith('_') or hasattr(self,lowertablename) or \
regex_python_keywords.match(tablename):
raise SyntaxError, 'invalid table name: %s' % tablename
elif lowertablename in self.tables:
raise SyntaxError, 'table already defined: %s' % tablename
elif self.check_reserved:
self.check_reserved_keyword(tablename)
if self._common_fields:
fields = [f for f in fields] + [f for f in self._common_fields]
common_filter = args.get('common_filter', None)
t = self[tablename] = table_class(self, tablename, *fields,
**dict(primarykey=primarykey,
trigger_name=trigger_name,
sequence_name=sequence_name,
common_filter=common_filter))
# db magic
if self._uri in (None,'None'):
return t
t._create_references()
if migrate or self._adapter.dbengine=='google:datastore':
try:
sql_locker.acquire()
self._adapter.create_table(t,migrate=migrate,
fake_migrate=fake_migrate,
polymodel=polymodel)
finally:
sql_locker.release()
else:
t._dbt = None
self.tables.append(tablename)
t._format = format
t._singular = singular
t._plural = plural
t._actual = True
return t
def __iter__(self):
for tablename in self.tables:
yield self[tablename]
def __getitem__(self, key):
return dict.__getitem__(self, str(key))
def __setitem__(self, key, value):
dict.__setitem__(self, str(key), value)
def __getattr__(self, key):
return self[key]
def __setattr__(self, key, value):
if key[:1]!='_' and key in self:
raise SyntaxError, \
'Object %s exists and cannot be redefined' % key
self[key] = value
def __repr__(self):
return '<DAL ' + dict.__repr__(self) + '>'
def smart_query(self,fields,text):
return Set(self, smart_query(fields,text))
def __call__(self, query=None, ignore_common_filters=None):
if isinstance(query,Table):
query = query._id>0
elif isinstance(query,Field):
query = query!=None
return Set(self, query, ignore_common_filters=ignore_common_filters)
def commit(self):
self._adapter.commit()
def rollback(self):
self._adapter.rollback()
def executesql(self, query, placeholders=None, as_dict=False):
"""
placeholders is optional and will always be None when using DAL.
If using raw SQL with placeholders, placeholders may be
a sequence of values to be substituted in
or, (if supported by the DB driver), a dictionary with keys
matching named placeholders in your SQL.
Added 2009-12-05 "as_dict" optional argument. Will always be
None when using DAL. If using raw SQL can be set to True
and the results cursor returned by the DB driver will be
converted to a sequence of dictionaries keyed with the db
field names. Tested with SQLite but should work with any database
since the cursor.description used to get field names is part of the
Python dbi 2.0 specs. Results returned with as_dict=True are
the same as those returned when applying .to_list() to a DAL query.
[{field1: value1, field2: value2}, {field1: value1b, field2: value2b}]
--bmeredyk
"""
if placeholders:
self._adapter.execute(query, placeholders)
else:
self._adapter.execute(query)
if as_dict:
if not hasattr(self._adapter.cursor,'description'):
raise RuntimeError, "database does not support executesql(...,as_dict=True)"
# Non-DAL legacy db query, converts cursor results to dict.
# sequence of 7-item sequences. each sequence tells about a column.
# first item is always the field name according to Python Database API specs
columns = self._adapter.cursor.description
# reduce the column info down to just the field names
fields = [f[0] for f in columns]
# will hold our finished resultset in a list
data = self._adapter.cursor.fetchall()
# convert the list for each row into a dictionary so it's
# easier to work with. row['field_name'] rather than row[0]
return [dict(zip(fields,row)) for row in data]
# see if any results returned from database
try:
return self._adapter.cursor.fetchall()
except:
return None
def _update_referenced_by(self, other):
for tablename in self.tables:
by = self[tablename]._referenced_by
by[:] = [item for item in by if not item[0] == other]
def export_to_csv_file(self, ofile, *args, **kwargs):
step = int(kwargs.get('max_fetch_rows,',500))
write_colnames = kwargs['write_colnames'] = \
kwargs.get("write_colnames", True)
for table in self.tables:
ofile.write('TABLE %s\r\n' % table)
query = self[table]._id > 0
nrows = self(query).count()
kwargs['write_colnames'] = write_colnames
for k in range(0,nrows,step):
self(query).select(limitby=(k,k+step)).export_to_csv_file(
ofile, *args, **kwargs)
kwargs['write_colnames'] = False
ofile.write('\r\n\r\n')
ofile.write('END')
def import_from_csv_file(self, ifile, id_map=None, null='<NULL>',
unique='uuid', *args, **kwargs):
if id_map is None: id_map={}
for line in ifile:
line = line.strip()
if not line:
continue
elif line == 'END':
return
elif not line.startswith('TABLE ') or not line[6:] in self.tables:
raise SyntaxError, 'invalid file format'
else:
tablename = line[6:]
self[tablename].import_from_csv_file(ifile, id_map, null,
unique, *args, **kwargs)
class SQLALL(object):
"""
Helper class providing a comma-separated string having all the field names
(prefixed by table name and '.')
normally only called from within gluon.sql
"""
def __init__(self, table):
self.table = table
def __str__(self):
return ', '.join([str(field) for field in self.table])
class Reference(int):
def __allocate(self):
if not self._record:
self._record = self._table[int(self)]
if not self._record:
raise RuntimeError, "Using a recursive select but encountered a broken reference: %s %d"%(self._table, int(self))
def __getattr__(self, key):
if key == 'id':
return int(self)
self.__allocate()
return self._record.get(key, None)
def get(self, key):
return self.__getattr__(key)
def __setattr__(self, key, value):
if key.startswith('_'):
int.__setattr__(self, key, value)
return
self.__allocate()
self._record[key] = value
def __getitem__(self, key):
if key == 'id':
return int(self)
self.__allocate()
return self._record.get(key, None)
def __setitem__(self,key,value):
self.__allocate()
self._record[key] = value
def Reference_unpickler(data):
return marshal.loads(data)
def Reference_pickler(data):
try:
marshal_dump = marshal.dumps(int(data))
except AttributeError:
marshal_dump = 'i%s' % struct.pack('<i', int(data))
return (Reference_unpickler, (marshal_dump,))
copy_reg.pickle(Reference, Reference_pickler, Reference_unpickler)
class Table(dict):
"""
an instance of this class represents a database table
Example::
db = DAL(...)
db.define_table('users', Field('name'))
db.users.insert(name='me') # print db.users._insert(...) to see SQL
db.users.drop()
"""
def __init__(
self,
db,
tablename,
*fields,
**args
):
"""
Initializes the table and performs checking on the provided fields.
Each table will have automatically an 'id'.
If a field is of type Table, the fields (excluding 'id') from that table
will be used instead.
:raises SyntaxError: when a supplied field is of incorrect type.
"""
self._actual = False # set to True by define_table()
self._tablename = tablename
self._sequence_name = args.get('sequence_name',None) or \
db and db._adapter.sequence_name(tablename)
self._trigger_name = args.get('trigger_name',None) or \
db and db._adapter.trigger_name(tablename)
self._common_filter = args.get('common_filter', None)
primarykey = args.get('primarykey', None)
fieldnames,newfields=set(),[]
if primarykey:
if not isinstance(primarykey,list):
raise SyntaxError, \
"primarykey must be a list of fields from table '%s'" \
% tablename
self._primarykey = primarykey
elif not [f for f in fields if isinstance(f,Field) and f.type=='id']:
field = Field('id', 'id')
newfields.append(field)
fieldnames.add('id')
self._id = field
for field in fields:
if not isinstance(field, (Field, Table)):
raise SyntaxError, \
'define_table argument is not a Field or Table: %s' % field
elif isinstance(field, Field) and not field.name in fieldnames:
if hasattr(field, '_db'):
field = copy.copy(field)
newfields.append(field)
fieldnames.add(field.name)
if field.type=='id':
self._id = field
elif isinstance(field, Table):
table = field
for field in table:
if not field.name in fieldnames and not field.type=='id':
field = copy.copy(field)
# correct self references
if not table._actual and field.type == 'reference '+table._tablename:
field.type = 'reference '+self._tablename
newfields.append(field)
fieldnames.add(field.name)
else:
# let's ignore new fields with duplicated names!!!
pass
fields = newfields
self._db = db
tablename = tablename
self._fields = SQLCallableList()
self.virtualfields = []
fields = list(fields)
if db and self._db._adapter.uploads_in_blob==True:
for field in fields:
if isinstance(field, Field) and field.type == 'upload'\
and field.uploadfield is True:
tmp = field.uploadfield = '%s_blob' % field.name
fields.append(self._db.Field(tmp, 'blob', default=''))
lower_fieldnames = set()
reserved = dir(Table) + ['fields']
for field in fields:
if db and db.check_reserved:
db.check_reserved_keyword(field.name)
elif field.name in reserved:
raise SyntaxError, "field name %s not allowed" % field.name
if field.name.lower() in lower_fieldnames:
raise SyntaxError, "duplicate field %s in table %s" \
% (field.name, tablename)
else:
lower_fieldnames.add(field.name.lower())
self.fields.append(field.name)
self[field.name] = field
if field.type == 'id':
self['id'] = field
field.tablename = field._tablename = tablename
field.table = field._table = self
field.db = field._db = self._db
if self._db and not field.type in ('text','blob') and \
self._db._adapter.maxcharlength < field.length:
field.length = self._db._adapter.maxcharlength
if field.requires is DEFAULT:
field.requires = sqlhtml_validators(field)
self.ALL = SQLALL(self)
if hasattr(self,'_primarykey'):
for k in self._primarykey:
if k not in self.fields:
raise SyntaxError, \
"primarykey must be a list of fields from table '%s " % tablename
else:
self[k].notnull = True
@property
def fields(self):
return self._fields
def update(self,*args,**kwargs):
raise RuntimeError, "Syntax Not Supported"
def _validate(self,**vars):
errors = Row()
for key,value in vars.items():
value,error = self[key].validate(value)
if error:
errors[key] = error
return errors
def _create_references(self):
pr = self._db._pending_references
self._referenced_by = []
for fieldname in self.fields:
field=self[fieldname]
if isinstance(field.type,str) and field.type[:10] == 'reference ':
ref = field.type[10:].strip()
if not ref.split():
raise SyntaxError, 'Table: reference to nothing: %s' %ref
refs = ref.split('.')
rtablename = refs[0]
if not rtablename in self._db:
pr[rtablename] = pr.get(rtablename,[]) + [field]
continue
rtable = self._db[rtablename]
if len(refs)==2:
rfieldname = refs[1]
if not hasattr(rtable,'_primarykey'):
raise SyntaxError,\
'keyed tables can only reference other keyed tables (for now)'
if rfieldname not in rtable.fields:
raise SyntaxError,\
"invalid field '%s' for referenced table '%s' in table '%s'" \
% (rfieldname, rtablename, self._tablename)
rtable._referenced_by.append((self._tablename, field.name))
for referee in pr.get(self._tablename,[]):
self._referenced_by.append((referee._tablename,referee.name))
def _filter_fields(self, record, id=False):
return dict([(k, v) for (k, v) in record.items() if k
in self.fields and (self[k].type!='id' or id)])
def _build_query(self,key):
""" for keyed table only """
query = None
for k,v in key.iteritems():
if k in self._primarykey:
if query:
query = query & (self[k] == v)
else:
query = (self[k] == v)
else:
raise SyntaxError, \
'Field %s is not part of the primary key of %s' % \
(k,self._tablename)
return query
def __getitem__(self, key):
if not key:
return None
elif isinstance(key, dict):
""" for keyed table """
query = self._build_query(key)
rows = self._db(query).select()
if rows:
return rows[0]
return None
elif str(key).isdigit():
return self._db(self._id == key).select(limitby=(0,1)).first()
elif key:
return dict.__getitem__(self, str(key))
def __call__(self, key=DEFAULT, **kwargs):
for_update = kwargs.get('_for_update',False)
if '_for_update' in kwargs: del kwargs['_for_update']
if not key is DEFAULT:
if isinstance(key, Query):
record = self._db(key).select(
limitby=(0,1),for_update=for_update).first()
elif not str(key).isdigit():
record = None
else:
record = self._db(self._id == key).select(
limitby=(0,1),for_update=for_update).first()
if record:
for k,v in kwargs.items():
if record[k]!=v: return None
return record
elif kwargs:
query = reduce(lambda a,b:a&b,[self[k]==v for k,v in kwargs.items()])
return self._db(query).select(limitby=(0,1),for_update=for_update).first()
else:
return None
def __setitem__(self, key, value):
if isinstance(key, dict) and isinstance(value, dict):
""" option for keyed table """
if set(key.keys()) == set(self._primarykey):
value = self._filter_fields(value)
kv = {}
kv.update(value)
kv.update(key)
if not self.insert(**kv):
query = self._build_query(key)
self._db(query).update(**self._filter_fields(value))
else:
raise SyntaxError,\
'key must have all fields from primary key: %s'%\
(self._primarykey)
elif str(key).isdigit():
if key == 0:
self.insert(**self._filter_fields(value))
elif self._db(self._id == key)\
.update(**self._filter_fields(value)) is None:
raise SyntaxError, 'No such record: %s' % key
else:
if isinstance(key, dict):
raise SyntaxError,\
'value must be a dictionary: %s' % value
dict.__setitem__(self, str(key), value)
def __delitem__(self, key):
if isinstance(key, dict):
query = self._build_query(key)
if not self._db(query).delete():
raise SyntaxError, 'No such record: %s' % key
elif not str(key).isdigit() or not self._db(self._id == key).delete():
raise SyntaxError, 'No such record: %s' % key
def __getattr__(self, key):
return self[key]
def __setattr__(self, key, value):
if key[:1]!='_' and key in self:
raise SyntaxError, 'Object exists and cannot be redefined: %s' % key
self[key] = value
def __iter__(self):
for fieldname in self.fields:
yield self[fieldname]
def __repr__(self):
return '<Table ' + dict.__repr__(self) + '>'
def __str__(self):
if self.get('_ot', None):
return '%s AS %s' % (self._ot, self._tablename)
return self._tablename
def _drop(self, mode = ''):
return self._db._adapter._drop(self, mode)
def drop(self, mode = ''):
return self._db._adapter.drop(self,mode)
def _listify(self,fields,update=False):
new_fields = []
new_fields_names = []
for name in fields:
if not name in self.fields:
if name != 'id':
raise SyntaxError, 'Field %s does not belong to the table' % name
else:
new_fields.append((self[name],fields[name]))
new_fields_names.append(name)
for ofield in self:
if not ofield.name in new_fields_names:
if not update and not ofield.default is None:
new_fields.append((ofield,ofield.default))
elif update and not ofield.update is None:
new_fields.append((ofield,ofield.update))
for ofield in self:
if not ofield.name in new_fields_names and ofield.compute:
try:
new_fields.append((ofield,ofield.compute(Row(fields))))
except KeyError:
pass
if not update and ofield.required and not ofield.name in new_fields_names:
raise SyntaxError,'Table: missing required field: %s' % ofield.name
return new_fields
def _insert(self, **fields):
return self._db._adapter._insert(self,self._listify(fields))
def insert(self, **fields):
return self._db._adapter.insert(self,self._listify(fields))
def validate_and_insert(self,**fields):
response = Row()
response.errors = Row()
new_fields = copy.copy(fields)
for key,value in fields.items():
value,error = self[key].validate(value)
if error:
response.errors[key] = error
else:
new_fields[key] = value
if not response.errors:
response.id = self.insert(**new_fields)
else:
response.id = None
return response
def update_or_insert(self, _key=DEFAULT, **values):
if _key is DEFAULT:
record = self(**values)
else:
record = self(_key)
if record:
record.update_record(**values)
newid = None
else:
newid = self.insert(**values)
return newid
def bulk_insert(self, items):
"""
here items is a list of dictionaries
"""
items = [self._listify(item) for item in items]
return self._db._adapter.bulk_insert(self,items)
def _truncate(self, mode = None):
return self._db._adapter._truncate(self, mode)
def truncate(self, mode = None):
return self._db._adapter.truncate(self, mode)
def import_from_csv_file(
self,
csvfile,
id_map=None,
null='<NULL>',
unique='uuid',
*args, **kwargs
):
"""
import records from csv file. Column headers must have same names as
table fields. field 'id' is ignored. If column names read 'table.file'
the 'table.' prefix is ignored.
'unique' argument is a field which must be unique
(typically a uuid field)
"""
delimiter = kwargs.get('delimiter', ',')
quotechar = kwargs.get('quotechar', '"')
quoting = kwargs.get('quoting', csv.QUOTE_MINIMAL)
reader = csv.reader(csvfile, delimiter=delimiter, quotechar=quotechar, quoting=quoting)
colnames = None
if isinstance(id_map, dict):
if not self._tablename in id_map:
id_map[self._tablename] = {}
id_map_self = id_map[self._tablename]
def fix(field, value, id_map):
list_reference_s='list:reference'
if value == null:
value = None
elif field.type=='blob':
value = base64.b64decode(value)
elif field.type=='double':
if not value.strip():
value = None
else:
value = float(value)
elif field.type=='integer':
if not value.strip():
value = None
else:
value = int(value)
elif field.type.startswith('list:string'):
value = bar_decode_string(value)
elif field.type.startswith(list_reference_s):
ref_table = field.type[len(list_reference_s):].strip()
value = [id_map[ref_table][int(v)] \
for v in bar_decode_string(value)]
elif field.type.startswith('list:'):
value = bar_decode_integer(value)
elif id_map and field.type.startswith('reference'):
try:
value = id_map[field.type[9:].strip()][int(value)]
except KeyError:
pass
return (field.name, value)
def is_id(colname):
if colname in self:
return self[colname].type == 'id'
else:
return False
for line in reader:
if not line:
break
if not colnames:
colnames = [x.split('.',1)[-1] for x in line][:len(line)]
cols, cid = [], []
for i,colname in enumerate(colnames):
if is_id(colname):
cid = i
else:
cols.append(i)
if colname == unique:
unique_idx = i
else:
items = [fix(self[colnames[i]], line[i], id_map) \
for i in cols if colnames[i] in self.fields]
# Validation. Check for duplicate of 'unique' &,
# if present, update instead of insert.
if not unique or unique not in colnames:
new_id = self.insert(**dict(items))
else:
unique_value = line[unique_idx]
query = self._db[self][unique] == unique_value
record = self._db(query).select().first()
if record:
record.update_record(**dict(items))
new_id = record[self._id.name]
else:
new_id = self.insert(**dict(items))
if id_map and cid != []:
id_map_self[int(line[cid])] = new_id
def with_alias(self, alias):
return self._db._adapter.alias(self,alias)
def on(self, query):
return Expression(self._db,self._db._adapter.ON,self,query)
class Expression(object):
def __init__(
self,
db,
op,
first=None,
second=None,
type=None,
):
self.db = db
self.op = op
self.first = first
self.second = second
### self._tablename = first._tablename ## CHECK
if not type and first and hasattr(first,'type'):
self.type = first.type
else:
self.type = type
def sum(self):
return Expression(self.db, self.db._adapter.AGGREGATE, self, 'SUM', self.type)
def max(self):
return Expression(self.db, self.db._adapter.AGGREGATE, self, 'MAX', self.type)
def min(self):
return Expression(self.db, self.db._adapter.AGGREGATE, self, 'MIN', self.type)
def len(self):
return Expression(self.db, self.db._adapter.AGGREGATE, self, 'LENGTH', 'integer')
def lower(self):
return Expression(self.db, self.db._adapter.LOWER, self, None, self.type)
def upper(self):
return Expression(self.db, self.db._adapter.UPPER, self, None, self.type)
def year(self):
return Expression(self.db, self.db._adapter.EXTRACT, self, 'year', 'integer')
def month(self):
return Expression(self.db, self.db._adapter.EXTRACT, self, 'month', 'integer')
def day(self):
return Expression(self.db, self.db._adapter.EXTRACT, self, 'day', 'integer')
def hour(self):
return Expression(self.db, self.db._adapter.EXTRACT, self, 'hour', 'integer')
def minutes(self):
return Expression(self.db, self.db._adapter.EXTRACT, self, 'minute', 'integer')
def coalesce(self,*others):
return Expression(self.db, self.db._adapter.COALESCE, self, others, self.type)
def coalesce_zero(self):
return Expression(self.db, self.db._adapter.COALESCE_ZERO, self, None, self.type)
def seconds(self):
return Expression(self.db, self.db._adapter.EXTRACT, self, 'second', 'integer')
def __getslice__(self, start, stop):
if start < 0:
pos0 = '(%s - %d)' % (self.len(), abs(start) - 1)
else:
pos0 = start + 1
if stop < 0:
length = '(%s - %d - %s)' % (self.len(), abs(stop) - 1, pos0)
elif stop == sys.maxint:
length = self.len()
else:
length = '(%s - %s)' % (stop + 1, pos0)
return Expression(self.db,self.db._adapter.SUBSTRING,
self, (pos0, length), self.type)
def __getitem__(self, i):
return self[i:i + 1]
def __str__(self):
return self.db._adapter.expand(self,self.type)
def __or__(self, other): # for use in sortby
return Expression(self.db,self.db._adapter.COMMA,self,other,self.type)
def __invert__(self):
if hasattr(self,'_op') and self.op == self.db._adapter.INVERT:
return self.first
return Expression(self.db,self.db._adapter.INVERT,self,type=self.type)
def __add__(self, other):
return Expression(self.db,self.db._adapter.ADD,self,other,self.type)
def __sub__(self, other):
if self.type == 'integer':
result_type = 'integer'
elif self.type in ['date','time','datetime','double']:
result_type = 'double'
else:
raise SyntaxError, "subtraction operation not supported for type"
return Expression(self.db,self.db._adapter.SUB,self,other,
result_type)
def __mul__(self, other):
return Expression(self.db,self.db._adapter.MUL,self,other,self.type)
def __div__(self, other):
return Expression(self.db,self.db._adapter.DIV,self,other,self.type)
def __mod__(self, other):
return Expression(self.db,self.db._adapter.MOD,self,other,self.type)
def __eq__(self, value):
return Query(self.db, self.db._adapter.EQ, self, value)
def __ne__(self, value):
return Query(self.db, self.db._adapter.NE, self, value)
def __lt__(self, value):
return Query(self.db, self.db._adapter.LT, self, value)
def __le__(self, value):
return Query(self.db, self.db._adapter.LE, self, value)
def __gt__(self, value):
return Query(self.db, self.db._adapter.GT, self, value)
def __ge__(self, value):
return Query(self.db, self.db._adapter.GE, self, value)
def like(self, value, case_sensitive=False):
op = case_sensitive and self.db._adapter.LIKE or self.db._adapter.ILIKE
return Query(self.db, op, self, value)
def regexp(self, value):
return Query(self.db, self.db._adapter.REGEXP, self, value)
def belongs(self, value):
if isinstance(value,Query):
value = self.db(value)._select(value.first._table._id)
return Query(self.db, self.db._adapter.BELONGS, self, value)
def startswith(self, value):
if not self.type in ('string', 'text'):
raise SyntaxError, "startswith used with incompatible field type"
return Query(self.db, self.db._adapter.STARTSWITH, self, value)
def endswith(self, value):
if not self.type in ('string', 'text'):
raise SyntaxError, "endswith used with incompatible field type"
return Query(self.db, self.db._adapter.ENDSWITH, self, value)
def contains(self, value, all=False):
if isinstance(value,(list, tuple)):
subqueries = [self.contains(str(v).strip()) for v in value if str(v).strip()]
return reduce(all and AND or OR, subqueries)
if not self.type in ('string', 'text') and not self.type.startswith('list:'):
raise SyntaxError, "contains used with incompatible field type"
return Query(self.db, self.db._adapter.CONTAINS, self, value)
def with_alias(self, alias):
return Expression(self.db, self.db._adapter.AS, self, alias, self.type)
# for use in both Query and sortby
class SQLCustomType(object):
"""
allows defining of custom SQL types
Example::
decimal = SQLCustomType(
type ='double',
native ='integer',
encoder =(lambda x: int(float(x) * 100)),
decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) )
)
db.define_table(
'example',
Field('value', type=decimal)
)
:param type: the web2py type (default = 'string')
:param native: the backend type
:param encoder: how to encode the value to store it in the backend
:param decoder: how to decode the value retrieved from the backend
:param validator: what validators to use ( default = None, will use the
default validator for type)
"""
def __init__(
self,
type='string',
native=None,
encoder=None,
decoder=None,
validator=None,
_class=None,
):
self.type = type
self.native = native
self.encoder = encoder or (lambda x: x)
self.decoder = decoder or (lambda x: x)
self.validator = validator
self._class = _class or type
def startswith(self, text=None):
try:
return self.type.startswith(self, text)
except TypeError:
return False
def __getslice__(self, a=0, b=100):
return None
def __getitem__(self, i):
return None
def __str__(self):
return self._class
class FieldVirtual(object):
def __init__(self, f):
self.f = f
class FieldLazy(object):
def __init__(self, f, handler=None):
self.f = f
self.handler = handler
class Field(Expression):
Virtual = FieldVirtual
Lazy = FieldLazy
"""
an instance of this class represents a database field
example::
a = Field(name, 'string', length=32, default=None, required=False,
requires=IS_NOT_EMPTY(), ondelete='CASCADE',
notnull=False, unique=False,
uploadfield=True, widget=None, label=None, comment=None,
uploadfield=True, # True means store on disk,
# 'a_field_name' means store in this field in db
# False means file content will be discarded.
writable=True, readable=True, update=None, authorize=None,
autodelete=False, represent=None, uploadfolder=None,
uploadseparate=False # upload to separate directories by uuid_keys
# first 2 character and tablename.fieldname
# False - old behavior
# True - put uploaded file in
# <uploaddir>/<tablename>.<fieldname>/uuid_key[:2]
# directory)
to be used as argument of DAL.define_table
allowed field types:
string, boolean, integer, double, text, blob,
date, time, datetime, upload, password
strings must have a length of Adapter.maxcharlength by default (512 or 255 for mysql)
fields should have a default or they will be required in SQLFORMs
the requires argument is used to validate the field input in SQLFORMs
"""
def __init__(
self,
fieldname,
type='string',
length=None,
default=DEFAULT,
required=False,
requires=DEFAULT,
ondelete='CASCADE',
notnull=False,
unique=False,
uploadfield=True,
widget=None,
label=DEFAULT,
comment=None,
writable=True,
readable=True,
update=None,
authorize=None,
autodelete=False,
represent=None,
uploadfolder=None,
uploadseparate=False,
compute=None,
custom_store=None,
custom_retrieve=None,
custom_delete=None,
):
self.db = None
self.op = None
self.first = None
self.second = None
if not isinstance(fieldname,str):
raise SyntaxError, "missing field name"
self.name = fieldname = cleanup(fieldname)
if hasattr(Table,fieldname) or fieldname[0] == '_' or \
regex_python_keywords.match(fieldname):
raise SyntaxError, 'Field: invalid field name: %s' % fieldname
if isinstance(type, Table):
type = 'reference ' + type._tablename
self.type = type # 'string', 'integer'
self.length = (length is None) and DEFAULTLENGTH.get(type,512) or length
if default is DEFAULT:
self.default = update or None
else:
self.default = default
self.required = required # is this field required
self.ondelete = ondelete.upper() # this is for reference fields only
self.notnull = notnull
self.unique = unique
self.uploadfield = uploadfield
self.uploadfolder = uploadfolder
self.uploadseparate = uploadseparate
self.widget = widget
if label is DEFAULT:
self.label = fieldname.replace('_', ' ').title()
else:
self.label = label or ''
self.comment = comment
self.writable = writable
self.readable = readable
self.update = update
self.authorize = authorize
self.autodelete = autodelete
if not represent and type in ('list:integer','list:string'):
represent=lambda x,r=None: ', '.join(str(y) for y in x or [])
self.represent = represent
self.compute = compute
self.isattachment = True
self.custom_store = custom_store
self.custom_retrieve = custom_retrieve
self.custom_delete = custom_delete
if self.label is None:
self.label = fieldname.replace('_',' ').title()
if requires is None:
self.requires = []
else:
self.requires = requires
def store(self, file, filename=None, path=None):
if self.custom_store:
return self.custom_store(file,filename,path)
if isinstance(file, cgi.FieldStorage):
file = file.file
filename = filename or file.filename
elif not filename:
filename = file.name
filename = os.path.basename(filename.replace('/', os.sep)\
.replace('\\', os.sep))
m = re.compile('\.(?P<e>\w{1,5})$').search(filename)
extension = m and m.group('e') or 'txt'
uuid_key = web2py_uuid().replace('-', '')[-16:]
encoded_filename = base64.b16encode(filename).lower()
newfilename = '%s.%s.%s.%s' % \
(self._tablename, self.name, uuid_key, encoded_filename)
newfilename = newfilename[:(self.length - 1 - len(extension))] + '.' + extension
if isinstance(self.uploadfield,Field):
blob_uploadfield_name = self.uploadfield.uploadfield
keys={self.uploadfield.name: newfilename,
blob_uploadfield_name: file.read()}
self.uploadfield.table.insert(**keys)
elif self.uploadfield == True:
if path:
pass
elif self.uploadfolder:
path = self.uploadfolder
elif self.db._adapter.folder:
path = os.path.join(self.db._adapter.folder, '..', 'uploads')
else:
raise RuntimeError, "you must specify a Field(...,uploadfolder=...)"
if self.uploadseparate:
path = os.path.join(path,"%s.%s" % (self._tablename, self.name),uuid_key[:2])
if not os.path.exists(path):
os.makedirs(path)
pathfilename = os.path.join(path, newfilename)
dest_file = open(pathfilename, 'wb')
try:
shutil.copyfileobj(file, dest_file)
except IOError:
raise IOError, 'Unable to store file "%s" because invalid permissions, readonly file system, or filename too long' % pathfilename
dest_file.close()
return newfilename
def retrieve(self, name, path=None):
if self.custom_retrieve:
return self.custom_retrieve(name, path)
import http
if self.authorize or isinstance(self.uploadfield, str):
row = self.db(self == name).select().first()
if not row:
raise http.HTTP(404)
if self.authorize and not self.authorize(row):
raise http.HTTP(403)
try:
m = regex_content.match(name)
if not m or not self.isattachment:
raise TypeError, 'Can\'t retrieve %s' % name
filename = base64.b16decode(m.group('name'), True)
filename = regex_cleanup_fn.sub('_', filename)
except (TypeError, AttributeError):
filename = name
if isinstance(self.uploadfield, str): # ## if file is in DB
return (filename, cStringIO.StringIO(row[self.uploadfield] or ''))
elif isinstance(self.uploadfield,Field):
blob_uploadfield_name = self.uploadfield.uploadfield
query = self.uploadfield == name
data = self.uploadfield.table(query)[blob_uploadfield_name]
return (filename, cStringIO.StringIO(data))
else:
# ## if file is on filesystem
if path:
pass
elif self.uploadfolder:
path = self.uploadfolder
else:
path = os.path.join(self.db._adapter.folder, '..', 'uploads')
if self.uploadseparate:
t = m.group('table')
f = m.group('field')
u = m.group('uuidkey')
path = os.path.join(path,"%s.%s" % (t,f),u[:2])
return (filename, open(os.path.join(path, name), 'rb'))
def formatter(self, value):
if value is None or not self.requires:
return value
if not isinstance(self.requires, (list, tuple)):
requires = [self.requires]
elif isinstance(self.requires, tuple):
requires = list(self.requires)
else:
requires = copy.copy(self.requires)
requires.reverse()
for item in requires:
if hasattr(item, 'formatter'):
value = item.formatter(value)
return value
def validate(self, value):
if not self.requires:
return (value, None)
requires = self.requires
if not isinstance(requires, (list, tuple)):
requires = [requires]
for validator in requires:
(value, error) = validator(value)
if error:
return (value, error)
return (value, None)
def count(self):
return Expression(self.db, self.db._adapter.AGGREGATE, self, 'COUNT', 'integer')
def __nonzero__(self):
return True
def __str__(self):
try:
return '%s.%s' % (self.tablename, self.name)
except:
return '<no table>.%s' % self.name
def raw(s): return Expression(None,s)
class Query(object):
"""
a query object necessary to define a set.
it can be stored or can be passed to DAL.__call__() to obtain a Set
Example::
query = db.users.name=='Max'
set = db(query)
records = set.select()
"""
def __init__(
self,
db,
op,
first=None,
second=None,
ignore_common_filters = False,
):
self.db = self._db = db
self.op = op
self.first = first
self.second = second
self.ignore_common_filters = ignore_common_filters
def __str__(self):
return self.db._adapter.expand(self)
def __and__(self, other):
return Query(self.db,self.db._adapter.AND,self,other)
def __or__(self, other):
return Query(self.db,self.db._adapter.OR,self,other)
def __invert__(self):
if self.op==self.db._adapter.NOT:
return self.first
return Query(self.db,self.db._adapter.NOT,self)
regex_quotes = re.compile("'[^']*'")
def xorify(orderby):
if not orderby:
return None
orderby2 = orderby[0]
for item in orderby[1:]:
orderby2 = orderby2 | item
return orderby2
def use_common_filters(query):
return (query and hasattr(query,'ignore_common_filters') and \
not query.ignore_common_filters)
class Set(object):
"""
a Set represents a set of records in the database,
the records are identified by the query=Query(...) object.
normally the Set is generated by DAL.__call__(Query(...))
given a set, for example
set = db(db.users.name=='Max')
you can:
set.update(db.users.name='Massimo')
set.delete() # all elements in the set
set.select(orderby=db.users.id, groupby=db.users.name, limitby=(0,10))
and take subsets:
subset = set(db.users.id<5)
"""
def __init__(self, db, query, ignore_common_filters = None):
self.db = db
self._db = db # for backward compatibility
if not ignore_common_filters is None and \
use_common_filters(query) == ignore_common_filters:
query = copy.copy(query)
query.ignore_common_filters = ignore_common_filters
self.query = query
def __call__(self, query, ignore_common_filters=False):
if isinstance(query,Table):
query = query._id>0
elif isinstance(query,str):
query = raw(query)
elif isinstance(query,Field):
query = query!=None
if self.query:
return Set(self.db, self.query & query,
ignore_common_filters = ignore_common_filters)
else:
return Set(self.db, query,
ignore_common_filters = ignore_common_filters)
def _count(self,distinct=None):
return self.db._adapter._count(self.query,distinct)
def _select(self, *fields, **attributes):
adapter = self.db._adapter
fields = adapter.expand_all(fields, adapter.tables(self.query))
return adapter._select(self.query,fields,attributes)
def _delete(self):
tablename=self.db._adapter.get_table(self.query)
return self.db._adapter._delete(tablename,self.query)
def _update(self, **update_fields):
tablename = self.db._adapter.get_table(self.query)
fields = self.db[tablename]._listify(update_fields,update=True)
return self.db._adapter._update(tablename,self.query,fields)
def isempty(self):
return not self.select(limitby=(0,1))
def count(self,distinct=None):
return self.db._adapter.count(self.query,distinct)
def select(self, *fields, **attributes):
adapter = self.db._adapter
fields = adapter.expand_all(fields, adapter.tables(self.query))
return adapter.select(self.query,fields,attributes)
def delete(self):
tablename=self.db._adapter.get_table(self.query)
self.delete_uploaded_files()
return self.db._adapter.delete(tablename,self.query)
def update(self, **update_fields):
tablename = self.db._adapter.get_table(self.query)
fields = self.db[tablename]._listify(update_fields,update=True)
if not fields:
raise SyntaxError, "No fields to update"
self.delete_uploaded_files(update_fields)
return self.db._adapter.update(tablename,self.query,fields)
def validate_and_update(self, **update_fields):
tablename = self.db._adapter.get_table(self.query)
response = Row()
response.errors = Row()
new_fields = copy.copy(update_fields)
for key,value in update_fields.items():
value,error = self.db[tablename][key].validate(value)
if error:
response.errors[key] = error
else:
new_fields[key] = value
fields = self.db[tablename]._listify(new_fields,update=True)
if not fields:
raise SyntaxError, "No fields to update"
if response.errors:
response.updated = None
else:
self.delete_uploaded_files(new_fields)
response.updated = self.db._adapter.update(tablename,self.query,fields)
return response
def delete_uploaded_files(self, upload_fields=None):
table = self.db[self.db._adapter.tables(self.query)[0]]
# ## mind uploadfield==True means file is not in DB
if upload_fields:
fields = upload_fields.keys()
else:
fields = table.fields
fields = [f for f in fields if table[f].type == 'upload'
and table[f].uploadfield == True
and table[f].autodelete]
if not fields:
return
for record in self.select(*[table[f] for f in fields]):
for fieldname in fields:
field = table[fieldname]
oldname = record.get(fieldname, None)
if not oldname:
continue
if upload_fields and oldname == upload_fields[fieldname]:
continue
if field.custom_delete:
field.custom_delete(oldname)
else:
uploadfolder = field.uploadfolder
if not uploadfolder:
uploadfolder = os.path.join(self.db._adapter.folder, '..', 'uploads')
if field.uploadseparate:
items = oldname.split('.')
uploadfolder = os.path.join(uploadfolder,
"%s.%s" % (items[0], items[1]),
items[2][:2])
oldpath = os.path.join(uploadfolder, oldname)
if os.path.exists(oldpath):
os.unlink(oldpath)
def update_record(pack, a=None):
(colset, table, id) = pack
b = a or dict(colset)
c = dict([(k,v) for (k,v) in b.items() if k in table.fields and table[k].type!='id'])
table._db(table._id==id).update(**c)
for (k, v) in c.items():
colset[k] = v
class VirtualCommand(object):
def __init__(self,method,row):
self.method=method
self.row=row
def __call__(self,*args,**kwargs):
return self.method(self.row,*args,**kwargs)
def lazy_virtualfield(f):
f.__lazy__ = True
return f
class Rows(object):
"""
A wrapper for the return value of a select. It basically represents a table.
It has an iterator and each row is represented as a dictionary.
"""
# ## TODO: this class still needs some work to care for ID/OID
def __init__(
self,
db=None,
records=[],
colnames=[],
compact=True,
rawrows=None
):
self.db = db
self.records = records
self.colnames = colnames
self.compact = compact
self.response = rawrows
def setvirtualfields(self,**keyed_virtualfields):
"""
db.define_table('x',Field('number','integer'))
if db(db.x).isempty(): [db.x.insert(number=i) for i in range(10)]
from gluon.dal import lazy_virtualfield
class MyVirtualFields(object):
# normal virtual field (backward compatible, discouraged)
def normal_shift(self): return self.x.number+1
# lazy virtual field (because of @staticmethod)
@lazy_virtualfield
def lazy_shift(instance,row,delta=4): return row.x.number+delta
db.x.virtualfields.append(MyVirtualFields())
for row in db(db.x).select():
print row.number, row.normal_shift, row.lazy_shift(delta=7)
"""
if not keyed_virtualfields:
return self
for row in self.records:
for (tablename,virtualfields) in keyed_virtualfields.items():
attributes = dir(virtualfields)
if not tablename in row:
box = row[tablename] = Row()
else:
box = row[tablename]
updated = False
for attribute in attributes:
if attribute[0] != '_':
method = getattr(virtualfields,attribute)
if hasattr(method,'__lazy__'):
box[attribute]=VirtualCommand(method,row)
elif type(method)==types.MethodType:
if not updated:
virtualfields.__dict__.update(row)
updated = True
box[attribute]=method()
return self
def __and__(self,other):
if self.colnames!=other.colnames: raise Exception, 'Cannot & incompatible Rows objects'
records = self.records+other.records
return Rows(self.db,records,self.colnames)
def __or__(self,other):
if self.colnames!=other.colnames: raise Exception, 'Cannot | incompatible Rows objects'
records = self.records
records += [record for record in other.records \
if not record in records]
return Rows(self.db,records,self.colnames)
def __nonzero__(self):
if len(self.records):
return 1
return 0
def __len__(self):
return len(self.records)
def __getslice__(self, a, b):
return Rows(self.db,self.records[a:b],self.colnames)
def __getitem__(self, i):
row = self.records[i]
keys = row.keys()
if self.compact and len(keys) == 1 and keys[0] != '_extra':
return row[row.keys()[0]]
return row
def __iter__(self):
"""
iterator over records
"""
for i in xrange(len(self)):
yield self[i]
def __str__(self):
"""
serializes the table into a csv file
"""
s = cStringIO.StringIO()
self.export_to_csv_file(s)
return s.getvalue()
def first(self):
if not self.records:
return None
return self[0]
def last(self):
if not self.records:
return None
return self[-1]
def find(self,f):
"""
returns a new Rows object, a subset of the original object,
filtered by the function f
"""
if not self.records:
return Rows(self.db, [], self.colnames)
records = []
for i in range(0,len(self)):
row = self[i]
if f(row):
records.append(self.records[i])
return Rows(self.db, records, self.colnames)
def exclude(self, f):
"""
removes elements from the calling Rows object, filtered by the function f,
and returns a new Rows object containing the removed elements
"""
if not self.records:
return Rows(self.db, [], self.colnames)
removed = []
i=0
while i<len(self):
row = self[i]
if f(row):
removed.append(self.records[i])
del self.records[i]
else:
i += 1
return Rows(self.db, removed, self.colnames)
def sort(self, f, reverse=False):
"""
returns a list of sorted elements (not sorted in place)
"""
return Rows(self.db,sorted(self,key=f,reverse=reverse),self.colnames)
def group_by_value(self, field):
"""
regroups the rows, by one of the fields
"""
if not self.records:
return {}
key = str(field)
grouped_row_group = dict()
for row in self:
value = row[key]
if not value in grouped_row_group:
grouped_row_group[value] = [row]
else:
grouped_row_group[value].append(row)
return grouped_row_group
def as_list(self,
compact=True,
storage_to_dict=True,
datetime_to_str=True):
"""
returns the data as a list or dictionary.
:param storage_to_dict: when True returns a dict, otherwise a list(default True)
:param datetime_to_str: convert datetime fields as strings (default True)
"""
(oc, self.compact) = (self.compact, compact)
if storage_to_dict:
items = [item.as_dict(datetime_to_str) for item in self]
else:
items = [item for item in self]
self.compact = compact
return items
def as_dict(self,
key='id',
compact=True,
storage_to_dict=True,
datetime_to_str=True):
"""
returns the data as a dictionary of dictionaries (storage_to_dict=True) or records (False)
:param key: the name of the field to be used as dict key, normally the id
:param compact: ? (default True)
:param storage_to_dict: when True returns a dict, otherwise a list(default True)
:param datetime_to_str: convert datetime fields as strings (default True)
"""
rows = self.as_list(compact, storage_to_dict, datetime_to_str)
if isinstance(key,str) and key.count('.')==1:
(table, field) = key.split('.')
return dict([(r[table][field],r) for r in rows])
elif isinstance(key,str):
return dict([(r[key],r) for r in rows])
else:
return dict([(key(r),r) for r in rows])
def export_to_csv_file(self, ofile, null='<NULL>', *args, **kwargs):
"""
export data to csv, the first line contains the column names
:param ofile: where the csv must be exported to
:param null: how null values must be represented (default '<NULL>')
:param delimiter: delimiter to separate values (default ',')
:param quotechar: character to use to quote string values (default '"')
:param quoting: quote system, use csv.QUOTE_*** (default csv.QUOTE_MINIMAL)
:param represent: use the fields .represent value (default False)
:param colnames: list of column names to use (default self.colnames)
This will only work when exporting rows objects!!!!
DO NOT use this with db.export_to_csv()
"""
delimiter = kwargs.get('delimiter', ',')
quotechar = kwargs.get('quotechar', '"')
quoting = kwargs.get('quoting', csv.QUOTE_MINIMAL)
represent = kwargs.get('represent', False)
writer = csv.writer(ofile, delimiter=delimiter,
quotechar=quotechar, quoting=quoting)
colnames = kwargs.get('colnames', self.colnames)
write_colnames = kwargs.get('write_colnames',True)
# a proper csv starting with the column names
if write_colnames:
writer.writerow(colnames)
def none_exception(value):
"""
returns a cleaned up value that can be used for csv export:
- unicode text is encoded as such
- None values are replaced with the given representation (default <NULL>)
"""
if value is None:
return null
elif isinstance(value, unicode):
return value.encode('utf8')
elif isinstance(value,Reference):
return int(value)
elif hasattr(value, 'isoformat'):
return value.isoformat()[:19].replace('T', ' ')
elif isinstance(value, (list,tuple)): # for type='list:..'
return bar_encode(value)
return value
for record in self:
row = []
for col in colnames:
if not regex_table_field.match(col):
row.append(record._extra[col])
else:
(t, f) = col.split('.')
field = self.db[t][f]
if isinstance(record.get(t, None), (Row,dict)):
value = record[t][f]
else:
value = record[f]
if field.type=='blob' and not value is None:
value = base64.b64encode(value)
elif represent and field.represent:
value = field.represent(value)
row.append(none_exception(value))
writer.writerow(row)
def xml(self):
"""
serializes the table using sqlhtml.SQLTABLE (if present)
"""
import sqlhtml
return sqlhtml.SQLTABLE(self).xml()
def json(self, mode='object', default=None):
"""
serializes the table to a JSON list of objects
"""
mode = mode.lower()
if not mode in ['object', 'array']:
raise SyntaxError, 'Invalid JSON serialization mode: %s' % mode
def inner_loop(record, col):
(t, f) = col.split('.')
res = None
if not regex_table_field.match(col):
key = col
res = record._extra[col]
else:
key = f
if isinstance(record.get(t, None), Row):
res = record[t][f]
else:
res = record[f]
if mode == 'object':
return (key, res)
else:
return res
if mode == 'object':
items = [dict([inner_loop(record, col) for col in
self.colnames]) for record in self]
else:
items = [[inner_loop(record, col) for col in self.colnames]
for record in self]
if have_serializers:
return serializers.json(items,default=default or serializers.custom_json)
else:
import simplejson
return simplejson.dumps(items)
def Rows_unpickler(data):
return cPickle.loads(data)
def Rows_pickler(data):
return Rows_unpickler, \
(cPickle.dumps(data.as_list(storage_to_dict=False,
datetime_to_str=False)),)
copy_reg.pickle(Rows, Rows_pickler, Rows_unpickler)
################################################################################
# dummy function used to define some doctests
################################################################################
def test_all():
"""
>>> if len(sys.argv)<2: db = DAL(\"sqlite://test.db\")
>>> if len(sys.argv)>1: db = DAL(sys.argv[1])
>>> tmp = db.define_table('users',\
Field('stringf', 'string', length=32, required=True),\
Field('booleanf', 'boolean', default=False),\
Field('passwordf', 'password', notnull=True),\
Field('uploadf', 'upload'),\
Field('blobf', 'blob'),\
Field('integerf', 'integer', unique=True),\
Field('doublef', 'double', unique=True,notnull=True),\
Field('datef', 'date', default=datetime.date.today()),\
Field('timef', 'time'),\
Field('datetimef', 'datetime'),\
migrate='test_user.table')
Insert a field
>>> db.users.insert(stringf='a', booleanf=True, passwordf='p', blobf='0A',\
uploadf=None, integerf=5, doublef=3.14,\
datef=datetime.date(2001, 1, 1),\
timef=datetime.time(12, 30, 15),\
datetimef=datetime.datetime(2002, 2, 2, 12, 30, 15))
1
Drop the table
>>> db.users.drop()
Examples of insert, select, update, delete
>>> tmp = db.define_table('person',\
Field('name'),\
Field('birth','date'),\
migrate='test_person.table')
>>> person_id = db.person.insert(name=\"Marco\",birth='2005-06-22')
>>> person_id = db.person.insert(name=\"Massimo\",birth='1971-12-21')
commented len(db().select(db.person.ALL))
commented 2
>>> me = db(db.person.id==person_id).select()[0] # test select
>>> me.name
'Massimo'
>>> db(db.person.name=='Massimo').update(name='massimo') # test update
1
>>> db(db.person.name=='Marco').select().first().delete_record() # test delete
1
Update a single record
>>> me.update_record(name=\"Max\")
>>> me.name
'Max'
Examples of complex search conditions
>>> len(db((db.person.name=='Max')&(db.person.birth<'2003-01-01')).select())
1
>>> len(db((db.person.name=='Max')&(db.person.birth<datetime.date(2003,01,01))).select())
1
>>> len(db((db.person.name=='Max')|(db.person.birth<'2003-01-01')).select())
1
>>> me = db(db.person.id==person_id).select(db.person.name)[0]
>>> me.name
'Max'
Examples of search conditions using extract from date/datetime/time
>>> len(db(db.person.birth.month()==12).select())
1
>>> len(db(db.person.birth.year()>1900).select())
1
Example of usage of NULL
>>> len(db(db.person.birth==None).select()) ### test NULL
0
>>> len(db(db.person.birth!=None).select()) ### test NULL
1
Examples of search conditions using lower, upper, and like
>>> len(db(db.person.name.upper()=='MAX').select())
1
>>> len(db(db.person.name.like('%ax')).select())
1
>>> len(db(db.person.name.upper().like('%AX')).select())
1
>>> len(db(~db.person.name.upper().like('%AX')).select())
0
orderby, groupby and limitby
>>> people = db().select(db.person.name, orderby=db.person.name)
>>> order = db.person.name|~db.person.birth
>>> people = db().select(db.person.name, orderby=order)
>>> people = db().select(db.person.name, orderby=db.person.name, groupby=db.person.name)
>>> people = db().select(db.person.name, orderby=order, limitby=(0,100))
Example of one 2 many relation
>>> tmp = db.define_table('dog',\
Field('name'),\
Field('birth','date'),\
Field('owner',db.person),\
migrate='test_dog.table')
>>> db.dog.insert(name='Snoopy', birth=None, owner=person_id)
1
A simple JOIN
>>> len(db(db.dog.owner==db.person.id).select())
1
>>> len(db().select(db.person.ALL, db.dog.name,left=db.dog.on(db.dog.owner==db.person.id)))
1
Drop tables
>>> db.dog.drop()
>>> db.person.drop()
Example of many 2 many relation and Set
>>> tmp = db.define_table('author', Field('name'),\
migrate='test_author.table')
>>> tmp = db.define_table('paper', Field('title'),\
migrate='test_paper.table')
>>> tmp = db.define_table('authorship',\
Field('author_id', db.author),\
Field('paper_id', db.paper),\
migrate='test_authorship.table')
>>> aid = db.author.insert(name='Massimo')
>>> pid = db.paper.insert(title='QCD')
>>> tmp = db.authorship.insert(author_id=aid, paper_id=pid)
Define a Set
>>> authored_papers = db((db.author.id==db.authorship.author_id)&(db.paper.id==db.authorship.paper_id))
>>> rows = authored_papers.select(db.author.name, db.paper.title)
>>> for row in rows: print row.author.name, row.paper.title
Massimo QCD
Example of search condition using belongs
>>> set = (1, 2, 3)
>>> rows = db(db.paper.id.belongs(set)).select(db.paper.ALL)
>>> print rows[0].title
QCD
Example of search condition using nested select
>>> nested_select = db()._select(db.authorship.paper_id)
>>> rows = db(db.paper.id.belongs(nested_select)).select(db.paper.ALL)
>>> print rows[0].title
QCD
Example of expressions
>>> mynumber = db.define_table('mynumber', Field('x', 'integer'))
>>> db(mynumber.id>0).delete()
0
>>> for i in range(10): tmp = mynumber.insert(x=i)
>>> db(mynumber.id>0).select(mynumber.x.sum())[0](mynumber.x.sum())
45
>>> db(mynumber.x+2==5).select(mynumber.x + 2)[0](mynumber.x + 2)
5
Output in csv
>>> print str(authored_papers.select(db.author.name, db.paper.title)).strip()
author.name,paper.title\r
Massimo,QCD
Delete all leftover tables
>>> DAL.distributed_transaction_commit(db)
>>> db.mynumber.drop()
>>> db.authorship.drop()
>>> db.author.drop()
>>> db.paper.drop()
"""
################################################################################
# deprecated since the new DAL; here only for backward compatibility
################################################################################
SQLField = Field
SQLTable = Table
SQLXorable = Expression
SQLQuery = Query
SQLSet = Set
SQLRows = Rows
SQLStorage = Row
SQLDB = DAL
GQLDB = DAL
DAL.Field = Field # was necessary in gluon/globals.py session.connect
DAL.Table = Table # was necessary in gluon/globals.py session.connect
################################################################################
# run tests
################################################################################
if __name__ == '__main__':
import doctest
doctest.testmod()
|