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
|
## DBI: R Database Interface
<span id="topic+DBI"></span> <span id="topic+DBI-package"></span>
DBI defines an interface for communication between R and relational
database management systems. All classes in this package are virtual and
need to be extended by the various R/DBMS implementations (so-called
*DBI backends*).
### Definition
A DBI backend is an R package which imports the
<span class="pkg">DBI</span> and <span class="pkg">methods</span>
packages. For better or worse, the names of many existing backends start
with ‘R’, e.g., <span class="pkg">RSQLite</span>,
<span class="pkg">RMySQL</span>, <span class="pkg">RSQLServer</span>; it
is up to the backend author to adopt this convention or not.
### DBI classes and methods
A backend defines three classes, which are subclasses of DBIDriver,
DBIConnection, and DBIResult. The backend provides implementation for
all methods of these base classes that are defined but not implemented
by DBI. All methods defined in <span class="pkg">DBI</span> are
reexported (so that the package can be used without having to attach
<span class="pkg">DBI</span>), and have an ellipsis `...` in their
formals for extensibility.
### Construction of the DBIDriver object
The backend must support creation of an instance of its DBIDriver
subclass with a <span class="dfn">constructor function</span>. By
default, its name is the package name without the leading ‘R’ (if it
exists), e.g., `SQLite` for the <span class="pkg">RSQLite</span>
package. However, backend authors may choose a different name. The
constructor must be exported, and it must be a function that is callable
without arguments. DBI recommends to define a constructor with an empty
argument list.
### Examples
``` r
RSQLite::SQLite()
```
## Determine the SQL data type of an object
<span id="topic+dbDataType"></span>
This section describes the behavior of the following method:
``` r
dbDataType(dbObj, obj, ...)
```
### Description
Returns an SQL string that describes the SQL data type to be used for an
object. The default implementation of this generic determines the SQL
type of an R object according to the SQL 92 specification, which may
serve as a starting point for driver implementations. DBI also provides
an implementation for data.frame which will return a character vector
giving the type for each column in the dataframe.
### Arguments
| | |
|---------|-----------------------------------------------------|
| `dbObj` | A object inheriting from DBIDriver or DBIConnection |
| `obj` | An R object whose SQL type we want to determine. |
| `...` | Other arguments passed on to methods. |
### Details
The data types supported by databases are different than the data types
in R, but the mapping between the primitive types is straightforward:
- Any of the many fixed and varying length character types are mapped to
character vectors
- Fixed-precision (non-IEEE) numbers are mapped into either numeric or
integer vectors.
Notice that many DBMS do not follow IEEE arithmetic, so there are
potential problems with under/overflows and loss of precision.
### Value
`dbDataType()` returns the SQL type that corresponds to the `obj`
argument as a non-empty character string. For data frames, a character
vector with one element per column is returned.
### Failure modes
An error is raised for invalid values for the `obj` argument such as a
`NULL` value.
### Specification
The backend can override the `dbDataType()` generic for its driver
class.
This generic expects an arbitrary object as second argument. To query
the values returned by the default implementation, run
`example(dbDataType, package = "DBI")`. If the backend needs to override
this generic, it must accept all basic R data types as its second
argument, namely logical, integer, numeric, character, dates (see
Dates), date-time (see DateTimeClasses), and difftime. If the database
supports blobs, this method also must accept lists of raw vectors, and
blob::blob objects. As-is objects (i.e., wrapped by `I()`) must be
supported and return the same results as their unwrapped counterparts.
The SQL data type for factor and ordered is the same as for character.
The behavior for other object types is not specified.
All data types returned by `dbDataType()` are usable in an SQL statement
of the form `"CREATE TABLE test (a ...)"`.
### Examples
``` r
dbDataType(ANSI(), 1:5)
dbDataType(ANSI(), 1)
dbDataType(ANSI(), TRUE)
dbDataType(ANSI(), Sys.Date())
dbDataType(ANSI(), Sys.time())
dbDataType(ANSI(), Sys.time() - as.POSIXct(Sys.Date()))
dbDataType(ANSI(), c("x", "abc"))
dbDataType(ANSI(), list(raw(10), raw(20)))
dbDataType(ANSI(), I(3))
dbDataType(ANSI(), iris)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbDataType(con, 1:5)
dbDataType(con, 1)
dbDataType(con, TRUE)
dbDataType(con, Sys.Date())
dbDataType(con, Sys.time())
dbDataType(con, Sys.time() - as.POSIXct(Sys.Date()))
dbDataType(con, c("x", "abc"))
dbDataType(con, list(raw(10), raw(20)))
dbDataType(con, I(3))
dbDataType(con, iris)
dbDisconnect(con)
```
## Create a connection to a DBMS
<span id="topic+dbConnect"></span>
This section describes the behavior of the following method:
``` r
dbConnect(drv, ...)
```
### Description
Connect to a DBMS going through the appropriate authentication
procedure. Some implementations may allow you to have multiple
connections open, so you may invoke this function repeatedly assigning
its output to different objects. The authentication mechanism is left
unspecified, so check the documentation of individual drivers for
details. Use `dbCanConnect()` to check if a connection can be
established.
### Arguments
| | |
|----|----|
| `drv` | An object that inherits from DBIDriver, or an existing DBIConnection object (in order to clone an existing connection). |
| `...` | Authentication arguments needed by the DBMS instance; these typically include `user`, `password`, `host`, `port`, `dbname`, etc. For details see the appropriate `DBIDriver`. |
### Value
`dbConnect()` returns an S4 object that inherits from DBIConnection.
This object is used to communicate with the database engine.
A `format()` method is defined for the connection object. It returns a
string that consists of a single line of text.
### Specification
DBI recommends using the following argument names for authentication
parameters, with `NULL` default:
- `user` for the user name (default: current user)
- `password` for the password
- `host` for the host name (default: local connection)
- `port` for the port number (default: local connection)
- `dbname` for the name of the database on the host, or the database
file name
The defaults should provide reasonable behavior, in particular a local
connection for `host = NULL`. For some DBMS (e.g., PostgreSQL), this is
different to a TCP/IP connection to `localhost`.
In addition, DBI supports the `bigint` argument that governs how 64-bit
integer data is returned. The following values are supported:
- `"integer"`: always return as `integer`, silently overflow
- `"numeric"`: always return as `numeric`, silently round
- `"character"`: always return the decimal representation as `character`
- `"integer64"`: return as a data type that can be coerced using
`as.integer()` (with warning on overflow), `as.numeric()` and
`as.character()`
### Examples
``` r
# SQLite only needs a path to the database. (Here, ":memory:" is a special
# path that creates an in-memory database.) Other database drivers
# will require more details (like user, password, host, port, etc.)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
con
dbListTables(con)
dbDisconnect(con)
# Bad, for subtle reasons:
# This code fails when RSQLite isn't loaded yet,
# because dbConnect() doesn't know yet about RSQLite.
dbListTables(con <- dbConnect(RSQLite::SQLite(), ":memory:"))
```
## Disconnect (close) a connection
<span id="topic+dbDisconnect"></span>
This section describes the behavior of the following method:
``` r
dbDisconnect(conn, ...)
```
### Description
This closes the connection, discards all pending work, and frees
resources (e.g., memory, sockets).
### Arguments
| | |
|--------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `...` | Other parameters passed on to methods. |
### Value
`dbDisconnect()` returns `TRUE`, invisibly.
### Failure modes
A warning is issued on garbage collection when a connection has been
released without calling `dbDisconnect()`, but this cannot be tested
automatically. At least one warning is issued immediately when calling
`dbDisconnect()` on an already disconnected or invalid connection.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbDisconnect(con)
```
## Execute a query on a given database connection
<span id="topic+dbSendQuery"></span>
This section describes the behavior of the following method:
``` r
dbSendQuery(conn, statement, ...)
```
### Description
The `dbSendQuery()` method only submits and synchronously executes the
SQL query to the database engine. It does *not* extract any records —
for that you need to use the `dbFetch()` method, and then you must call
`dbClearResult()` when you finish fetching the records you need. For
interactive use, you should almost always prefer `dbGetQuery()`. Use
`dbSendQueryArrow()` or `dbGetQueryArrow()` instead to retrieve the
results as an Arrow object.
### Arguments
| | |
|-------------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `statement` | a character string containing SQL. |
| `...` | Other parameters passed on to methods. |
### Additional arguments
The following arguments are not part of the `dbSendQuery()` generic (to
improve compatibility across backends) but are part of the DBI
specification:
- `params` (default: `NULL`)
- `immediate` (default: `NULL`)
They must be provided as named arguments. See the "Specification"
sections for details on their usage.
### Specification
No warnings occur under normal conditions. When done, the DBIResult
object must be cleared with a call to `dbClearResult()`. Failure to
clear the result set leads to a warning when the connection is closed.
If the backend supports only one open result set per connection, issuing
a second query invalidates an already open result set and raises a
warning. The newly opened result set is valid and must be cleared with
`dbClearResult()`.
The `param` argument allows passing query parameters, see `dbBind()` for
details.
### Specification for the `immediate` argument
The `immediate` argument supports distinguishing between "direct" and
"prepared" APIs offered by many database drivers. Passing
`immediate = TRUE` leads to immediate execution of the query or
statement, via the "direct" API (if supported by the driver). The
default `NULL` means that the backend should choose whatever API makes
the most sense for the database, and (if relevant) tries the other API
if the first attempt fails. A successful second attempt should result in
a message that suggests passing the correct `immediate` argument.
Examples for possible behaviors:
1. DBI backend defaults to `immediate = TRUE` internally
1. A query without parameters is passed: query is executed
2. A query with parameters is passed:
1. `params` not given: rejected immediately by the database
because of a syntax error in the query, the backend tries
`immediate = FALSE` (and gives a message)
2. `params` given: query is executed using `immediate = FALSE`
2. DBI backend defaults to `immediate = FALSE` internally
1. A query without parameters is passed:
1. simple query: query is executed
2. "special" query (such as setting a config options): fails,
the backend tries `immediate = TRUE` (and gives a message)
2. A query with parameters is passed:
1. `params` not given: waiting for parameters via `dbBind()`
2. `params` given: query is executed
### Details
This method is for `SELECT` queries only. Some backends may support data
manipulation queries through this method for compatibility reasons.
However, callers are strongly encouraged to use `dbSendStatement()` for
data manipulation statements.
The query is submitted to the database server and the DBMS executes it,
possibly generating vast amounts of data. Where these data live is
driver-specific: some drivers may choose to leave the output on the
server and transfer them piecemeal to R, others may transfer all the
data to the client – but not necessarily to the memory that R manages.
See individual drivers' `dbSendQuery()` documentation for details.
### Value
`dbSendQuery()` returns an S4 object that inherits from DBIResult. The
result set can be used with `dbFetch()` to extract records. Once you
have finished using a result, make sure to clear it with
`dbClearResult()`.
### The data retrieval flow
This section gives a complete overview over the flow for the execution
of queries that return tabular data as data frames.
Most of this flow, except repeated calling of `dbBind()` or
`dbBindArrow()`, is implemented by `dbGetQuery()`, which should be
sufficient unless you want to access the results in a paged way or you
have a parameterized query that you want to reuse. This flow requires an
active connection established by `dbConnect()`. See also
`vignette("dbi-advanced")` for a walkthrough.
1. Use `dbSendQuery()` to create a result set object of class
DBIResult.
2. Optionally, bind query parameters with `dbBind()` or
`dbBindArrow()`. This is required only if the query contains
placeholders such as `?` or `\$1`, depending on the database
backend.
3. Optionally, use `dbColumnInfo()` to retrieve the structure of the
result set without retrieving actual data.
4. Use `dbFetch()` to get the entire result set, a page of results, or
the remaining rows. Fetching zero rows is also possible to retrieve
the structure of the result set as a data frame. This step can be
called multiple times. Only forward paging is supported, you need to
cache previous pages if you need to navigate backwards.
5. Use `dbHasCompleted()` to tell when you're done. This method returns
`TRUE` if no more rows are available for fetching.
6. Repeat the last four steps as necessary.
7. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### Failure modes
An error is raised when issuing a query over a closed or invalid
connection, or if the query is not a non-`NA` string. An error is also
raised if the syntax of the query is invalid and all query parameters
are given (by passing the `params` argument) or the `immediate` argument
is set to `TRUE`.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4")
dbFetch(rs)
dbClearResult(rs)
# Pass one set of values with the param argument:
rs <- dbSendQuery(
con,
"SELECT * FROM mtcars WHERE cyl = ?",
params = list(4L)
)
dbFetch(rs)
dbClearResult(rs)
# Pass multiple sets of values with dbBind():
rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = ?")
dbBind(rs, list(6L))
dbFetch(rs)
dbBind(rs, list(8L))
dbFetch(rs)
dbClearResult(rs)
dbDisconnect(con)
```
## Fetch records from a previously executed query
<span id="topic+dbFetch"></span> <span id="topic+fetch"></span>
This section describes the behavior of the following methods:
``` r
dbFetch(res, n = -1, ...)
fetch(res, n = -1, ...)
```
### Description
Fetch the next `n` elements (rows) from the result set and return them
as a data.frame.
### Arguments
| | |
|----|----|
| `res` | An object inheriting from DBIResult, created by `dbSendQuery()`. |
| `n` | maximum number of records to retrieve per fetch. Use `n = -1` or `n = Inf` to retrieve all pending records. Some implementations may recognize other special values. |
| `...` | Other arguments passed on to methods. |
### Details
`fetch()` is provided for compatibility with older DBI clients - for all
new code you are strongly encouraged to use `dbFetch()`. The default
implementation for `dbFetch()` calls `fetch()` so that it is compatible
with existing code. Modern backends should implement for `dbFetch()`
only.
### Value
`dbFetch()` always returns a data.frame with as many rows as records
were fetched and as many columns as fields in the result set, even if
the result is a single value or has one or zero rows. Passing `n = NA`
is supported and returns an arbitrary number of rows (at least one) as
specified by the driver, but at most the remaining rows in the result
set.
### The data retrieval flow
This section gives a complete overview over the flow for the execution
of queries that return tabular data as data frames.
Most of this flow, except repeated calling of `dbBind()` or
`dbBindArrow()`, is implemented by `dbGetQuery()`, which should be
sufficient unless you want to access the results in a paged way or you
have a parameterized query that you want to reuse. This flow requires an
active connection established by `dbConnect()`. See also
`vignette("dbi-advanced")` for a walkthrough.
1. Use `dbSendQuery()` to create a result set object of class
DBIResult.
2. Optionally, bind query parameters with `dbBind()` or
`dbBindArrow()`. This is required only if the query contains
placeholders such as `?` or `\$1`, depending on the database
backend.
3. Optionally, use `dbColumnInfo()` to retrieve the structure of the
result set without retrieving actual data.
4. Use `dbFetch()` to get the entire result set, a page of results, or
the remaining rows. Fetching zero rows is also possible to retrieve
the structure of the result set as a data frame. This step can be
called multiple times. Only forward paging is supported, you need to
cache previous pages if you need to navigate backwards.
5. Use `dbHasCompleted()` to tell when you're done. This method returns
`TRUE` if no more rows are available for fetching.
6. Repeat the last four steps as necessary.
7. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### Failure modes
An attempt to fetch from a closed result set raises an error. If the `n`
argument is not an atomic whole number greater or equal to -1 or Inf, an
error is raised, but a subsequent call to `dbFetch()` with proper `n`
argument succeeds.
Calling `dbFetch()` on a result set from a data manipulation query
created by `dbSendStatement()` can be fetched and return an empty data
frame, with a warning.
### Specification
Fetching multi-row queries with one or more columns by default returns
the entire result. Multi-row queries can also be fetched progressively
by passing a whole number (integer or numeric) as the `n` argument. A
value of Inf for the `n` argument is supported and also returns the full
result. If more rows than available are fetched, the result is returned
in full without warning. If fewer rows than requested are returned,
further fetches will return a data frame with zero rows. If zero rows
are fetched, the columns of the data frame are still fully typed.
Fetching fewer rows than available is permitted, no warning is issued
when clearing the result set.
A column named `row_names` is treated like any other column.
The column types of the returned data frame depend on the data returned:
- integer (or coercible to an integer) for integer values between -2^31
and 2^31 - 1, with NA for SQL `NULL` values
- numeric for numbers with a fractional component, with NA for SQL
`NULL` values
- logical for Boolean values (some backends may return an integer); with
NA for SQL `NULL` values
- character for text, with NA for SQL `NULL` values
- lists of raw for blobs with NULL entries for SQL NULL values
- coercible using `as.Date()` for dates, with NA for SQL `NULL` values
(also applies to the return value of the SQL function `current_date`)
- coercible using `hms::as_hms()` for times, with NA for SQL `NULL`
values (also applies to the return value of the SQL function
`current_time`)
- coercible using `as.POSIXct()` for timestamps, with NA for SQL `NULL`
values (also applies to the return value of the SQL function
`current_timestamp`)
If dates and timestamps are supported by the backend, the following R
types are used:
- Date for dates (also applies to the return value of the SQL function
`current_date`)
- POSIXct for timestamps (also applies to the return value of the SQL
function `current_timestamp`)
R has no built-in type with lossless support for the full range of
64-bit or larger integers. If 64-bit integers are returned from a query,
the following rules apply:
- Values are returned in a container with support for the full range of
valid 64-bit values (such as the `integer64` class of the
<span class="pkg">bit64</span> package)
- Coercion to numeric always returns a number that is as close as
possible to the true value
- Loss of precision when converting to numeric gives a warning
- Conversion to character always returns a lossless decimal
representation of the data
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
# Fetch all results
rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4")
dbFetch(rs)
dbClearResult(rs)
# Fetch in chunks
rs <- dbSendQuery(con, "SELECT * FROM mtcars")
while (!dbHasCompleted(rs)) {
chunk <- dbFetch(rs, 10)
print(nrow(chunk))
}
dbClearResult(rs)
dbDisconnect(con)
```
## Clear a result set
<span id="topic+dbClearResult"></span>
This section describes the behavior of the following method:
``` r
dbClearResult(res, ...)
```
### Description
Frees all resources (local and remote) associated with a result set.
This step is mandatory for all objects obtained by calling
`dbSendQuery()` or `dbSendStatement()`.
### Arguments
| | |
|-------|---------------------------------------|
| `res` | An object inheriting from DBIResult. |
| `...` | Other arguments passed on to methods. |
### Value
`dbClearResult()` returns `TRUE`, invisibly, for result sets obtained
from `dbSendQuery()`, `dbSendStatement()`, or `dbSendQueryArrow()`,
### The data retrieval flow
This section gives a complete overview over the flow for the execution
of queries that return tabular data as data frames.
Most of this flow, except repeated calling of `dbBind()` or
`dbBindArrow()`, is implemented by `dbGetQuery()`, which should be
sufficient unless you want to access the results in a paged way or you
have a parameterized query that you want to reuse. This flow requires an
active connection established by `dbConnect()`. See also
`vignette("dbi-advanced")` for a walkthrough.
1. Use `dbSendQuery()` to create a result set object of class
DBIResult.
2. Optionally, bind query parameters with `dbBind()` or
`dbBindArrow()`. This is required only if the query contains
placeholders such as `?` or `\$1`, depending on the database
backend.
3. Optionally, use `dbColumnInfo()` to retrieve the structure of the
result set without retrieving actual data.
4. Use `dbFetch()` to get the entire result set, a page of results, or
the remaining rows. Fetching zero rows is also possible to retrieve
the structure of the result set as a data frame. This step can be
called multiple times. Only forward paging is supported, you need to
cache previous pages if you need to navigate backwards.
5. Use `dbHasCompleted()` to tell when you're done. This method returns
`TRUE` if no more rows are available for fetching.
6. Repeat the last four steps as necessary.
7. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### The command execution flow
This section gives a complete overview over the flow for the execution
of SQL statements that have side effects such as stored procedures,
inserting or deleting data, or setting database or connection options.
Most of this flow, except repeated calling of `dbBindArrow()`, is
implemented by `dbExecute()`, which should be sufficient for
non-parameterized queries. This flow requires an active connection
established by `dbConnect()`. See also `vignette("dbi-advanced")` for a
walkthrough.
1. Use `dbSendStatement()` to create a result set object of class
DBIResult. For some queries you need to pass `immediate = TRUE`.
2. Optionally, bind query parameters with`dbBind()` or `dbBindArrow()`.
This is required only if the query contains placeholders such as `?`
or `\$1`, depending on the database backend.
3. Optionally, use `dbGetRowsAffected()` to retrieve the number of rows
affected by the query.
4. Repeat the last two steps as necessary.
5. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### Failure modes
An attempt to close an already closed result set issues a warning for
`dbSendQuery()`, `dbSendStatement()`, and `dbSendQueryArrow()`,
### Specification
`dbClearResult()` frees all resources associated with retrieving the
result of a query or update operation. The DBI backend can expect a call
to `dbClearResult()` for each `dbSendQuery()` or `dbSendStatement()`
call.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
rs <- dbSendQuery(con, "SELECT 1")
print(dbFetch(rs))
dbClearResult(rs)
dbDisconnect(con)
```
## Bind values to a parameterized/prepared statement
<span id="topic+dbBind"></span> <span id="topic+dbBindArrow"></span>
This section describes the behavior of the following methods:
``` r
dbBind(res, params, ...)
dbBindArrow(res, params, ...)
```
### Description
For parametrized or prepared statements, the `dbSendQuery()`,
`dbSendQueryArrow()`, and `dbSendStatement()` functions can be called
with statements that contain placeholders for values. The `dbBind()` and
`dbBindArrow()` functions bind these placeholders to actual values, and
are intended to be called on the result set before calling `dbFetch()`
or `dbFetchArrow()`. The values are passed to `dbBind()` as lists or
data frames, and to `dbBindArrow()` as a stream created by
`nanoarrow::as_nanoarrow_array_stream()`.
[![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental)
`dbBindArrow()` is experimental, as are the other `*Arrow` functions.
`dbSendQuery()` is compatible with `dbBindArrow()`, and
`dbSendQueryArrow()` is compatible with `dbBind()`.
### Arguments
| | |
|----|----|
| `res` | An object inheriting from DBIResult. |
| `params` | For `dbBind()`, a list of values, named or unnamed, or a data frame, with one element/column per query parameter. For `dbBindArrow()`, values as a nanoarrow stream, with one column per query parameter. |
| `...` | Other arguments passed on to methods. |
### Details
<span class="pkg">DBI</span> supports parametrized (or prepared) queries
and statements via the `dbBind()` and `dbBindArrow()` generics.
Parametrized queries are different from normal queries in that they
allow an arbitrary number of placeholders, which are later substituted
by actual values. Parametrized queries (and statements) serve two
purposes:
- The same query can be executed more than once with different values.
The DBMS may cache intermediate information for the query, such as the
execution plan, and execute it faster.
- Separation of query syntax and parameters protects against SQL
injection.
The placeholder format is currently not specified by
<span class="pkg">DBI</span>; in the future, a uniform placeholder
syntax may be supported. Consult the backend documentation for the
supported formats. For automated testing, backend authors specify the
placeholder syntax with the `placeholder_pattern` tweak. Known examples
are:
- `?` (positional matching in order of appearance) in
<span class="pkg">RMariaDB</span> and <span class="pkg">RSQLite</span>
- `\$1` (positional matching by index) in
<span class="pkg">RPostgres</span> and
<span class="pkg">RSQLite</span>
- `:name` and `\$name` (named matching) in
<span class="pkg">RSQLite</span>
### Value
`dbBind()` returns the result set, invisibly, for queries issued by
`dbSendQuery()` or `dbSendQueryArrow()` and also for data manipulation
statements issued by `dbSendStatement()`.
### The data retrieval flow
This section gives a complete overview over the flow for the execution
of queries that return tabular data as data frames.
Most of this flow, except repeated calling of `dbBind()` or
`dbBindArrow()`, is implemented by `dbGetQuery()`, which should be
sufficient unless you want to access the results in a paged way or you
have a parameterized query that you want to reuse. This flow requires an
active connection established by `dbConnect()`. See also
`vignette("dbi-advanced")` for a walkthrough.
1. Use `dbSendQuery()` to create a result set object of class
DBIResult.
2. Optionally, bind query parameters with `dbBind()` or
`dbBindArrow()`. This is required only if the query contains
placeholders such as `?` or `\$1`, depending on the database
backend.
3. Optionally, use `dbColumnInfo()` to retrieve the structure of the
result set without retrieving actual data.
4. Use `dbFetch()` to get the entire result set, a page of results, or
the remaining rows. Fetching zero rows is also possible to retrieve
the structure of the result set as a data frame. This step can be
called multiple times. Only forward paging is supported, you need to
cache previous pages if you need to navigate backwards.
5. Use `dbHasCompleted()` to tell when you're done. This method returns
`TRUE` if no more rows are available for fetching.
6. Repeat the last four steps as necessary.
7. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### The data retrieval flow for Arrow streams
This section gives a complete overview over the flow for the execution
of queries that return tabular data as an Arrow stream.
Most of this flow, except repeated calling of `dbBindArrow()` or
`dbBind()`, is implemented by `dbGetQueryArrow()`, which should be
sufficient unless you have a parameterized query that you want to reuse.
This flow requires an active connection established by `dbConnect()`.
See also `vignette("dbi-advanced")` for a walkthrough.
1. Use `dbSendQueryArrow()` to create a result set object of class
DBIResultArrow.
2. Optionally, bind query parameters with `dbBindArrow()` or
`dbBind()`. This is required only if the query contains placeholders
such as `?` or `\$1`, depending on the database backend.
3. Use `dbFetchArrow()` to get a data stream.
4. Repeat the last two steps as necessary.
5. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### The command execution flow
This section gives a complete overview over the flow for the execution
of SQL statements that have side effects such as stored procedures,
inserting or deleting data, or setting database or connection options.
Most of this flow, except repeated calling of `dbBindArrow()`, is
implemented by `dbExecute()`, which should be sufficient for
non-parameterized queries. This flow requires an active connection
established by `dbConnect()`. See also `vignette("dbi-advanced")` for a
walkthrough.
1. Use `dbSendStatement()` to create a result set object of class
DBIResult. For some queries you need to pass `immediate = TRUE`.
2. Optionally, bind query parameters with`dbBind()` or `dbBindArrow()`.
This is required only if the query contains placeholders such as `?`
or `\$1`, depending on the database backend.
3. Optionally, use `dbGetRowsAffected()` to retrieve the number of rows
affected by the query.
4. Repeat the last two steps as necessary.
5. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### Failure modes
Calling `dbBind()` for a query without parameters raises an error.
Binding too many or not enough values, or parameters with wrong names or
unequal length, also raises an error. If the placeholders in the query
are named, all parameter values must have names (which must not be empty
or `NA`), and vice versa, otherwise an error is raised. The behavior for
mixing placeholders of different types (in particular mixing positional
and named placeholders) is not specified.
Calling `dbBind()` on a result set already cleared by `dbClearResult()`
also raises an error.
### Specification
<span class="pkg">DBI</span> clients execute parametrized statements as
follows:
1. Call `dbSendQuery()`, `dbSendQueryArrow()` or `dbSendStatement()`
with a query or statement that contains placeholders, store the
returned DBIResult object in a variable. Mixing placeholders (in
particular, named and unnamed ones) is not recommended. It is good
practice to register a call to `dbClearResult()` via `on.exit()`
right after calling `dbSendQuery()` or `dbSendStatement()` (see the
last enumeration item). Until `dbBind()` or `dbBindArrow()` have
been called, the returned result set object has the following
behavior:
- `dbFetch()` raises an error (for `dbSendQuery()` and
`dbSendQueryArrow()`)
- `dbGetRowCount()` returns zero (for `dbSendQuery()` and
`dbSendQueryArrow()`)
- `dbGetRowsAffected()` returns an integer `NA` (for
`dbSendStatement()`)
- `dbIsValid()` returns `TRUE`
- `dbHasCompleted()` returns `FALSE`
2. Call `dbBind()` or `dbBindArrow()`:
- For `dbBind()`, the `params` argument must be a list where all
elements have the same lengths and contain values supported by the
backend. A data.frame is internally stored as such a list.
- For `dbBindArrow()`, the `params` argument must be a nanoarrow
array stream, with one column per query parameter.
3. Retrieve the data or the number of affected rows from the
`DBIResult` object.
- For queries issued by `dbSendQuery()` or `dbSendQueryArrow()`,
call `dbFetch()`.
- For statements issued by `dbSendStatements()`, call
`dbGetRowsAffected()`. (Execution begins immediately after the
`dbBind()` call, the statement is processed entirely before the
function returns.)
4. Repeat 2. and 3. as necessary.
5. Close the result set via `dbClearResult()`.
The elements of the `params` argument do not need to be scalars, vectors
of arbitrary length (including length 0) are supported. For queries,
calling `dbFetch()` binding such parameters returns concatenated
results, equivalent to binding and fetching for each set of values and
connecting via `rbind()`. For data manipulation statements,
`dbGetRowsAffected()` returns the total number of rows affected if
binding non-scalar parameters. `dbBind()` also accepts repeated calls on
the same result set for both queries and data manipulation statements,
even if no results are fetched between calls to `dbBind()`, for both
queries and data manipulation statements.
If the placeholders in the query are named, their order in the `params`
argument is not important.
At least the following data types are accepted on input (including NA):
- integer
- numeric
- logical for Boolean values
- character (also with special characters such as spaces, newlines,
quotes, and backslashes)
- factor (bound as character, with warning)
- Date (also when stored internally as integer)
- POSIXct timestamps
- POSIXlt timestamps
- difftime values (also with units other than seconds and with the value
stored as integer)
- lists of raw for blobs (with `NULL` entries for SQL NULL values)
- objects of type blob::blob
### Examples
``` r
# Data frame flow:
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "iris", iris)
# Using the same query for different values
iris_result <- dbSendQuery(con, "SELECT * FROM iris WHERE [Petal.Width] > ?")
dbBind(iris_result, list(2.3))
dbFetch(iris_result)
dbBind(iris_result, list(3))
dbFetch(iris_result)
dbClearResult(iris_result)
# Executing the same statement with different values at once
iris_result <- dbSendStatement(con, "DELETE FROM iris WHERE [Species] = \$species")
dbBind(iris_result, list(species = c("setosa", "versicolor", "unknown")))
dbGetRowsAffected(iris_result)
dbClearResult(iris_result)
nrow(dbReadTable(con, "iris"))
dbDisconnect(con)
# Arrow flow:
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "iris", iris)
# Using the same query for different values
iris_result <- dbSendQueryArrow(con, "SELECT * FROM iris WHERE [Petal.Width] > ?")
dbBindArrow(
iris_result,
nanoarrow::as_nanoarrow_array_stream(data.frame(2.3, fix.empty.names = FALSE))
)
as.data.frame(dbFetchArrow(iris_result))
dbBindArrow(
iris_result,
nanoarrow::as_nanoarrow_array_stream(data.frame(3, fix.empty.names = FALSE))
)
as.data.frame(dbFetchArrow(iris_result))
dbClearResult(iris_result)
# Executing the same statement with different values at once
iris_result <- dbSendStatement(con, "DELETE FROM iris WHERE [Species] = \$species")
dbBindArrow(iris_result, nanoarrow::as_nanoarrow_array_stream(data.frame(
species = c("setosa", "versicolor", "unknown")
)))
dbGetRowsAffected(iris_result)
dbClearResult(iris_result)
nrow(dbReadTable(con, "iris"))
dbDisconnect(con)
```
## Retrieve results from a query
<span id="topic+dbGetQuery"></span>
This section describes the behavior of the following method:
``` r
dbGetQuery(conn, statement, ...)
```
### Description
Returns the result of a query as a data frame. `dbGetQuery()` comes with
a default implementation (which should work with most backends) that
calls `dbSendQuery()`, then `dbFetch()`, ensuring that the result is
always freed by `dbClearResult()`. For retrieving chunked/paged results
or for passing query parameters, see `dbSendQuery()`, in particular the
"The data retrieval flow" section. For retrieving results as an Arrow
object, see `dbGetQueryArrow()`.
### Arguments
| | |
|-------------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `statement` | a character string containing SQL. |
| `...` | Other parameters passed on to methods. |
### Additional arguments
The following arguments are not part of the `dbGetQuery()` generic (to
improve compatibility across backends) but are part of the DBI
specification:
- `n` (default: -1)
- `params` (default: `NULL`)
- `immediate` (default: `NULL`)
They must be provided as named arguments. See the "Specification" and
"Value" sections for details on their usage.
### Specification
A column named `row_names` is treated like any other column.
The `n` argument specifies the number of rows to be fetched. If omitted,
fetching multi-row queries with one or more columns returns the entire
result. A value of Inf for the `n` argument is supported and also
returns the full result. If more rows than available are fetched (by
passing a too large value for `n`), the result is returned in full
without warning. If zero rows are requested, the columns of the data
frame are still fully typed. Fetching fewer rows than available is
permitted, no warning is issued.
The `param` argument allows passing query parameters, see `dbBind()` for
details.
### Specification for the `immediate` argument
The `immediate` argument supports distinguishing between "direct" and
"prepared" APIs offered by many database drivers. Passing
`immediate = TRUE` leads to immediate execution of the query or
statement, via the "direct" API (if supported by the driver). The
default `NULL` means that the backend should choose whatever API makes
the most sense for the database, and (if relevant) tries the other API
if the first attempt fails. A successful second attempt should result in
a message that suggests passing the correct `immediate` argument.
Examples for possible behaviors:
1. DBI backend defaults to `immediate = TRUE` internally
1. A query without parameters is passed: query is executed
2. A query with parameters is passed:
1. `params` not given: rejected immediately by the database
because of a syntax error in the query, the backend tries
`immediate = FALSE` (and gives a message)
2. `params` given: query is executed using `immediate = FALSE`
2. DBI backend defaults to `immediate = FALSE` internally
1. A query without parameters is passed:
1. simple query: query is executed
2. "special" query (such as setting a config options): fails,
the backend tries `immediate = TRUE` (and gives a message)
2. A query with parameters is passed:
1. `params` not given: waiting for parameters via `dbBind()`
2. `params` given: query is executed
### Details
This method is for `SELECT` queries only (incl. other SQL statements
that return a `SELECT`-alike result, e.g., execution of a stored
procedure or data manipulation queries like
`INSERT INTO ... RETURNING ...`). To execute a stored procedure that
does not return a result set, use `dbExecute()`.
Some backends may support data manipulation statements through this
method for compatibility reasons. However, callers are strongly advised
to use `dbExecute()` for data manipulation statements.
### Value
`dbGetQuery()` always returns a data.frame, with as many rows as records
were fetched and as many columns as fields in the result set, even if
the result is a single value or has one or zero rows.
### Implementation notes
Subclasses should override this method only if they provide some sort of
performance optimization.
### Failure modes
An error is raised when issuing a query over a closed or invalid
connection, if the syntax of the query is invalid, or if the query is
not a non-`NA` string. If the `n` argument is not an atomic whole number
greater or equal to -1 or Inf, an error is raised, but a subsequent call
to `dbGetQuery()` with proper `n` argument succeeds.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
dbGetQuery(con, "SELECT * FROM mtcars")
dbGetQuery(con, "SELECT * FROM mtcars", n = 6)
# Pass values using the param argument:
# (This query runs eight times, once for each different
# parameter. The resulting rows are combined into a single
# data frame.)
dbGetQuery(
con,
"SELECT COUNT(*) FROM mtcars WHERE cyl = ?",
params = list(1:8)
)
dbDisconnect(con)
```
## Execute a data manipulation statement on a given database connection
<span id="topic+dbSendStatement"></span>
This section describes the behavior of the following method:
``` r
dbSendStatement(conn, statement, ...)
```
### Description
The `dbSendStatement()` method only submits and synchronously executes
the SQL data manipulation statement (e.g., `UPDATE`, `DELETE`,
`INSERT INTO`, `DROP TABLE`, ...) to the database engine. To query the
number of affected rows, call `dbGetRowsAffected()` on the returned
result object. You must also call `dbClearResult()` after that. For
interactive use, you should almost always prefer `dbExecute()`.
### Arguments
| | |
|-------------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `statement` | a character string containing SQL. |
| `...` | Other parameters passed on to methods. |
### Additional arguments
The following arguments are not part of the `dbSendStatement()` generic
(to improve compatibility across backends) but are part of the DBI
specification:
- `params` (default: `NULL`)
- `immediate` (default: `NULL`)
They must be provided as named arguments. See the "Specification"
sections for details on their usage.
### Specification
No warnings occur under normal conditions. When done, the DBIResult
object must be cleared with a call to `dbClearResult()`. Failure to
clear the result set leads to a warning when the connection is closed.
If the backend supports only one open result set per connection, issuing
a second query invalidates an already open result set and raises a
warning. The newly opened result set is valid and must be cleared with
`dbClearResult()`.
The `param` argument allows passing query parameters, see `dbBind()` for
details.
### Specification for the `immediate` argument
The `immediate` argument supports distinguishing between "direct" and
"prepared" APIs offered by many database drivers. Passing
`immediate = TRUE` leads to immediate execution of the query or
statement, via the "direct" API (if supported by the driver). The
default `NULL` means that the backend should choose whatever API makes
the most sense for the database, and (if relevant) tries the other API
if the first attempt fails. A successful second attempt should result in
a message that suggests passing the correct `immediate` argument.
Examples for possible behaviors:
1. DBI backend defaults to `immediate = TRUE` internally
1. A query without parameters is passed: query is executed
2. A query with parameters is passed:
1. `params` not given: rejected immediately by the database
because of a syntax error in the query, the backend tries
`immediate = FALSE` (and gives a message)
2. `params` given: query is executed using `immediate = FALSE`
2. DBI backend defaults to `immediate = FALSE` internally
1. A query without parameters is passed:
1. simple query: query is executed
2. "special" query (such as setting a config options): fails,
the backend tries `immediate = TRUE` (and gives a message)
2. A query with parameters is passed:
1. `params` not given: waiting for parameters via `dbBind()`
2. `params` given: query is executed
### Details
`dbSendStatement()` comes with a default implementation that simply
forwards to `dbSendQuery()`, to support backends that only implement the
latter.
### Value
`dbSendStatement()` returns an S4 object that inherits from DBIResult.
The result set can be used with `dbGetRowsAffected()` to determine the
number of rows affected by the query. Once you have finished using a
result, make sure to clear it with `dbClearResult()`.
### The command execution flow
This section gives a complete overview over the flow for the execution
of SQL statements that have side effects such as stored procedures,
inserting or deleting data, or setting database or connection options.
Most of this flow, except repeated calling of `dbBindArrow()`, is
implemented by `dbExecute()`, which should be sufficient for
non-parameterized queries. This flow requires an active connection
established by `dbConnect()`. See also `vignette("dbi-advanced")` for a
walkthrough.
1. Use `dbSendStatement()` to create a result set object of class
DBIResult. For some queries you need to pass `immediate = TRUE`.
2. Optionally, bind query parameters with`dbBind()` or `dbBindArrow()`.
This is required only if the query contains placeholders such as `?`
or `\$1`, depending on the database backend.
3. Optionally, use `dbGetRowsAffected()` to retrieve the number of rows
affected by the query.
4. Repeat the last two steps as necessary.
5. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### Failure modes
An error is raised when issuing a statement over a closed or invalid
connection, or if the statement is not a non-`NA` string. An error is
also raised if the syntax of the query is invalid and all query
parameters are given (by passing the `params` argument) or the
`immediate` argument is set to `TRUE`.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "cars", head(cars, 3))
rs <- dbSendStatement(
con,
"INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)"
)
dbHasCompleted(rs)
dbGetRowsAffected(rs)
dbClearResult(rs)
dbReadTable(con, "cars") # there are now 6 rows
# Pass one set of values directly using the param argument:
rs <- dbSendStatement(
con,
"INSERT INTO cars (speed, dist) VALUES (?, ?)",
params = list(4L, 5L)
)
dbClearResult(rs)
# Pass multiple sets of values using dbBind():
rs <- dbSendStatement(
con,
"INSERT INTO cars (speed, dist) VALUES (?, ?)"
)
dbBind(rs, list(5:6, 6:7))
dbBind(rs, list(7L, 8L))
dbClearResult(rs)
dbReadTable(con, "cars") # there are now 10 rows
dbDisconnect(con)
```
## Change database state
<span id="topic+dbExecute"></span>
This section describes the behavior of the following method:
``` r
dbExecute(conn, statement, ...)
```
### Description
Executes a statement and returns the number of rows affected.
`dbExecute()` comes with a default implementation (which should work
with most backends) that calls `dbSendStatement()`, then
`dbGetRowsAffected()`, ensuring that the result is always freed by
`dbClearResult()`. For passing query parameters, see `dbBind()`, in
particular the "The command execution flow" section.
### Arguments
| | |
|-------------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `statement` | a character string containing SQL. |
| `...` | Other parameters passed on to methods. |
### Additional arguments
The following arguments are not part of the `dbExecute()` generic (to
improve compatibility across backends) but are part of the DBI
specification:
- `params` (default: `NULL`)
- `immediate` (default: `NULL`)
They must be provided as named arguments. See the "Specification"
sections for details on their usage.
### Specification
The `param` argument allows passing query parameters, see `dbBind()` for
details.
### Specification for the `immediate` argument
The `immediate` argument supports distinguishing between "direct" and
"prepared" APIs offered by many database drivers. Passing
`immediate = TRUE` leads to immediate execution of the query or
statement, via the "direct" API (if supported by the driver). The
default `NULL` means that the backend should choose whatever API makes
the most sense for the database, and (if relevant) tries the other API
if the first attempt fails. A successful second attempt should result in
a message that suggests passing the correct `immediate` argument.
Examples for possible behaviors:
1. DBI backend defaults to `immediate = TRUE` internally
1. A query without parameters is passed: query is executed
2. A query with parameters is passed:
1. `params` not given: rejected immediately by the database
because of a syntax error in the query, the backend tries
`immediate = FALSE` (and gives a message)
2. `params` given: query is executed using `immediate = FALSE`
2. DBI backend defaults to `immediate = FALSE` internally
1. A query without parameters is passed:
1. simple query: query is executed
2. "special" query (such as setting a config options): fails,
the backend tries `immediate = TRUE` (and gives a message)
2. A query with parameters is passed:
1. `params` not given: waiting for parameters via `dbBind()`
2. `params` given: query is executed
### Details
You can also use `dbExecute()` to call a stored procedure that performs
data manipulation or other actions that do not return a result set. To
execute a stored procedure that returns a result set, or a data
manipulation query that also returns a result set such as
`INSERT INTO ... RETURNING ...`, use `dbGetQuery()` instead.
### Value
`dbExecute()` always returns a scalar numeric that specifies the number
of rows affected by the statement.
### Implementation notes
Subclasses should override this method only if they provide some sort of
performance optimization.
### Failure modes
An error is raised when issuing a statement over a closed or invalid
connection, if the syntax of the statement is invalid, or if the
statement is not a non-`NA` string.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "cars", head(cars, 3))
dbReadTable(con, "cars") # there are 3 rows
dbExecute(
con,
"INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)"
)
dbReadTable(con, "cars") # there are now 6 rows
# Pass values using the param argument:
dbExecute(
con,
"INSERT INTO cars (speed, dist) VALUES (?, ?)",
params = list(4:7, 5:8)
)
dbReadTable(con, "cars") # there are now 10 rows
dbDisconnect(con)
```
## Quote literal strings
<span id="topic+dbQuoteString"></span>
This section describes the behavior of the following method:
``` r
dbQuoteString(conn, x, ...)
```
### Description
Call this method to generate a string that is suitable for use in a
query as a string literal, to make sure that you generate valid SQL and
protect against SQL injection attacks.
### Arguments
| | |
|--------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `x` | A character vector to quote as string. |
| `...` | Other arguments passed on to methods. |
### Value
`dbQuoteString()` returns an object that can be coerced to character, of
the same length as the input. For an empty character vector this
function returns a length-0 object.
When passing the returned object again to `dbQuoteString()` as `x`
argument, it is returned unchanged. Passing objects of class SQL should
also return them unchanged. (For backends it may be most convenient to
return SQL objects to achieve this behavior, but this is not required.)
### Failure modes
Passing a numeric, integer, logical, or raw vector, or a list for the
`x` argument raises an error.
### Specification
The returned expression can be used in a `SELECT ...` query, and for any
scalar character `x` the value of
`dbGetQuery(paste0("SELECT ", dbQuoteString(x)))[[1]]` must be identical
to `x`, even if `x` contains spaces, tabs, quotes (single or double),
backticks, or newlines (in any combination) or is itself the result of a
`dbQuoteString()` call coerced back to character (even repeatedly). If
`x` is `NA`, the result must merely satisfy `is.na()`. The strings
`"NA"` or `"NULL"` are not treated specially.
`NA` should be translated to an unquoted SQL `NULL`, so that the query
`SELECT * FROM (SELECT 1) a WHERE ... IS NULL` returns one row.
### Examples
``` r
# Quoting ensures that arbitrary input is safe for use in a query
name <- "Robert'); DROP TABLE Students;--"
dbQuoteString(ANSI(), name)
# NAs become NULL
dbQuoteString(ANSI(), c("x", NA))
# SQL vectors are always passed through as is
var_name <- SQL("select")
var_name
dbQuoteString(ANSI(), var_name)
# This mechanism is used to prevent double escaping
dbQuoteString(ANSI(), dbQuoteString(ANSI(), name))
```
## Quote literal values
<span id="topic+dbQuoteLiteral"></span>
This section describes the behavior of the following method:
``` r
dbQuoteLiteral(conn, x, ...)
```
### Description
Call these methods to generate a string that is suitable for use in a
query as a literal value of the correct type, to make sure that you
generate valid SQL and protect against SQL injection attacks.
### Arguments
| | |
|--------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `x` | A vector to quote as string. |
| `...` | Other arguments passed on to methods. |
### Value
`dbQuoteLiteral()` returns an object that can be coerced to character,
of the same length as the input. For an empty integer, numeric,
character, logical, date, time, or blob vector, this function returns a
length-0 object.
When passing the returned object again to `dbQuoteLiteral()` as `x`
argument, it is returned unchanged. Passing objects of class SQL should
also return them unchanged. (For backends it may be most convenient to
return SQL objects to achieve this behavior, but this is not required.)
### Failure modes
Passing a list for the `x` argument raises an error.
### Specification
The returned expression can be used in a `SELECT ...` query, and the
value of `dbGetQuery(paste0("SELECT ", dbQuoteLiteral(x)))[[1]]` must be
equal to `x` for any scalar integer, numeric, string, and logical. If
`x` is `NA`, the result must merely satisfy `is.na()`. The literals
`"NA"` or `"NULL"` are not treated specially.
`NA` should be translated to an unquoted SQL `NULL`, so that the query
`SELECT * FROM (SELECT 1) a WHERE ... IS NULL` returns one row.
### Examples
``` r
# Quoting ensures that arbitrary input is safe for use in a query
name <- "Robert'); DROP TABLE Students;--"
dbQuoteLiteral(ANSI(), name)
# NAs become NULL
dbQuoteLiteral(ANSI(), c(1:3, NA))
# Logicals become integers by default
dbQuoteLiteral(ANSI(), c(TRUE, FALSE, NA))
# Raw vectors become hex strings by default
dbQuoteLiteral(ANSI(), list(as.raw(1:3), NULL))
# SQL vectors are always passed through as is
var_name <- SQL("select")
var_name
dbQuoteLiteral(ANSI(), var_name)
# This mechanism is used to prevent double escaping
dbQuoteLiteral(ANSI(), dbQuoteLiteral(ANSI(), name))
```
## Quote identifiers
<span id="topic+dbQuoteIdentifier"></span>
This section describes the behavior of the following method:
``` r
dbQuoteIdentifier(conn, x, ...)
```
### Description
Call this method to generate a string that is suitable for use in a
query as a column or table name, to make sure that you generate valid
SQL and protect against SQL injection attacks. The inverse operation is
`dbUnquoteIdentifier()`.
### Arguments
| | |
|--------|--------------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `x` | A character vector, SQL or Id object to quote as identifier. |
| `...` | Other arguments passed on to methods. |
### Value
`dbQuoteIdentifier()` returns an object that can be coerced to
character, of the same length as the input. For an empty character
vector this function returns a length-0 object. The names of the input
argument are preserved in the output. When passing the returned object
again to `dbQuoteIdentifier()` as `x` argument, it is returned
unchanged. Passing objects of class SQL should also return them
unchanged. (For backends it may be most convenient to return SQL objects
to achieve this behavior, but this is not required.)
### Failure modes
An error is raised if the input contains `NA`, but not for an empty
string.
### Specification
Calling `dbGetQuery()` for a query of the format `SELECT 1 AS ...`
returns a data frame with the identifier, unquoted, as column name.
Quoted identifiers can be used as table and column names in SQL queries,
in particular in queries like `SELECT 1 AS ...` and
`SELECT * FROM (SELECT 1) ...`. The method must use a quoting mechanism
that is unambiguously different from the quoting mechanism used for
strings, so that a query like `SELECT ... FROM (SELECT 1 AS ...)` throws
an error if the column names do not match.
The method can quote column names that contain special characters such
as a space, a dot, a comma, or quotes used to mark strings or
identifiers, if the database supports this. In any case, checking the
validity of the identifier should be performed only when executing a
query, and not by `dbQuoteIdentifier()`.
### Examples
``` r
# Quoting ensures that arbitrary input is safe for use in a query
name <- "Robert'); DROP TABLE Students;--"
dbQuoteIdentifier(ANSI(), name)
# Use Id() to specify other components such as the schema
id_name <- Id(schema = "schema_name", table = "table_name")
id_name
dbQuoteIdentifier(ANSI(), id_name)
# SQL vectors are always passed through as is
var_name <- SQL("select")
var_name
dbQuoteIdentifier(ANSI(), var_name)
# This mechanism is used to prevent double escaping
dbQuoteIdentifier(ANSI(), dbQuoteIdentifier(ANSI(), name))
```
## Unquote identifiers
<span id="topic+dbUnquoteIdentifier"></span>
This section describes the behavior of the following method:
``` r
dbUnquoteIdentifier(conn, x, ...)
```
### Description
Call this method to convert a SQL object created by
`dbQuoteIdentifier()` back to a list of Id objects.
### Arguments
| | |
|--------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `x` | An SQL or Id object. |
| `...` | Other arguments passed on to methods. |
### Value
`dbUnquoteIdentifier()` returns a list of objects of the same length as
the input. For an empty vector, this function returns a length-0 object.
The names of the input argument are preserved in the output. If `x` is a
value returned by `dbUnquoteIdentifier()`, calling
`dbUnquoteIdentifier(..., dbQuoteIdentifier(..., x))` returns `list(x)`.
If `x` is an object of class Id, calling `dbUnquoteIdentifier(..., x)`
returns `list(x)`. (For backends it may be most convenient to return Id
objects to achieve this behavior, but this is not required.)
Plain character vectors can also be passed to `dbUnquoteIdentifier()`.
### Failure modes
An error is raised if a character vectors with a missing value is passed
as the `x` argument.
### Specification
For any character vector of length one, quoting (with
`dbQuoteIdentifier()`) then unquoting then quoting the first element is
identical to just quoting. This is also true for strings that contain
special characters such as a space, a dot, a comma, or quotes used to
mark strings or identifiers, if the database supports this.
Unquoting simple strings (consisting of only letters) wrapped with
`SQL()` and then quoting via `dbQuoteIdentifier()` gives the same result
as just quoting the string. Similarly, unquoting expressions of the form
`SQL("schema.table")` and then quoting gives the same result as quoting
the identifier constructed by `Id("schema", "table")`.
### Examples
``` r
# Unquoting allows to understand the structure of a
# possibly complex quoted identifier
dbUnquoteIdentifier(
ANSI(),
SQL(c('"Catalog"."Schema"."Table"', '"Schema"."Table"', '"UnqualifiedTable"'))
)
# The returned object is always a list,
# also for Id objects
dbUnquoteIdentifier(ANSI(), Id("Catalog", "Schema", "Table"))
# Quoting and unquoting are inverses
dbQuoteIdentifier(
ANSI(),
dbUnquoteIdentifier(ANSI(), SQL("UnqualifiedTable"))[[1]]
)
dbQuoteIdentifier(
ANSI(),
dbUnquoteIdentifier(ANSI(), Id("Schema", "Table"))[[1]]
)
```
## Read database tables as data frames
<span id="topic+dbReadTable"></span>
This section describes the behavior of the following method:
``` r
dbReadTable(conn, name, ...)
```
### Description
Reads a database table to a data frame, optionally converting a column
to row names and converting the column names to valid R identifiers. Use
`dbReadTableArrow()` instead to obtain an Arrow object.
### Arguments
<table role="presentation">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr>
<td><code id="dbReadTable_+3A_conn">conn</code></td>
<td><p>A DBIConnection object, as returned by
<code>dbConnect()</code>.</p></td>
</tr>
<tr>
<td><code id="dbReadTable_+3A_name">name</code></td>
<td><p>The table name, passed on to <code>dbQuoteIdentifier()</code>.
Options are:</p>
<ul>
<li><p>a character string with the unquoted DBMS table name, e.g.
<code>"table_name"</code>,</p></li>
<li><p>a call to <code>Id()</code> with components to the fully
qualified table name, e.g.
<code>Id(schema = "my_schema", table = "table_name")</code></p></li>
<li><p>a call to <code>SQL()</code> with the quoted and fully qualified
table name given verbatim, e.g.
<code>SQL('"my_schema"."table_name"')</code></p></li>
</ul></td>
</tr>
<tr>
<td><code id="dbReadTable_+3A_...">...</code></td>
<td><p>Other parameters passed on to methods.</p></td>
</tr>
</tbody>
</table>
### Additional arguments
The following arguments are not part of the `dbReadTable()` generic (to
improve compatibility across backends) but are part of the DBI
specification:
- `row.names` (default: `FALSE`)
- `check.names`
They must be provided as named arguments. See the "Value" section for
details on their usage.
### Specification
The `name` argument is processed as follows, to support databases that
allow non-syntactic names for their objects:
- If an unquoted table name as string: `dbReadTable()` will do the
quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)`
- If the result of a call to `dbQuoteIdentifier()`: no more quoting is
done
### Details
This function returns a data frame. Use `dbReadTableArrow()` to obtain
an Arrow object.
### Value
`dbReadTable()` returns a data frame that contains the complete data
from the remote table, effectively the result of calling `dbGetQuery()`
with `SELECT * FROM <name>`.
An empty table is returned as a data frame with zero rows.
The presence of rownames depends on the `row.names` argument, see
`sqlColumnToRownames()` for details:
- If `FALSE` or `NULL`, the returned data frame doesn't have row names.
- If `TRUE`, a column named "row_names" is converted to row names.
<!-- -->
- If `NA`, a column named "row_names" is converted to row names if it
exists, otherwise no translation occurs.
- If a string, this specifies the name of the column in the remote table
that contains the row names.
The default is `row.names = FALSE`.
If the database supports identifiers with special characters, the
columns in the returned data frame are converted to valid R identifiers
if the `check.names` argument is `TRUE`, If `check.names = FALSE`, the
returned table has non-syntactic column names without quotes.
### Failure modes
An error is raised if the table does not exist.
An error is raised if `row.names` is `TRUE` and no "row_names" column
exists,
An error is raised if `row.names` is set to a string and no
corresponding column exists.
An error is raised when calling this method for a closed or invalid
connection. An error is raised if `name` cannot be processed with
`dbQuoteIdentifier()` or if this results in a non-scalar. Unsupported
values for `row.names` and `check.names` (non-scalars, unsupported data
types, `NA` for `check.names`) also raise an error.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars[1:10, ])
dbReadTable(con, "mtcars")
dbDisconnect(con)
```
## Copy data frames to database tables
<span id="topic+dbWriteTable"></span>
This section describes the behavior of the following method:
``` r
dbWriteTable(conn, name, value, ...)
```
### Description
Writes, overwrites or appends a data frame to a database table,
optionally converting row names to a column and specifying SQL data
types for fields.
### Arguments
<table role="presentation">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr>
<td><code id="dbWriteTable_+3A_conn">conn</code></td>
<td><p>A DBIConnection object, as returned by
<code>dbConnect()</code>.</p></td>
</tr>
<tr>
<td><code id="dbWriteTable_+3A_name">name</code></td>
<td><p>The table name, passed on to <code>dbQuoteIdentifier()</code>.
Options are:</p>
<ul>
<li><p>a character string with the unquoted DBMS table name, e.g.
<code>"table_name"</code>,</p></li>
<li><p>a call to <code>Id()</code> with components to the fully
qualified table name, e.g.
<code>Id(schema = "my_schema", table = "table_name")</code></p></li>
<li><p>a call to <code>SQL()</code> with the quoted and fully qualified
table name given verbatim, e.g.
<code>SQL('"my_schema"."table_name"')</code></p></li>
</ul></td>
</tr>
<tr>
<td><code id="dbWriteTable_+3A_value">value</code></td>
<td><p>A data.frame (or coercible to data.frame).</p></td>
</tr>
<tr>
<td><code id="dbWriteTable_+3A_...">...</code></td>
<td><p>Other parameters passed on to methods.</p></td>
</tr>
</tbody>
</table>
### Additional arguments
The following arguments are not part of the `dbWriteTable()` generic (to
improve compatibility across backends) but are part of the DBI
specification:
- `row.names` (default: `FALSE`)
- `overwrite` (default: `FALSE`)
- `append` (default: `FALSE`)
- `field.types` (default: `NULL`)
- `temporary` (default: `FALSE`)
They must be provided as named arguments. See the "Specification" and
"Value" sections for details on their usage.
### Specification
The `name` argument is processed as follows, to support databases that
allow non-syntactic names for their objects:
- If an unquoted table name as string: `dbWriteTable()` will do the
quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)`
- If the result of a call to `dbQuoteIdentifier()`: no more quoting is
done
The `value` argument must be a data frame with a subset of the columns
of the existing table if `append = TRUE`. The order of the columns does
not matter with `append = TRUE`.
If the `overwrite` argument is `TRUE`, an existing table of the same
name will be overwritten. This argument doesn't change behavior if the
table does not exist yet.
If the `append` argument is `TRUE`, the rows in an existing table are
preserved, and the new data are appended. If the table doesn't exist
yet, it is created.
If the `temporary` argument is `TRUE`, the table is not available in a
second connection and is gone after reconnecting. Not all backends
support this argument. A regular, non-temporary table is visible in a
second connection, in a pre-existing connection, and after reconnecting
to the database.
SQL keywords can be used freely in table names, column names, and data.
Quotes, commas, spaces, and other special characters such as newlines
and tabs, can also be used in the data, and, if the database supports
non-syntactic identifiers, also for table names and column names.
The following data types must be supported at least, and be read
identically with `dbReadTable()`:
- integer
- numeric (the behavior for `Inf` and `NaN` is not specified)
- logical
- `NA` as NULL
- 64-bit values (using `"bigint"` as field type); the result can be
- converted to a numeric, which may lose precision,
- converted a character vector, which gives the full decimal
representation
- written to another table and read again unchanged
- character (in both UTF-8 and native encodings), supporting empty
strings before and after a non-empty string
- factor (returned as character)
- list of raw (if supported by the database)
- objects of type blob::blob (if supported by the database)
- date (if supported by the database; returned as `Date`), also for
dates prior to 1970 or 1900 or after 2038
- time (if supported by the database; returned as objects that inherit
from `difftime`)
- timestamp (if supported by the database; returned as `POSIXct`
respecting the time zone but not necessarily preserving the input time
zone), also for timestamps prior to 1970 or 1900 or after 2038
respecting the time zone but not necessarily preserving the input time
zone)
Mixing column types in the same table is supported.
The `field.types` argument must be a named character vector with at most
one entry for each column. It indicates the SQL data type to be used for
a new column. If a column is missed from `field.types`, the type is
inferred from the input data with `dbDataType()`.
The interpretation of rownames depends on the `row.names` argument, see
`sqlRownamesToColumn()` for details:
- If `FALSE` or `NULL`, row names are ignored.
- If `TRUE`, row names are converted to a column named "row_names", even
if the input data frame only has natural row names from 1 to
`nrow(...)`.
- If `NA`, a column named "row_names" is created if the data has custom
row names, no extra column is created in the case of natural row
names.
- If a string, this specifies the name of the column in the remote table
that contains the row names, even if the input data frame only has
natural row names.
The default is `row.names = FALSE`.
### Details
This function expects a data frame. Use `dbWriteTableArrow()` to write
an Arrow object.
This function is useful if you want to create and load a table at the
same time. Use `dbAppendTable()` or `dbAppendTableArrow()` for appending
data to an existing table, `dbCreateTable()` or `dbCreateTableArrow()`
for creating a table, and `dbExistsTable()` and `dbRemoveTable()` for
overwriting tables.
DBI only standardizes writing data frames with `dbWriteTable()`. Some
backends might implement methods that can consume CSV files or other
data formats. For details, see the documentation for the individual
methods.
### Value
`dbWriteTable()` returns `TRUE`, invisibly.
### Failure modes
If the table exists, and both `append` and `overwrite` arguments are
unset, or `append = TRUE` and the data frame with the new data has
different column names, an error is raised; the remote table remains
unchanged.
An error is raised when calling this method for a closed or invalid
connection. An error is also raised if `name` cannot be processed with
`dbQuoteIdentifier()` or if this results in a non-scalar. Invalid values
for the additional arguments `row.names`, `overwrite`, `append`,
`field.types`, and `temporary` (non-scalars, unsupported data types,
`NA`, incompatible values, duplicate or missing names, incompatible
columns) also raise an error.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars[1:5, ])
dbReadTable(con, "mtcars")
dbWriteTable(con, "mtcars", mtcars[6:10, ], append = TRUE)
dbReadTable(con, "mtcars")
dbWriteTable(con, "mtcars", mtcars[1:10, ], overwrite = TRUE)
dbReadTable(con, "mtcars")
# No row names
dbWriteTable(con, "mtcars", mtcars[1:10, ], overwrite = TRUE, row.names = FALSE)
dbReadTable(con, "mtcars")
```
## Create a table in the database
<span id="topic+dbCreateTable"></span>
This section describes the behavior of the following method:
``` r
dbCreateTable(conn, name, fields, ..., row.names = NULL, temporary = FALSE)
```
### Description
The default `dbCreateTable()` method calls `sqlCreateTable()` and
`dbExecute()`. Use `dbCreateTableArrow()` to create a table from an
Arrow schema.
### Arguments
<table role="presentation">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr>
<td><code id="dbCreateTable_+3A_conn">conn</code></td>
<td><p>A DBIConnection object, as returned by
<code>dbConnect()</code>.</p></td>
</tr>
<tr>
<td><code id="dbCreateTable_+3A_name">name</code></td>
<td><p>The table name, passed on to <code>dbQuoteIdentifier()</code>.
Options are:</p>
<ul>
<li><p>a character string with the unquoted DBMS table name, e.g.
<code>"table_name"</code>,</p></li>
<li><p>a call to <code>Id()</code> with components to the fully
qualified table name, e.g.
<code>Id(schema = "my_schema", table = "table_name")</code></p></li>
<li><p>a call to <code>SQL()</code> with the quoted and fully qualified
table name given verbatim, e.g.
<code>SQL('"my_schema"."table_name"')</code></p></li>
</ul></td>
</tr>
<tr>
<td><code id="dbCreateTable_+3A_fields">fields</code></td>
<td><p>Either a character vector or a data frame.</p>
<p>A named character vector: Names are column names, values are types.
Names are escaped with <code>dbQuoteIdentifier()</code>. Field types are
unescaped.</p>
<p>A data frame: field types are generated using
<code>dbDataType()</code>.</p></td>
</tr>
<tr>
<td><code id="dbCreateTable_+3A_...">...</code></td>
<td><p>Other parameters passed on to methods.</p></td>
</tr>
<tr>
<td><code id="dbCreateTable_+3A_row.names">row.names</code></td>
<td><p>Must be <code>NULL</code>.</p></td>
</tr>
<tr>
<td><code id="dbCreateTable_+3A_temporary">temporary</code></td>
<td><p>If <code>TRUE</code>, will generate a temporary table.</p></td>
</tr>
</tbody>
</table>
### Additional arguments
The following arguments are not part of the `dbCreateTable()` generic
(to improve compatibility across backends) but are part of the DBI
specification:
- `temporary` (default: `FALSE`)
They must be provided as named arguments. See the "Specification" and
"Value" sections for details on their usage.
### Specification
The `name` argument is processed as follows, to support databases that
allow non-syntactic names for their objects:
- If an unquoted table name as string: `dbCreateTable()` will do the
quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)`
- If the result of a call to `dbQuoteIdentifier()`: no more quoting is
done
The `value` argument can be:
- a data frame,
- a named list of SQL types
If the `temporary` argument is `TRUE`, the table is not available in a
second connection and is gone after reconnecting. Not all backends
support this argument. A regular, non-temporary table is visible in a
second connection, in a pre-existing connection, and after reconnecting
to the database.
SQL keywords can be used freely in table names, column names, and data.
Quotes, commas, and spaces can also be used for table names and column
names, if the database supports non-syntactic identifiers.
The `row.names` argument must be missing or `NULL`, the default value.
All other values for the `row.names` argument (in particular `TRUE`,
`NA`, and a string) raise an error.
### Details
Backends compliant to ANSI SQL 99 don't need to override it. Backends
with a different SQL syntax can override `sqlCreateTable()`, backends
with entirely different ways to create tables need to override this
method.
The `row.names` argument is not supported by this method. Process the
values with `sqlRownamesToColumn()` before calling this method.
The argument order is different from the `sqlCreateTable()` method, the
latter will be adapted in a later release of DBI.
### Value
`dbCreateTable()` returns `TRUE`, invisibly.
### Failure modes
If the table exists, an error is raised; the remote table remains
unchanged.
An error is raised when calling this method for a closed or invalid
connection. An error is also raised if `name` cannot be processed with
`dbQuoteIdentifier()` or if this results in a non-scalar. Invalid values
for the `row.names` and `temporary` arguments (non-scalars, unsupported
data types, `NA`, incompatible values, duplicate names) also raise an
error.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbCreateTable(con, "iris", iris)
dbReadTable(con, "iris")
dbDisconnect(con)
```
## Insert rows into a table
<span id="topic+dbAppendTable"></span>
This section describes the behavior of the following method:
``` r
dbAppendTable(conn, name, value, ..., row.names = NULL)
```
### Description
The `dbAppendTable()` method assumes that the table has been created
beforehand, e.g. with `dbCreateTable()`. The default implementation
calls `sqlAppendTableTemplate()` and then `dbExecute()` with the `param`
argument. Use `dbAppendTableArrow()` to append data from an Arrow
stream.
### Arguments
<table role="presentation">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr>
<td><code id="dbAppendTable_+3A_conn">conn</code></td>
<td><p>A DBIConnection object, as returned by
<code>dbConnect()</code>.</p></td>
</tr>
<tr>
<td><code id="dbAppendTable_+3A_name">name</code></td>
<td><p>The table name, passed on to <code>dbQuoteIdentifier()</code>.
Options are:</p>
<ul>
<li><p>a character string with the unquoted DBMS table name, e.g.
<code>"table_name"</code>,</p></li>
<li><p>a call to <code>Id()</code> with components to the fully
qualified table name, e.g.
<code>Id(schema = "my_schema", table = "table_name")</code></p></li>
<li><p>a call to <code>SQL()</code> with the quoted and fully qualified
table name given verbatim, e.g.
<code>SQL('"my_schema"."table_name"')</code></p></li>
</ul></td>
</tr>
<tr>
<td><code id="dbAppendTable_+3A_value">value</code></td>
<td><p>A data.frame (or coercible to data.frame).</p></td>
</tr>
<tr>
<td><code id="dbAppendTable_+3A_...">...</code></td>
<td><p>Other parameters passed on to methods.</p></td>
</tr>
<tr>
<td><code id="dbAppendTable_+3A_row.names">row.names</code></td>
<td><p>Must be <code>NULL</code>.</p></td>
</tr>
</tbody>
</table>
### Details
Backends compliant to ANSI SQL 99 which use `?` as a placeholder for
prepared queries don't need to override it. Backends with a different
SQL syntax which use `?` as a placeholder for prepared queries can
override `sqlAppendTable()`. Other backends (with different placeholders
or with entirely different ways to create tables) need to override the
`dbAppendTable()` method.
The `row.names` argument is not supported by this method. Process the
values with `sqlRownamesToColumn()` before calling this method.
### Value
`dbAppendTable()` returns a scalar numeric.
### Failure modes
If the table does not exist, or the new data in `values` is not a data
frame or has different column names, an error is raised; the remote
table remains unchanged.
An error is raised when calling this method for a closed or invalid
connection. An error is also raised if `name` cannot be processed with
`dbQuoteIdentifier()` or if this results in a non-scalar. Invalid values
for the `row.names` argument (non-scalars, unsupported data types, `NA`)
also raise an error.
Passing a `value` argument different to `NULL` to the `row.names`
argument (in particular `TRUE`, `NA`, and a string) raises an error.
### Specification
SQL keywords can be used freely in table names, column names, and data.
Quotes, commas, spaces, and other special characters such as newlines
and tabs, can also be used in the data, and, if the database supports
non-syntactic identifiers, also for table names and column names.
The following data types must be supported at least, and be read
identically with `dbReadTable()`:
- integer
- numeric (the behavior for `Inf` and `NaN` is not specified)
- logical
- `NA` as NULL
- 64-bit values (using `"bigint"` as field type); the result can be
- converted to a numeric, which may lose precision,
- converted a character vector, which gives the full decimal
representation
- written to another table and read again unchanged
- character (in both UTF-8 and native encodings), supporting empty
strings (before and after non-empty strings)
- factor (returned as character, with a warning)
- list of raw (if supported by the database)
- objects of type blob::blob (if supported by the database)
- date (if supported by the database; returned as `Date`) also for dates
prior to 1970 or 1900 or after 2038
- time (if supported by the database; returned as objects that inherit
from `difftime`)
- timestamp (if supported by the database; returned as `POSIXct`
respecting the time zone but not necessarily preserving the input time
zone), also for timestamps prior to 1970 or 1900 or after 2038
respecting the time zone but not necessarily preserving the input time
zone)
Mixing column types in the same table is supported.
The `name` argument is processed as follows, to support databases that
allow non-syntactic names for their objects:
- If an unquoted table name as string: `dbAppendTable()` will do the
quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)`
- If the result of a call to `dbQuoteIdentifier()`: no more quoting is
done to support databases that allow non-syntactic names for their
objects:
The `row.names` argument must be `NULL`, the default value. Row names
are ignored.
The `value` argument must be a data frame with a subset of the columns
of the existing table. The order of the columns does not matter.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbCreateTable(con, "iris", iris)
dbAppendTable(con, "iris", iris)
dbReadTable(con, "iris")
dbDisconnect(con)
```
## Remove a table from the database
<span id="topic+dbRemoveTable"></span>
This section describes the behavior of the following method:
``` r
dbRemoveTable(conn, name, ...)
```
### Description
Remove a remote table (e.g., created by `dbWriteTable()`) from the
database.
### Arguments
<table role="presentation">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr>
<td><code id="dbRemoveTable_+3A_conn">conn</code></td>
<td><p>A DBIConnection object, as returned by
<code>dbConnect()</code>.</p></td>
</tr>
<tr>
<td><code id="dbRemoveTable_+3A_name">name</code></td>
<td><p>The table name, passed on to <code>dbQuoteIdentifier()</code>.
Options are:</p>
<ul>
<li><p>a character string with the unquoted DBMS table name, e.g.
<code>"table_name"</code>,</p></li>
<li><p>a call to <code>Id()</code> with components to the fully
qualified table name, e.g.
<code>Id(schema = "my_schema", table = "table_name")</code></p></li>
<li><p>a call to <code>SQL()</code> with the quoted and fully qualified
table name given verbatim, e.g.
<code>SQL('"my_schema"."table_name"')</code></p></li>
</ul></td>
</tr>
<tr>
<td><code id="dbRemoveTable_+3A_...">...</code></td>
<td><p>Other parameters passed on to methods.</p></td>
</tr>
</tbody>
</table>
### Additional arguments
The following arguments are not part of the `dbRemoveTable()` generic
(to improve compatibility across backends) but are part of the DBI
specification:
- `temporary` (default: `FALSE`)
- `fail_if_missing` (default: `TRUE`)
These arguments must be provided as named arguments.
If `temporary` is `TRUE`, the call to `dbRemoveTable()` will consider
only temporary tables. Not all backends support this argument. In
particular, permanent tables of the same name are left untouched.
If `fail_if_missing` is `FALSE`, the call to `dbRemoveTable()` succeeds
if the table does not exist.
### Specification
A table removed by `dbRemoveTable()` doesn't appear in the list of
tables returned by `dbListTables()`, and `dbExistsTable()` returns
`FALSE`. The removal propagates immediately to other connections to the
same database. This function can also be used to remove a temporary
table.
The `name` argument is processed as follows, to support databases that
allow non-syntactic names for their objects:
- If an unquoted table name as string: `dbRemoveTable()` will do the
quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)`
- If the result of a call to `dbQuoteIdentifier()`: no more quoting is
done
### Value
`dbRemoveTable()` returns `TRUE`, invisibly.
### Failure modes
If the table does not exist, an error is raised. An attempt to remove a
view with this function may result in an error.
An error is raised when calling this method for a closed or invalid
connection. An error is also raised if `name` cannot be processed with
`dbQuoteIdentifier()` or if this results in a non-scalar.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbExistsTable(con, "iris")
dbWriteTable(con, "iris", iris)
dbExistsTable(con, "iris")
dbRemoveTable(con, "iris")
dbExistsTable(con, "iris")
dbDisconnect(con)
```
## List remote tables
<span id="topic+dbListTables"></span>
This section describes the behavior of the following method:
``` r
dbListTables(conn, ...)
```
### Description
Returns the unquoted names of remote tables accessible through this
connection. This should include views and temporary objects, but not all
database backends (in particular <span class="pkg">RMariaDB</span> and
<span class="pkg">RMySQL</span>) support this.
### Arguments
| | |
|--------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `...` | Other parameters passed on to methods. |
### Value
`dbListTables()` returns a character vector that enumerates all tables
and views in the database. Tables added with `dbWriteTable()` are part
of the list. As soon a table is removed from the database, it is also
removed from the list of database tables.
The same applies to temporary tables if supported by the database.
The returned names are suitable for quoting with `dbQuoteIdentifier()`.
### Failure modes
An error is raised when calling this method for a closed or invalid
connection.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbListTables(con)
dbWriteTable(con, "mtcars", mtcars)
dbListTables(con)
dbDisconnect(con)
```
## List field names of a remote table
<span id="topic+dbListFields"></span>
This section describes the behavior of the following method:
``` r
dbListFields(conn, name, ...)
```
### Description
Returns the field names of a remote table as a character vector.
### Arguments
<table role="presentation">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr>
<td><code id="dbListFields_+3A_conn">conn</code></td>
<td><p>A DBIConnection object, as returned by
<code>dbConnect()</code>.</p></td>
</tr>
<tr>
<td><code id="dbListFields_+3A_name">name</code></td>
<td><p>The table name, passed on to <code>dbQuoteIdentifier()</code>.
Options are:</p>
<ul>
<li><p>a character string with the unquoted DBMS table name, e.g.
<code>"table_name"</code>,</p></li>
<li><p>a call to <code>Id()</code> with components to the fully
qualified table name, e.g.
<code>Id(schema = "my_schema", table = "table_name")</code></p></li>
<li><p>a call to <code>SQL()</code> with the quoted and fully qualified
table name given verbatim, e.g.
<code>SQL('"my_schema"."table_name"')</code></p></li>
</ul></td>
</tr>
<tr>
<td><code id="dbListFields_+3A_...">...</code></td>
<td><p>Other parameters passed on to methods.</p></td>
</tr>
</tbody>
</table>
### Value
`dbListFields()` returns a character vector that enumerates all fields
in the table in the correct order. This also works for temporary tables
if supported by the database. The returned names are suitable for
quoting with `dbQuoteIdentifier()`.
### Failure modes
If the table does not exist, an error is raised. Invalid types for the
`name` argument (e.g., `character` of length not equal to one, or
numeric) lead to an error. An error is also raised when calling this
method for a closed or invalid connection.
### Specification
The `name` argument can be
- a string
- the return value of `dbQuoteIdentifier()`
- a value from the `table` column from the return value of
`dbListObjects()` where `is_prefix` is `FALSE`
A column named `row_names` is treated like any other column.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
dbListFields(con, "mtcars")
dbDisconnect(con)
```
## Does a table exist?
<span id="topic+dbExistsTable"></span>
This section describes the behavior of the following method:
``` r
dbExistsTable(conn, name, ...)
```
### Description
Returns if a table given by name exists in the database.
### Arguments
<table role="presentation">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr>
<td><code id="dbExistsTable_+3A_conn">conn</code></td>
<td><p>A DBIConnection object, as returned by
<code>dbConnect()</code>.</p></td>
</tr>
<tr>
<td><code id="dbExistsTable_+3A_name">name</code></td>
<td><p>The table name, passed on to <code>dbQuoteIdentifier()</code>.
Options are:</p>
<ul>
<li><p>a character string with the unquoted DBMS table name, e.g.
<code>"table_name"</code>,</p></li>
<li><p>a call to <code>Id()</code> with components to the fully
qualified table name, e.g.
<code>Id(schema = "my_schema", table = "table_name")</code></p></li>
<li><p>a call to <code>SQL()</code> with the quoted and fully qualified
table name given verbatim, e.g.
<code>SQL('"my_schema"."table_name"')</code></p></li>
</ul></td>
</tr>
<tr>
<td><code id="dbExistsTable_+3A_...">...</code></td>
<td><p>Other parameters passed on to methods.</p></td>
</tr>
</tbody>
</table>
### Value
`dbExistsTable()` returns a logical scalar, `TRUE` if the table or view
specified by the `name` argument exists, `FALSE` otherwise.
This includes temporary tables if supported by the database.
### Failure modes
An error is raised when calling this method for a closed or invalid
connection. An error is also raised if `name` cannot be processed with
`dbQuoteIdentifier()` or if this results in a non-scalar.
### Specification
The `name` argument is processed as follows, to support databases that
allow non-syntactic names for their objects:
- If an unquoted table name as string: `dbExistsTable()` will do the
quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)`
- If the result of a call to `dbQuoteIdentifier()`: no more quoting is
done
For all tables listed by `dbListTables()`, `dbExistsTable()` returns
`TRUE`.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbExistsTable(con, "iris")
dbWriteTable(con, "iris", iris)
dbExistsTable(con, "iris")
dbDisconnect(con)
```
## List remote objects
<span id="topic+dbListObjects"></span>
This section describes the behavior of the following method:
``` r
dbListObjects(conn, prefix = NULL, ...)
```
### Description
Returns the names of remote objects accessible through this connection
as a data frame. This should include temporary objects, but not all
database backends (in particular <span class="pkg">RMariaDB</span> and
<span class="pkg">RMySQL</span>) support this. Compared to
`dbListTables()`, this method also enumerates tables and views in
schemas, and returns fully qualified identifiers to access these
objects. This allows exploration of all database objects available to
the current user, including those that can only be accessed by giving
the full namespace.
### Arguments
| | |
|----|----|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `prefix` | A fully qualified path in the database's namespace, or `NULL`. This argument will be processed with `dbUnquoteIdentifier()`. If given the method will return all objects accessible through this prefix. |
| `...` | Other parameters passed on to methods. |
### Value
`dbListObjects()` returns a data frame with columns `table` and
`is_prefix` (in that order), optionally with other columns with a dot
(`.`) prefix. The `table` column is of type list. Each object in this
list is suitable for use as argument in `dbQuoteIdentifier()`. The
`is_prefix` column is a logical. This data frame contains one row for
each object (schema, table and view) accessible from the prefix (if
passed) or from the global namespace (if prefix is omitted). Tables
added with `dbWriteTable()` are part of the data frame. As soon a table
is removed from the database, it is also removed from the data frame of
database objects.
The same applies to temporary objects if supported by the database.
The returned names are suitable for quoting with `dbQuoteIdentifier()`.
### Failure modes
An error is raised when calling this method for a closed or invalid
connection.
### Specification
The `prefix` column indicates if the `table` value refers to a table or
a prefix. For a call with the default `prefix = NULL`, the `table`
values that have `is_prefix == FALSE` correspond to the tables returned
from `dbListTables()`,
The `table` object can be quoted with `dbQuoteIdentifier()`. The result
of quoting can be passed to `dbUnquoteIdentifier()`. (For backends it
may be convenient to use the Id class, but this is not required.)
Values in `table` column that have `is_prefix == TRUE` can be passed as
the `prefix` argument to another call to `dbListObjects()`. For the data
frame returned from a `dbListObject()` call with the `prefix` argument
set, all `table` values where `is_prefix` is `FALSE` can be used in a
call to `dbExistsTable()` which returns `TRUE`.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbListObjects(con)
dbWriteTable(con, "mtcars", mtcars)
dbListObjects(con)
dbDisconnect(con)
```
## Is this DBMS object still valid?
<span id="topic+dbIsValid"></span>
This section describes the behavior of the following method:
``` r
dbIsValid(dbObj, ...)
```
### Description
This generic tests whether a database object is still valid (i.e. it
hasn't been disconnected or cleared).
### Arguments
| | |
|----|----|
| `dbObj` | An object inheriting from DBIObject, i.e. DBIDriver, DBIConnection, or a DBIResult |
| `...` | Other arguments to methods. |
### Value
`dbIsValid()` returns a logical scalar, `TRUE` if the object specified
by `dbObj` is valid, `FALSE` otherwise. A DBIConnection object is
initially valid, and becomes invalid after disconnecting with
`dbDisconnect()`. For an invalid connection object (e.g., for some
drivers if the object is saved to a file and then restored), the method
also returns `FALSE`. A DBIResult object is valid after a call to
`dbSendQuery()`, and stays valid even after all rows have been fetched;
only clearing it with `dbClearResult()` invalidates it. A DBIResult
object is also valid after a call to `dbSendStatement()`, and stays
valid after querying the number of rows affected; only clearing it with
`dbClearResult()` invalidates it. If the connection to the database
system is dropped (e.g., due to connectivity problems, server failure,
etc.), `dbIsValid()` should return `FALSE`. This is not tested
automatically.
### Examples
``` r
dbIsValid(RSQLite::SQLite())
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbIsValid(con)
rs <- dbSendQuery(con, "SELECT 1")
dbIsValid(rs)
dbClearResult(rs)
dbIsValid(rs)
dbDisconnect(con)
dbIsValid(con)
```
## Completion status
<span id="topic+dbHasCompleted"></span>
This section describes the behavior of the following method:
``` r
dbHasCompleted(res, ...)
```
### Description
This method returns if the operation has completed. A `SELECT` query is
completed if all rows have been fetched. A data manipulation statement
is always completed.
### Arguments
| | |
|-------|---------------------------------------|
| `res` | An object inheriting from DBIResult. |
| `...` | Other arguments passed on to methods. |
### Value
`dbHasCompleted()` returns a logical scalar. For a query initiated by
`dbSendQuery()` with non-empty result set, `dbHasCompleted()` returns
`FALSE` initially and `TRUE` after calling `dbFetch()` without limit.
For a query initiated by `dbSendStatement()`, `dbHasCompleted()` always
returns `TRUE`.
### The data retrieval flow
This section gives a complete overview over the flow for the execution
of queries that return tabular data as data frames.
Most of this flow, except repeated calling of `dbBind()` or
`dbBindArrow()`, is implemented by `dbGetQuery()`, which should be
sufficient unless you want to access the results in a paged way or you
have a parameterized query that you want to reuse. This flow requires an
active connection established by `dbConnect()`. See also
`vignette("dbi-advanced")` for a walkthrough.
1. Use `dbSendQuery()` to create a result set object of class
DBIResult.
2. Optionally, bind query parameters with `dbBind()` or
`dbBindArrow()`. This is required only if the query contains
placeholders such as `?` or `\$1`, depending on the database
backend.
3. Optionally, use `dbColumnInfo()` to retrieve the structure of the
result set without retrieving actual data.
4. Use `dbFetch()` to get the entire result set, a page of results, or
the remaining rows. Fetching zero rows is also possible to retrieve
the structure of the result set as a data frame. This step can be
called multiple times. Only forward paging is supported, you need to
cache previous pages if you need to navigate backwards.
5. Use `dbHasCompleted()` to tell when you're done. This method returns
`TRUE` if no more rows are available for fetching.
6. Repeat the last four steps as necessary.
7. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### Failure modes
Attempting to query completion status for a result set cleared with
`dbClearResult()` gives an error.
### Specification
The completion status for a query is only guaranteed to be set to
`FALSE` after attempting to fetch past the end of the entire result.
Therefore, for a query with an empty result set, the initial return
value is unspecified, but the result value is `TRUE` after trying to
fetch only one row.
Similarly, for a query with a result set of length n, the return value
is unspecified after fetching n rows, but the result value is `TRUE`
after trying to fetch only one more row.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
rs <- dbSendQuery(con, "SELECT * FROM mtcars")
dbHasCompleted(rs)
ret1 <- dbFetch(rs, 10)
dbHasCompleted(rs)
ret2 <- dbFetch(rs)
dbHasCompleted(rs)
dbClearResult(rs)
dbDisconnect(con)
```
## Get the statement associated with a result set
<span id="topic+dbGetStatement"></span>
This section describes the behavior of the following method:
``` r
dbGetStatement(res, ...)
```
### Description
Returns the statement that was passed to `dbSendQuery()` or
`dbSendStatement()`.
### Arguments
| | |
|-------|---------------------------------------|
| `res` | An object inheriting from DBIResult. |
| `...` | Other arguments passed on to methods. |
### Value
`dbGetStatement()` returns a string, the query used in either
`dbSendQuery()` or `dbSendStatement()`.
### Failure modes
Attempting to query the statement for a result set cleared with
`dbClearResult()` gives an error.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
rs <- dbSendQuery(con, "SELECT * FROM mtcars")
dbGetStatement(rs)
dbClearResult(rs)
dbDisconnect(con)
```
## The number of rows fetched so far
<span id="topic+dbGetRowCount"></span>
This section describes the behavior of the following method:
``` r
dbGetRowCount(res, ...)
```
### Description
Returns the total number of rows actually fetched with calls to
`dbFetch()` for this result set.
### Arguments
| | |
|-------|---------------------------------------|
| `res` | An object inheriting from DBIResult. |
| `...` | Other arguments passed on to methods. |
### Value
`dbGetRowCount()` returns a scalar number (integer or numeric), the
number of rows fetched so far. After calling `dbSendQuery()`, the row
count is initially zero. After a call to `dbFetch()` without limit, the
row count matches the total number of rows returned. Fetching a limited
number of rows increases the number of rows by the number of rows
returned, even if fetching past the end of the result set. For queries
with an empty result set, zero is returned even after fetching. For data
manipulation statements issued with `dbSendStatement()`, zero is
returned before and after calling `dbFetch()`.
### Failure modes
Attempting to get the row count for a result set cleared with
`dbClearResult()` gives an error.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
rs <- dbSendQuery(con, "SELECT * FROM mtcars")
dbGetRowCount(rs)
ret1 <- dbFetch(rs, 10)
dbGetRowCount(rs)
ret2 <- dbFetch(rs)
dbGetRowCount(rs)
nrow(ret1) + nrow(ret2)
dbClearResult(rs)
dbDisconnect(con)
```
## The number of rows affected
<span id="topic+dbGetRowsAffected"></span>
This section describes the behavior of the following method:
``` r
dbGetRowsAffected(res, ...)
```
### Description
This method returns the number of rows that were added, deleted, or
updated by a data manipulation statement.
### Arguments
| | |
|-------|---------------------------------------|
| `res` | An object inheriting from DBIResult. |
| `...` | Other arguments passed on to methods. |
### Value
`dbGetRowsAffected()` returns a scalar number (integer or numeric), the
number of rows affected by a data manipulation statement issued with
`dbSendStatement()`. The value is available directly after the call and
does not change after calling `dbFetch()`. `NA_integer_` or
`NA_numeric_` are allowed if the number of rows affected is not known.
For queries issued with `dbSendQuery()`, zero is returned before and
after the call to `dbFetch()`. `NA` values are not allowed.
### The command execution flow
This section gives a complete overview over the flow for the execution
of SQL statements that have side effects such as stored procedures,
inserting or deleting data, or setting database or connection options.
Most of this flow, except repeated calling of `dbBindArrow()`, is
implemented by `dbExecute()`, which should be sufficient for
non-parameterized queries. This flow requires an active connection
established by `dbConnect()`. See also `vignette("dbi-advanced")` for a
walkthrough.
1. Use `dbSendStatement()` to create a result set object of class
DBIResult. For some queries you need to pass `immediate = TRUE`.
2. Optionally, bind query parameters with`dbBind()` or `dbBindArrow()`.
This is required only if the query contains placeholders such as `?`
or `\$1`, depending on the database backend.
3. Optionally, use `dbGetRowsAffected()` to retrieve the number of rows
affected by the query.
4. Repeat the last two steps as necessary.
5. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### Failure modes
Attempting to get the rows affected for a result set cleared with
`dbClearResult()` gives an error.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
rs <- dbSendStatement(con, "DELETE FROM mtcars")
dbGetRowsAffected(rs)
nrow(mtcars)
dbClearResult(rs)
dbDisconnect(con)
```
## Information about result types
<span id="topic+dbColumnInfo"></span>
This section describes the behavior of the following method:
``` r
dbColumnInfo(res, ...)
```
### Description
Produces a data.frame that describes the output of a query. The
data.frame should have as many rows as there are output fields in the
result set, and each column in the data.frame describes an aspect of the
result set field (field name, type, etc.)
### Arguments
| | |
|-------|---------------------------------------|
| `res` | An object inheriting from DBIResult. |
| `...` | Other arguments passed on to methods. |
### Value
`dbColumnInfo()` returns a data frame with at least two columns `"name"`
and `"type"` (in that order) (and optional columns that start with a
dot). The `"name"` and `"type"` columns contain the names and types of
the R columns of the data frame that is returned from `dbFetch()`. The
`"type"` column is of type `character` and only for information. Do not
compute on the `"type"` column, instead use `dbFetch(res, n = 0)` to
create a zero-row data frame initialized with the correct data types.
### The data retrieval flow
This section gives a complete overview over the flow for the execution
of queries that return tabular data as data frames.
Most of this flow, except repeated calling of `dbBind()` or
`dbBindArrow()`, is implemented by `dbGetQuery()`, which should be
sufficient unless you want to access the results in a paged way or you
have a parameterized query that you want to reuse. This flow requires an
active connection established by `dbConnect()`. See also
`vignette("dbi-advanced")` for a walkthrough.
1. Use `dbSendQuery()` to create a result set object of class
DBIResult.
2. Optionally, bind query parameters with `dbBind()` or
`dbBindArrow()`. This is required only if the query contains
placeholders such as `?` or `\$1`, depending on the database
backend.
3. Optionally, use `dbColumnInfo()` to retrieve the structure of the
result set without retrieving actual data.
4. Use `dbFetch()` to get the entire result set, a page of results, or
the remaining rows. Fetching zero rows is also possible to retrieve
the structure of the result set as a data frame. This step can be
called multiple times. Only forward paging is supported, you need to
cache previous pages if you need to navigate backwards.
5. Use `dbHasCompleted()` to tell when you're done. This method returns
`TRUE` if no more rows are available for fetching.
6. Repeat the last four steps as necessary.
7. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### Failure modes
An attempt to query columns for a closed result set raises an error.
### Specification
A column named `row_names` is treated like any other column.
The column names are always consistent with the data returned by
`dbFetch()`.
If the query returns unnamed columns, non-empty and non-`NA` names are
assigned.
Column names that correspond to SQL or R keywords are left unchanged.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
rs <- dbSendQuery(con, "SELECT 1 AS a, 2 AS b")
dbColumnInfo(rs)
dbFetch(rs)
dbClearResult(rs)
dbDisconnect(con)
```
## Begin/commit/rollback SQL transactions
<span id="topic+dbBegin"></span> <span id="topic+dbCommit"></span>
<span id="topic+dbRollback"></span>
<span id="topic+transactions"></span>
This section describes the behavior of the following methods:
``` r
dbBegin(conn, ...)
dbCommit(conn, ...)
dbRollback(conn, ...)
```
### Description
A transaction encapsulates several SQL statements in an atomic unit. It
is initiated with `dbBegin()` and either made persistent with
`dbCommit()` or undone with `dbRollback()`. In any case, the DBMS
guarantees that either all or none of the statements have a permanent
effect. This helps ensuring consistency of write operations to multiple
tables.
### Arguments
| | |
|--------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `...` | Other parameters passed on to methods. |
### Details
Not all database engines implement transaction management, in which case
these methods should not be implemented for the specific DBIConnection
subclass.
### Value
`dbBegin()`, `dbCommit()` and `dbRollback()` return `TRUE`, invisibly.
### Failure modes
The implementations are expected to raise an error in case of failure,
but this is not tested. In any way, all generics throw an error with a
closed or invalid connection. In addition, a call to `dbCommit()` or
`dbRollback()` without a prior call to `dbBegin()` raises an error.
Nested transactions are not supported by DBI, an attempt to call
`dbBegin()` twice yields an error.
### Specification
Actual support for transactions may vary between backends. A transaction
is initiated by a call to `dbBegin()` and committed by a call to
`dbCommit()`. Data written in a transaction must persist after the
transaction is committed. For example, a record that is missing when the
transaction is started but is created during the transaction must exist
both during and after the transaction, and also in a new connection.
A transaction can also be aborted with `dbRollback()`. All data written
in such a transaction must be removed after the transaction is rolled
back. For example, a record that is missing when the transaction is
started but is created during the transaction must not exist anymore
after the rollback.
Disconnection from a connection with an open transaction effectively
rolls back the transaction. All data written in such a transaction must
be removed after the transaction is rolled back.
The behavior is not specified if other arguments are passed to these
functions. In particular, <span class="pkg">RSQLite</span> issues named
transactions with support for nesting if the `name` argument is set.
The transaction isolation level is not specified by DBI.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "cash", data.frame(amount = 100))
dbWriteTable(con, "account", data.frame(amount = 2000))
# All operations are carried out as logical unit:
dbBegin(con)
withdrawal <- 300
dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal))
dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal))
dbCommit(con)
dbReadTable(con, "cash")
dbReadTable(con, "account")
# Rolling back after detecting negative value on account:
dbBegin(con)
withdrawal <- 5000
dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal))
dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal))
if (dbReadTable(con, "account")\$amount >= 0) {
dbCommit(con)
} else {
dbRollback(con)
}
dbReadTable(con, "cash")
dbReadTable(con, "account")
dbDisconnect(con)
```
## Self-contained SQL transactions
<span id="topic+dbWithTransaction"></span>
<span id="topic+dbBreak"></span>
This section describes the behavior of the following methods:
``` r
dbWithTransaction(conn, code, ...)
dbBreak()
```
### Description
Given that transactions are implemented, this function allows you to
pass in code that is run in a transaction. The default method of
`dbWithTransaction()` calls `dbBegin()` before executing the code, and
`dbCommit()` after successful completion, or `dbRollback()` in case of
an error. The advantage is that you don't have to remember to do
`dbBegin()` and `dbCommit()` or `dbRollback()` – that is all taken care
of. The special function `dbBreak()` allows an early exit with rollback,
it can be called only inside `dbWithTransaction()`.
### Arguments
| | |
|--------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `code` | An arbitrary block of R code. |
| `...` | Other parameters passed on to methods. |
### Details
DBI implements `dbWithTransaction()`, backends should need to override
this generic only if they implement specialized handling.
### Value
`dbWithTransaction()` returns the value of the executed code.
### Failure modes
Failure to initiate the transaction (e.g., if the connection is closed
or invalid or if `dbBegin()` has been called already) gives an error.
### Specification
`dbWithTransaction()` initiates a transaction with `dbBegin()`, executes
the code given in the `code` argument, and commits the transaction with
`dbCommit()`. If the code raises an error, the transaction is instead
aborted with `dbRollback()`, and the error is propagated. If the code
calls `dbBreak()`, execution of the code stops and the transaction is
silently aborted. All side effects caused by the code (such as the
creation of new variables) propagate to the calling environment.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "cash", data.frame(amount = 100))
dbWriteTable(con, "account", data.frame(amount = 2000))
# All operations are carried out as logical unit:
dbWithTransaction(
con,
{
withdrawal <- 300
dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal))
dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal))
}
)
# The code is executed as if in the current environment:
withdrawal
# The changes are committed to the database after successful execution:
dbReadTable(con, "cash")
dbReadTable(con, "account")
# Rolling back with dbBreak():
dbWithTransaction(
con,
{
withdrawal <- 5000
dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal))
dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal))
if (dbReadTable(con, "account")\$amount < 0) {
dbBreak()
}
}
)
# These changes were not committed to the database:
dbReadTable(con, "cash")
dbReadTable(con, "account")
dbDisconnect(con)
```
## Get DBMS metadata
<span id="topic+dbGetInfo"></span>
This section describes the behavior of the following method:
``` r
dbGetInfo(dbObj, ...)
```
### Description
Retrieves information on objects of class DBIDriver, DBIConnection or
DBIResult.
### Arguments
| | |
|----|----|
| `dbObj` | An object inheriting from DBIObject, i.e. DBIDriver, DBIConnection, or a DBIResult |
| `...` | Other arguments to methods. |
### Value
For objects of class DBIDriver, `dbGetInfo()` returns a named list that
contains at least the following components:
- `driver.version`: the package version of the DBI backend,
- `client.version`: the version of the DBMS client library.
For objects of class DBIConnection, `dbGetInfo()` returns a named list
that contains at least the following components:
- `db.version`: version of the database server,
- `dbname`: database name,
- `username`: username to connect to the database,
- `host`: hostname of the database server,
- `port`: port on the database server. It must not contain a `password`
component. Components that are not applicable should be set to `NA`.
For objects of class DBIResult, `dbGetInfo()` returns a named list that
contains at least the following components:
- `statatment`: the statement used with `dbSendQuery()` or
`dbExecute()`, as returned by `dbGetStatement()`,
- `row.count`: the number of rows fetched so far (for queries), as
returned by `dbGetRowCount()`,
- `rows.affected`: the number of rows affected (for statements), as
returned by `dbGetRowsAffected()`
- `has.completed`: a logical that indicates if the query or statement
has completed, as returned by `dbHasCompleted()`.
### Implementation notes
The default implementation for `DBIResult objects` constructs such a
list from the return values of the corresponding methods,
`dbGetStatement()`, `dbGetRowCount()`, `dbGetRowsAffected()`, and
`dbHasCompleted()`.
### Examples
``` r
dbGetInfo(RSQLite::SQLite())
```
## Execute a query on a given database connection for retrieval via Arrow
<span id="topic+dbSendQueryArrow"></span>
This section describes the behavior of the following method:
``` r
dbSendQueryArrow(conn, statement, ...)
```
### Description
[![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental)
The `dbSendQueryArrow()` method only submits and synchronously executes
the SQL query to the database engine. It does *not* extract any records
— for that you need to use the `dbFetchArrow()` method, and then you
must call `dbClearResult()` when you finish fetching the records you
need. For interactive use, you should almost always prefer
`dbGetQueryArrow()`. Use `dbSendQuery()` or `dbGetQuery()` instead to
retrieve the results as a data frame.
### Arguments
| | |
|-------------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `statement` | a character string containing SQL. |
| `...` | Other parameters passed on to methods. |
### Additional arguments
The following arguments are not part of the `dbSendQueryArrow()` generic
(to improve compatibility across backends) but are part of the DBI
specification:
- `params` (default: `NULL`)
- `immediate` (default: `NULL`)
They must be provided as named arguments. See the "Specification"
sections for details on their usage.
### Specification
No warnings occur under normal conditions. When done, the DBIResult
object must be cleared with a call to `dbClearResult()`. Failure to
clear the result set leads to a warning when the connection is closed.
If the backend supports only one open result set per connection, issuing
a second query invalidates an already open result set and raises a
warning. The newly opened result set is valid and must be cleared with
`dbClearResult()`.
The `param` argument allows passing query parameters, see `dbBind()` for
details.
### Specification for the `immediate` argument
The `immediate` argument supports distinguishing between "direct" and
"prepared" APIs offered by many database drivers. Passing
`immediate = TRUE` leads to immediate execution of the query or
statement, via the "direct" API (if supported by the driver). The
default `NULL` means that the backend should choose whatever API makes
the most sense for the database, and (if relevant) tries the other API
if the first attempt fails. A successful second attempt should result in
a message that suggests passing the correct `immediate` argument.
Examples for possible behaviors:
1. DBI backend defaults to `immediate = TRUE` internally
1. A query without parameters is passed: query is executed
2. A query with parameters is passed:
1. `params` not given: rejected immediately by the database
because of a syntax error in the query, the backend tries
`immediate = FALSE` (and gives a message)
2. `params` given: query is executed using `immediate = FALSE`
2. DBI backend defaults to `immediate = FALSE` internally
1. A query without parameters is passed:
1. simple query: query is executed
2. "special" query (such as setting a config options): fails,
the backend tries `immediate = TRUE` (and gives a message)
2. A query with parameters is passed:
1. `params` not given: waiting for parameters via `dbBind()`
2. `params` given: query is executed
### Details
This method is for `SELECT` queries only. Some backends may support data
manipulation queries through this method for compatibility reasons.
However, callers are strongly encouraged to use `dbSendStatement()` for
data manipulation statements.
### Value
`dbSendQueryArrow()` returns an S4 object that inherits from
DBIResultArrow. The result set can be used with `dbFetchArrow()` to
extract records. Once you have finished using a result, make sure to
clear it with `dbClearResult()`.
### The data retrieval flow for Arrow streams
This section gives a complete overview over the flow for the execution
of queries that return tabular data as an Arrow stream.
Most of this flow, except repeated calling of `dbBindArrow()` or
`dbBind()`, is implemented by `dbGetQueryArrow()`, which should be
sufficient unless you have a parameterized query that you want to reuse.
This flow requires an active connection established by `dbConnect()`.
See also `vignette("dbi-advanced")` for a walkthrough.
1. Use `dbSendQueryArrow()` to create a result set object of class
DBIResultArrow.
2. Optionally, bind query parameters with `dbBindArrow()` or
`dbBind()`. This is required only if the query contains placeholders
such as `?` or `\$1`, depending on the database backend.
3. Use `dbFetchArrow()` to get a data stream.
4. Repeat the last two steps as necessary.
5. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### Failure modes
An error is raised when issuing a query over a closed or invalid
connection, or if the query is not a non-`NA` string. An error is also
raised if the syntax of the query is invalid and all query parameters
are given (by passing the `params` argument) or the `immediate` argument
is set to `TRUE`.
### Examples
``` r
# Retrieve data as arrow table
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4")
dbFetchArrow(rs)
dbClearResult(rs)
dbDisconnect(con)
```
## Fetch records from a previously executed query as an Arrow object
<span id="topic+dbFetchArrow"></span>
This section describes the behavior of the following method:
``` r
dbFetchArrow(res, ...)
```
### Description
[![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental)
Fetch the result set and return it as an Arrow object. Use
`dbFetchArrowChunk()` to fetch results in chunks.
### Arguments
| | |
|----|----|
| `res` | An object inheriting from DBIResultArrow, created by `dbSendQueryArrow()`. |
| `...` | Other arguments passed on to methods. |
### Value
`dbFetchArrow()` always returns an object coercible to a data.frame with
as many rows as records were fetched and as many columns as fields in
the result set, even if the result is a single value or has one or zero
rows.
### The data retrieval flow for Arrow streams
This section gives a complete overview over the flow for the execution
of queries that return tabular data as an Arrow stream.
Most of this flow, except repeated calling of `dbBindArrow()` or
`dbBind()`, is implemented by `dbGetQueryArrow()`, which should be
sufficient unless you have a parameterized query that you want to reuse.
This flow requires an active connection established by `dbConnect()`.
See also `vignette("dbi-advanced")` for a walkthrough.
1. Use `dbSendQueryArrow()` to create a result set object of class
DBIResultArrow.
2. Optionally, bind query parameters with `dbBindArrow()` or
`dbBind()`. This is required only if the query contains placeholders
such as `?` or `\$1`, depending on the database backend.
3. Use `dbFetchArrow()` to get a data stream.
4. Repeat the last two steps as necessary.
5. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### Failure modes
An attempt to fetch from a closed result set raises an error.
### Specification
Fetching multi-row queries with one or more columns by default returns
the entire result. The object returned by `dbFetchArrow()` can also be
passed to `nanoarrow::as_nanoarrow_array_stream()` to create a nanoarrow
array stream object that can be used to read the result set in batches.
The chunk size is implementation-specific.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
# Fetch all results
rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4")
as.data.frame(dbFetchArrow(rs))
dbClearResult(rs)
dbDisconnect(con)
```
## Fetch the next batch of records from a previously executed query as an Arrow object
<span id="topic+dbFetchArrowChunk"></span>
This section describes the behavior of the following method:
``` r
dbFetchArrowChunk(res, ...)
```
### Description
[![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental)
Fetch the next chunk of the result set and return it as an Arrow object.
The chunk size is implementation-specific. Use `dbFetchArrow()` to fetch
all results.
### Arguments
| | |
|----|----|
| `res` | An object inheriting from DBIResultArrow, created by `dbSendQueryArrow()`. |
| `...` | Other arguments passed on to methods. |
### Value
`dbFetchArrowChunk()` always returns an object coercible to a data.frame
with as many rows as records were fetched and as many columns as fields
in the result set, even if the result is a single value or has one or
zero rows.
### The data retrieval flow for Arrow streams
This section gives a complete overview over the flow for the execution
of queries that return tabular data as an Arrow stream.
Most of this flow, except repeated calling of `dbBindArrow()` or
`dbBind()`, is implemented by `dbGetQueryArrow()`, which should be
sufficient unless you have a parameterized query that you want to reuse.
This flow requires an active connection established by `dbConnect()`.
See also `vignette("dbi-advanced")` for a walkthrough.
1. Use `dbSendQueryArrow()` to create a result set object of class
DBIResultArrow.
2. Optionally, bind query parameters with `dbBindArrow()` or
`dbBind()`. This is required only if the query contains placeholders
such as `?` or `\$1`, depending on the database backend.
3. Use `dbFetchArrow()` to get a data stream.
4. Repeat the last two steps as necessary.
5. Use `dbClearResult()` to clean up the result set object. This step
is mandatory even if no rows have been fetched or if an error has
occurred during the processing. It is good practice to use
`on.exit()` or `withr::defer()` to ensure that this step is always
executed.
### Failure modes
An attempt to fetch from a closed result set raises an error.
### Specification
Fetching multi-row queries with one or more columns returns the next
chunk. The size of the chunk is implementation-specific. The object
returned by `dbFetchArrowChunk()` can also be passed to
`nanoarrow::as_nanoarrow_array()` to create a nanoarrow array object.
The chunk size is implementation-specific.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
# Fetch all results
rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4")
dbHasCompleted(rs)
as.data.frame(dbFetchArrowChunk(rs))
dbHasCompleted(rs)
as.data.frame(dbFetchArrowChunk(rs))
dbClearResult(rs)
dbDisconnect(con)
```
## Retrieve results from a query as an Arrow object
<span id="topic+dbGetQueryArrow"></span>
This section describes the behavior of the following method:
``` r
dbGetQueryArrow(conn, statement, ...)
```
### Description
[![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental)
Returns the result of a query as an Arrow object. `dbGetQueryArrow()`
comes with a default implementation (which should work with most
backends) that calls `dbSendQueryArrow()`, then `dbFetchArrow()`,
ensuring that the result is always freed by `dbClearResult()`. For
passing query parameters, see `dbSendQueryArrow()`, in particular the
"The data retrieval flow for Arrow streams" section. For retrieving
results as a data frame, see `dbGetQuery()`.
### Arguments
| | |
|-------------|-------------------------------------------------------|
| `conn` | A DBIConnection object, as returned by `dbConnect()`. |
| `statement` | a character string containing SQL. |
| `...` | Other parameters passed on to methods. |
### Additional arguments
The following arguments are not part of the `dbGetQueryArrow()` generic
(to improve compatibility across backends) but are part of the DBI
specification:
- `params` (default: `NULL`)
- `immediate` (default: `NULL`)
They must be provided as named arguments. See the "Specification" and
"Value" sections for details on their usage.
The `param` argument allows passing query parameters, see `dbBind()` for
details.
### Specification for the `immediate` argument
The `immediate` argument supports distinguishing between "direct" and
"prepared" APIs offered by many database drivers. Passing
`immediate = TRUE` leads to immediate execution of the query or
statement, via the "direct" API (if supported by the driver). The
default `NULL` means that the backend should choose whatever API makes
the most sense for the database, and (if relevant) tries the other API
if the first attempt fails. A successful second attempt should result in
a message that suggests passing the correct `immediate` argument.
Examples for possible behaviors:
1. DBI backend defaults to `immediate = TRUE` internally
1. A query without parameters is passed: query is executed
2. A query with parameters is passed:
1. `params` not given: rejected immediately by the database
because of a syntax error in the query, the backend tries
`immediate = FALSE` (and gives a message)
2. `params` given: query is executed using `immediate = FALSE`
2. DBI backend defaults to `immediate = FALSE` internally
1. A query without parameters is passed:
1. simple query: query is executed
2. "special" query (such as setting a config options): fails,
the backend tries `immediate = TRUE` (and gives a message)
2. A query with parameters is passed:
1. `params` not given: waiting for parameters via `dbBind()`
2. `params` given: query is executed
### Details
This method is for `SELECT` queries only (incl. other SQL statements
that return a `SELECT`-alike result, e.g., execution of a stored
procedure or data manipulation queries like
`INSERT INTO ... RETURNING ...`). To execute a stored procedure that
does not return a result set, use `dbExecute()`.
Some backends may support data manipulation statements through this
method. However, callers are strongly advised to use `dbExecute()` for
data manipulation statements.
### Value
`dbGetQueryArrow()` always returns an object coercible to a data.frame,
with as many rows as records were fetched and as many columns as fields
in the result set, even if the result is a single value or has one or
zero rows.
### Implementation notes
Subclasses should override this method only if they provide some sort of
performance optimization.
### Failure modes
An error is raised when issuing a query over a closed or invalid
connection, if the syntax of the query is invalid, or if the query is
not a non-`NA` string. The object returned by `dbGetQueryArrow()` can
also be passed to `nanoarrow::as_nanoarrow_array_stream()` to create a
nanoarrow array stream object that can be used to read the result set in
batches. The chunk size is implementation-specific.
### Examples
``` r
# Retrieve data as arrow table
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
dbGetQueryArrow(con, "SELECT * FROM mtcars")
dbDisconnect(con)
```
## Read database tables as Arrow objects
<span id="topic+dbReadTableArrow"></span>
This section describes the behavior of the following method:
``` r
dbReadTableArrow(conn, name, ...)
```
### Description
[![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental)
Reads a database table as an Arrow object. Use `dbReadTable()` instead
to obtain a data frame.
### Arguments
<table role="presentation">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr>
<td><code id="dbReadTableArrow_+3A_conn">conn</code></td>
<td><p>A DBIConnection object, as returned by
<code>dbConnect()</code>.</p></td>
</tr>
<tr>
<td><code id="dbReadTableArrow_+3A_name">name</code></td>
<td><p>The table name, passed on to <code>dbQuoteIdentifier()</code>.
Options are:</p>
<ul>
<li><p>a character string with the unquoted DBMS table name, e.g.
<code>"table_name"</code>,</p></li>
<li><p>a call to <code>Id()</code> with components to the fully
qualified table name, e.g.
<code>Id(schema = "my_schema", table = "table_name")</code></p></li>
<li><p>a call to <code>SQL()</code> with the quoted and fully qualified
table name given verbatim, e.g.
<code>SQL('"my_schema"."table_name"')</code></p></li>
</ul></td>
</tr>
<tr>
<td><code id="dbReadTableArrow_+3A_...">...</code></td>
<td><p>Other parameters passed on to methods.</p></td>
</tr>
</tbody>
</table>
### Details
This function returns an Arrow object. Convert it to a data frame with
`as.data.frame()` or use `dbReadTable()` to obtain a data frame.
### Value
`dbReadTableArrow()` returns an Arrow object that contains the complete
data from the remote table, effectively the result of calling
`dbGetQueryArrow()` with `SELECT * FROM <name>`.
An empty table is returned as an Arrow object with zero rows.
### Failure modes
An error is raised if the table does not exist.
An error is raised when calling this method for a closed or invalid
connection. An error is raised if `name` cannot be processed with
`dbQuoteIdentifier()` or if this results in a non-scalar.
### Specification
The `name` argument is processed as follows, to support databases that
allow non-syntactic names for their objects:
- If an unquoted table name as string: `dbReadTableArrow()` will do the
quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)`
- If the result of a call to `dbQuoteIdentifier()`: no more quoting is
done
### Examples
``` r
# Read data as Arrow table
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars[1:10, ])
dbReadTableArrow(con, "mtcars")
dbDisconnect(con)
```
## Copy Arrow objects to database tables
<span id="topic+dbWriteTableArrow"></span>
This section describes the behavior of the following method:
``` r
dbWriteTableArrow(conn, name, value, ...)
```
### Description
[![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental)
Writes, overwrites or appends an Arrow object to a database table.
### Arguments
<table role="presentation">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr>
<td><code id="dbWriteTableArrow_+3A_conn">conn</code></td>
<td><p>A DBIConnection object, as returned by
<code>dbConnect()</code>.</p></td>
</tr>
<tr>
<td><code id="dbWriteTableArrow_+3A_name">name</code></td>
<td><p>The table name, passed on to <code>dbQuoteIdentifier()</code>.
Options are:</p>
<ul>
<li><p>a character string with the unquoted DBMS table name, e.g.
<code>"table_name"</code>,</p></li>
<li><p>a call to <code>Id()</code> with components to the fully
qualified table name, e.g.
<code>Id(schema = "my_schema", table = "table_name")</code></p></li>
<li><p>a call to <code>SQL()</code> with the quoted and fully qualified
table name given verbatim, e.g.
<code>SQL('"my_schema"."table_name"')</code></p></li>
</ul></td>
</tr>
<tr>
<td><code id="dbWriteTableArrow_+3A_value">value</code></td>
<td><p>An nanoarray stream, or an object coercible to a nanoarray stream
with <code>nanoarrow::as_nanoarrow_array_stream()</code>.</p></td>
</tr>
<tr>
<td><code id="dbWriteTableArrow_+3A_...">...</code></td>
<td><p>Other parameters passed on to methods.</p></td>
</tr>
</tbody>
</table>
### Additional arguments
The following arguments are not part of the `dbWriteTableArrow()`
generic (to improve compatibility across backends) but are part of the
DBI specification:
- `overwrite` (default: `FALSE`)
- `append` (default: `FALSE`)
- `temporary` (default: `FALSE`)
They must be provided as named arguments. See the "Specification" and
"Value" sections for details on their usage.
### Specification
The `name` argument is processed as follows, to support databases that
allow non-syntactic names for their objects:
- If an unquoted table name as string: `dbWriteTableArrow()` will do the
quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)`
- If the result of a call to `dbQuoteIdentifier()`: no more quoting is
done
The `value` argument must be a data frame with a subset of the columns
of the existing table if `append = TRUE`. The order of the columns does
not matter with `append = TRUE`.
If the `overwrite` argument is `TRUE`, an existing table of the same
name will be overwritten. This argument doesn't change behavior if the
table does not exist yet.
If the `append` argument is `TRUE`, the rows in an existing table are
preserved, and the new data are appended. If the table doesn't exist
yet, it is created.
If the `temporary` argument is `TRUE`, the table is not available in a
second connection and is gone after reconnecting. Not all backends
support this argument. A regular, non-temporary table is visible in a
second connection, in a pre-existing connection, and after reconnecting
to the database.
SQL keywords can be used freely in table names, column names, and data.
Quotes, commas, spaces, and other special characters such as newlines
and tabs, can also be used in the data, and, if the database supports
non-syntactic identifiers, also for table names and column names.
The following data types must be supported at least, and be read
identically with `dbReadTable()`:
- integer
- numeric (the behavior for `Inf` and `NaN` is not specified)
- logical
- `NA` as NULL
- 64-bit values (using `"bigint"` as field type); the result can be
- converted to a numeric, which may lose precision,
- converted a character vector, which gives the full decimal
representation
- written to another table and read again unchanged
- character (in both UTF-8 and native encodings), supporting empty
strings before and after a non-empty string
- factor (possibly returned as character)
- objects of type blob::blob (if supported by the database)
- date (if supported by the database; returned as `Date`), also for
dates prior to 1970 or 1900 or after 2038
- time (if supported by the database; returned as objects that inherit
from `difftime`)
- timestamp (if supported by the database; returned as `POSIXct`
respecting the time zone but not necessarily preserving the input time
zone), also for timestamps prior to 1970 or 1900 or after 2038
respecting the time zone but not necessarily preserving the input time
zone)
Mixing column types in the same table is supported.
### Details
This function expects an Arrow object. Convert a data frame to an Arrow
object with `nanoarrow::as_nanoarrow_array_stream()` or use
`dbWriteTable()` to write a data frame.
This function is useful if you want to create and load a table at the
same time. Use `dbAppendTableArrow()` for appending data to an existing
table, `dbCreateTableArrow()` for creating a table and specifying field
types, and `dbRemoveTable()` for overwriting tables.
### Value
`dbWriteTableArrow()` returns `TRUE`, invisibly.
### Failure modes
If the table exists, and both `append` and `overwrite` arguments are
unset, or `append = TRUE` and the data frame with the new data has
different column names, an error is raised; the remote table remains
unchanged.
An error is raised when calling this method for a closed or invalid
connection. An error is also raised if `name` cannot be processed with
`dbQuoteIdentifier()` or if this results in a non-scalar. Invalid values
for the additional arguments `overwrite`, `append`, and `temporary`
(non-scalars, unsupported data types, `NA`, incompatible values,
incompatible columns) also raise an error.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTableArrow(con, "mtcars", nanoarrow::as_nanoarrow_array_stream(mtcars[1:5, ]))
dbReadTable(con, "mtcars")
dbDisconnect(con)
```
## Create a table in the database based on an Arrow object
<span id="topic+dbCreateTableArrow"></span>
This section describes the behavior of the following method:
``` r
dbCreateTableArrow(conn, name, value, ..., temporary = FALSE)
```
### Description
[![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental)
The default `dbCreateTableArrow()` method determines the R data types of
the Arrow schema associated with the Arrow object, and calls
`dbCreateTable()`. Backends that implement `dbAppendTableArrow()` should
typically also implement this generic. Use `dbCreateTable()` to create a
table from the column types as defined in a data frame.
### Arguments
<table role="presentation">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr>
<td><code id="dbCreateTableArrow_+3A_conn">conn</code></td>
<td><p>A DBIConnection object, as returned by
<code>dbConnect()</code>.</p></td>
</tr>
<tr>
<td><code id="dbCreateTableArrow_+3A_name">name</code></td>
<td><p>The table name, passed on to <code>dbQuoteIdentifier()</code>.
Options are:</p>
<ul>
<li><p>a character string with the unquoted DBMS table name, e.g.
<code>"table_name"</code>,</p></li>
<li><p>a call to <code>Id()</code> with components to the fully
qualified table name, e.g.
<code>Id(schema = "my_schema", table = "table_name")</code></p></li>
<li><p>a call to <code>SQL()</code> with the quoted and fully qualified
table name given verbatim, e.g.
<code>SQL('"my_schema"."table_name"')</code></p></li>
</ul></td>
</tr>
<tr>
<td><code id="dbCreateTableArrow_+3A_value">value</code></td>
<td><p>An object for which a schema can be determined via
<code>nanoarrow::infer_nanoarrow_schema()</code>.</p></td>
</tr>
<tr>
<td><code id="dbCreateTableArrow_+3A_...">...</code></td>
<td><p>Other parameters passed on to methods.</p></td>
</tr>
<tr>
<td><code id="dbCreateTableArrow_+3A_temporary">temporary</code></td>
<td><p>If <code>TRUE</code>, will generate a temporary table.</p></td>
</tr>
</tbody>
</table>
### Additional arguments
The following arguments are not part of the `dbCreateTableArrow()`
generic (to improve compatibility across backends) but are part of the
DBI specification:
- `temporary` (default: `FALSE`)
They must be provided as named arguments. See the "Specification" and
"Value" sections for details on their usage.
### Specification
The `name` argument is processed as follows, to support databases that
allow non-syntactic names for their objects:
- If an unquoted table name as string: `dbCreateTableArrow()` will do
the quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)`
- If the result of a call to `dbQuoteIdentifier()`: no more quoting is
done
The `value` argument can be:
- a data frame,
- a nanoarrow array
- a nanoarrow array stream (which will still contain the data after the
call)
- a nanoarrow schema
If the `temporary` argument is `TRUE`, the table is not available in a
second connection and is gone after reconnecting. Not all backends
support this argument. A regular, non-temporary table is visible in a
second connection, in a pre-existing connection, and after reconnecting
to the database.
SQL keywords can be used freely in table names, column names, and data.
Quotes, commas, and spaces can also be used for table names and column
names, if the database supports non-syntactic identifiers.
### Value
`dbCreateTableArrow()` returns `TRUE`, invisibly.
### Failure modes
If the table exists, an error is raised; the remote table remains
unchanged.
An error is raised when calling this method for a closed or invalid
connection. An error is also raised if `name` cannot be processed with
`dbQuoteIdentifier()` or if this results in a non-scalar. Invalid values
for the `temporary` argument (non-scalars, unsupported data types, `NA`,
incompatible values, duplicate names) also raise an error.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
ptype <- data.frame(a = numeric())
dbCreateTableArrow(con, "df", nanoarrow::infer_nanoarrow_schema(ptype))
dbReadTable(con, "df")
dbDisconnect(con)
```
## Insert rows into a table from an Arrow stream
<span id="topic+dbAppendTableArrow"></span>
This section describes the behavior of the following method:
``` r
dbAppendTableArrow(conn, name, value, ...)
```
### Description
[![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental)
The `dbAppendTableArrow()` method assumes that the table has been
created beforehand, e.g. with `dbCreateTableArrow()`. The default
implementation calls `dbAppendTable()` for each chunk of the stream. Use
`dbAppendTable()` to append data from a data.frame.
### Arguments
<table role="presentation">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr>
<td><code id="dbAppendTableArrow_+3A_conn">conn</code></td>
<td><p>A DBIConnection object, as returned by
<code>dbConnect()</code>.</p></td>
</tr>
<tr>
<td><code id="dbAppendTableArrow_+3A_name">name</code></td>
<td><p>The table name, passed on to <code>dbQuoteIdentifier()</code>.
Options are:</p>
<ul>
<li><p>a character string with the unquoted DBMS table name, e.g.
<code>"table_name"</code>,</p></li>
<li><p>a call to <code>Id()</code> with components to the fully
qualified table name, e.g.
<code>Id(schema = "my_schema", table = "table_name")</code></p></li>
<li><p>a call to <code>SQL()</code> with the quoted and fully qualified
table name given verbatim, e.g.
<code>SQL('"my_schema"."table_name"')</code></p></li>
</ul></td>
</tr>
<tr>
<td><code id="dbAppendTableArrow_+3A_value">value</code></td>
<td><p>An object coercible with
<code>nanoarrow::as_nanoarrow_array_stream()</code>.</p></td>
</tr>
<tr>
<td><code id="dbAppendTableArrow_+3A_...">...</code></td>
<td><p>Other parameters passed on to methods.</p></td>
</tr>
</tbody>
</table>
### Value
`dbAppendTableArrow()` returns a scalar numeric.
### Failure modes
If the table does not exist, or the new data in `values` is not a data
frame or has different column names, an error is raised; the remote
table remains unchanged.
An error is raised when calling this method for a closed or invalid
connection. An error is also raised if `name` cannot be processed with
`dbQuoteIdentifier()` or if this results in a non-scalar.
### Specification
SQL keywords can be used freely in table names, column names, and data.
Quotes, commas, spaces, and other special characters such as newlines
and tabs, can also be used in the data, and, if the database supports
non-syntactic identifiers, also for table names and column names.
The following data types must be supported at least, and be read
identically with `dbReadTable()`:
- integer
- numeric (the behavior for `Inf` and `NaN` is not specified)
- logical
- `NA` as NULL
- 64-bit values (using `"bigint"` as field type); the result can be
- converted to a numeric, which may lose precision,
- converted a character vector, which gives the full decimal
representation
- written to another table and read again unchanged
- character (in both UTF-8 and native encodings), supporting empty
strings (before and after non-empty strings)
- factor (possibly returned as character)
- objects of type blob::blob (if supported by the database)
- date (if supported by the database; returned as `Date`) also for dates
prior to 1970 or 1900 or after 2038
- time (if supported by the database; returned as objects that inherit
from `difftime`)
- timestamp (if supported by the database; returned as `POSIXct`
respecting the time zone but not necessarily preserving the input time
zone), also for timestamps prior to 1970 or 1900 or after 2038
respecting the time zone but not necessarily preserving the input time
zone)
Mixing column types in the same table is supported.
The `name` argument is processed as follows, to support databases that
allow non-syntactic names for their objects:
- If an unquoted table name as string: `dbAppendTableArrow()` will do
the quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)`
- If the result of a call to `dbQuoteIdentifier()`: no more quoting is
done to support databases that allow non-syntactic names for their
objects:
The `value` argument must be a data frame with a subset of the columns
of the existing table. The order of the columns does not matter.
### Examples
``` r
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbCreateTableArrow(con, "iris", iris[0, ])
dbAppendTableArrow(con, "iris", iris[1:5, ])
dbReadTable(con, "iris")
dbDisconnect(con)
```
|