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
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package flight_integration
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"math"
"net"
"os"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/flight"
"github.com/apache/arrow-go/v18/arrow/flight/flightsql"
"github.com/apache/arrow-go/v18/arrow/flight/flightsql/schema_ref"
"github.com/apache/arrow-go/v18/arrow/flight/session"
"github.com/apache/arrow-go/v18/arrow/internal/arrjson"
"github.com/apache/arrow-go/v18/arrow/ipc"
"github.com/apache/arrow-go/v18/arrow/memory"
"golang.org/x/xerrors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
)
type Scenario interface {
MakeServer(port int) flight.Server
RunClient(addr string, opts ...grpc.DialOption) error
}
func GetScenario(name string, args ...string) Scenario {
switch name {
case "auth:basic_proto":
return &authBasicProtoTester{}
case "middleware":
return &middlewareScenarioTester{}
case "ordered":
return &orderedScenarioTester{}
case "expiration_time:do_get":
return &expirationTimeDoGetScenarioTester{}
case "expiration_time:list_actions":
return &expirationTimeListActionsScenarioTester{}
case "expiration_time:cancel_flight_info":
return &expirationTimeCancelFlightInfoScenarioTester{}
case "expiration_time:renew_flight_endpoint":
return &expirationTimeRenewFlightEndpointScenarioTester{}
case "location:reuse_connection":
return &locationReuseConnectionScenarioTester{}
case "poll_flight_info":
return &pollFlightInfoScenarioTester{}
case "app_metadata_flight_info_endpoint":
return &appMetadataFlightInfoEndpointScenarioTester{}
case "flight_sql":
return &flightSqlScenarioTester{}
case "flight_sql:extension":
return &flightSqlExtensionScenarioTester{}
case "session_options":
return &sessionOptionsScenarioTester{}
case "flight_sql:ingestion":
return &flightSqlIngestionScenarioTester{}
case "":
if len(args) > 0 {
return &defaultIntegrationTester{path: args[0]}
}
return &defaultIntegrationTester{}
}
panic(fmt.Errorf("scenario not found: %s", name))
}
func initServer(port int, srv flight.Server) int {
srv.Init(fmt.Sprintf("0.0.0.0:%d", port))
_, p, _ := net.SplitHostPort(srv.Addr().String())
port, _ = strconv.Atoi(p)
return port
}
type integrationDataSet struct {
schema *arrow.Schema
chunks []arrow.Record
}
func consumeFlightLocation(ctx context.Context, loc *flight.Location, tkt *flight.Ticket, orig []arrow.Record, opts ...grpc.DialOption) error {
client, err := flight.NewClientWithMiddleware(loc.GetUri(), nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
stream, err := client.DoGet(ctx, tkt)
if err != nil {
return err
}
rdr, err := flight.NewRecordReader(stream)
if err != nil {
return err
}
defer rdr.Release()
for i, chunk := range orig {
if !rdr.Next() {
return fmt.Errorf("got fewer batches than expected, received so far: %d, expected: %d", i, len(orig))
}
if !array.RecordEqual(chunk, rdr.Record()) {
return fmt.Errorf("batch %d doesn't match", i)
}
if string(rdr.LatestAppMetadata()) != strconv.Itoa(i) {
return fmt.Errorf("expected metadata value: %s, but got: %s", strconv.Itoa(i), string(rdr.LatestAppMetadata()))
}
}
if rdr.Next() {
return fmt.Errorf("got more batches than the expected: %d", len(orig))
}
return nil
}
type defaultIntegrationTester struct {
flight.BaseFlightServer
port int
path string
uploadedChunks map[string]integrationDataSet
}
func (s *defaultIntegrationTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flight.NewClientWithMiddleware(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
ctx := context.Background()
descr := &flight.FlightDescriptor{
Type: flight.DescriptorPATH,
Path: []string{s.path},
}
fmt.Println("Opening JSON file '", s.path, "'")
r, err := os.Open(s.path)
if err != nil {
return fmt.Errorf("could not open JSON file: %q: %w", s.path, err)
}
rdr, err := arrjson.NewReader(r)
if err != nil {
return fmt.Errorf("could not create JSON file reader from file: %q: %w", s.path, err)
}
dataSet := integrationDataSet{
chunks: make([]arrow.Record, 0),
schema: rdr.Schema(),
}
for {
rec, err := rdr.Read()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
defer rec.Release()
dataSet.chunks = append(dataSet.chunks, rec)
}
stream, err := client.DoPut(ctx)
if err != nil {
return err
}
wr := flight.NewRecordWriter(stream, ipc.WithSchema(dataSet.schema))
wr.SetFlightDescriptor(descr)
for i, rec := range dataSet.chunks {
metadata := []byte(strconv.Itoa(i))
if err := wr.WriteWithAppMetadata(rec, metadata); err != nil {
return err
}
pr, err := stream.Recv()
if err != nil {
return err
}
acked := pr.GetAppMetadata()
switch {
case len(acked) == 0:
return fmt.Errorf("expected metadata value: %s, but got nothing", string(metadata))
case !bytes.Equal(metadata, acked):
return fmt.Errorf("expected metadata value: %s, but got: %s", string(metadata), string(acked))
}
}
wr.Close()
if err := stream.CloseSend(); err != nil {
return err
}
for {
_, err = stream.Recv()
if err != nil {
if err != io.EOF {
return err
}
break
}
}
info, err := client.GetFlightInfo(ctx, descr)
if err != nil {
return err
}
if len(info.Endpoint) == 0 {
fmt.Fprintln(os.Stderr, "no endpoints returned from flight server.")
return fmt.Errorf("no endpoints returned from flight server")
}
for _, ep := range info.Endpoint {
if len(ep.Location) == 0 {
return fmt.Errorf("no locations returned from flight server")
}
for _, loc := range ep.Location {
consumeFlightLocation(ctx, loc, ep.Ticket, dataSet.chunks, opts...)
}
}
return nil
}
func (s *defaultIntegrationTester) MakeServer(port int) flight.Server {
s.uploadedChunks = make(map[string]integrationDataSet)
srv := flight.NewServerWithMiddleware(nil)
srv.RegisterFlightService(s)
s.port = initServer(port, srv)
return srv
}
func (s *defaultIntegrationTester) GetFlightInfo(ctx context.Context, in *flight.FlightDescriptor) (*flight.FlightInfo, error) {
if in.Type == flight.DescriptorPATH {
if len(in.Path) == 0 {
return nil, status.Error(codes.InvalidArgument, "invalid path")
}
data, ok := s.uploadedChunks[in.Path[0]]
if !ok {
return nil, status.Errorf(codes.NotFound, "could not find flight: %s", in.Path[0])
}
flightData := &flight.FlightInfo{
Schema: flight.SerializeSchema(data.schema, memory.DefaultAllocator),
FlightDescriptor: in,
Endpoint: []*flight.FlightEndpoint{{
Ticket: &flight.Ticket{Ticket: []byte(in.Path[0])},
Location: []*flight.Location{{Uri: fmt.Sprintf("grpc+tcp://127.0.0.1:%d", s.port)}},
}},
TotalRecords: 0,
TotalBytes: -1,
}
for _, r := range data.chunks {
flightData.TotalRecords += r.NumRows()
}
return flightData, nil
}
return nil, status.Error(codes.Unimplemented, in.Type.String())
}
func (s *defaultIntegrationTester) DoGet(tkt *flight.Ticket, stream flight.FlightService_DoGetServer) error {
data, ok := s.uploadedChunks[string(tkt.Ticket)]
if !ok {
return status.Errorf(codes.NotFound, "could not find flight: %s", string(tkt.Ticket))
}
wr := flight.NewRecordWriter(stream, ipc.WithSchema(data.schema))
defer wr.Close()
for i, rec := range data.chunks {
wr.WriteWithAppMetadata(rec, []byte(strconv.Itoa(i)))
}
return nil
}
func (s *defaultIntegrationTester) DoPut(stream flight.FlightService_DoPutServer) error {
rdr, err := flight.NewRecordReader(stream)
if err != nil {
return status.Error(codes.Internal, err.Error())
}
var (
key string
dataset integrationDataSet
)
// creating the reader should have gotten the first message which would
// have the schema, which should have a populated flight descriptor
desc := rdr.LatestFlightDescriptor()
if desc.Type != flight.DescriptorPATH || len(desc.Path) < 1 {
return status.Error(codes.InvalidArgument, "must specify a path")
}
key = desc.Path[0]
dataset.schema = rdr.Schema()
dataset.chunks = make([]arrow.Record, 0)
for rdr.Next() {
rec := rdr.Record()
rec.Retain()
dataset.chunks = append(dataset.chunks, rec)
if len(rdr.LatestAppMetadata()) > 0 {
stream.Send(&flight.PutResult{AppMetadata: rdr.LatestAppMetadata()})
}
}
s.uploadedChunks[key] = dataset
return nil
}
func CheckActionResults(ctx context.Context, client flight.Client, action *flight.Action, results []string) error {
stream, err := client.DoAction(ctx, action)
if err != nil {
return err
}
defer stream.CloseSend()
for _, expected := range results {
res, err := stream.Recv()
if err != nil {
return err
}
actual := string(res.Body)
if expected != actual {
return fmt.Errorf("got wrong result: expected: %s, got: %s", expected, actual)
}
}
res, err := stream.Recv()
if res != nil || err != io.EOF {
return xerrors.New("action result stream had too many entries")
}
return nil
}
const (
authUsername = "arrow"
authPassword = "flight"
)
type authBasicValidator struct {
auth flight.BasicAuth
}
func (a *authBasicValidator) Authenticate(conn flight.AuthConn) error {
token, err := conn.Read()
if err != nil {
return err
}
var incoming flight.BasicAuth
if err = proto.Unmarshal(token, &incoming); err != nil {
return err
}
if incoming.Username != a.auth.Username || incoming.Password != a.auth.Password {
return status.Error(codes.Unauthenticated, "invalid token")
}
return conn.Send([]byte(a.auth.Username))
}
func (a *authBasicValidator) IsValid(token string) (interface{}, error) {
if token != a.auth.Username {
return nil, status.Error(codes.Unauthenticated, "invalid token")
}
return token, nil
}
type clientAuthBasic struct {
auth *flight.BasicAuth
token string
}
func (c *clientAuthBasic) Authenticate(_ context.Context, conn flight.AuthConn) error {
if c.auth != nil {
data, err := proto.Marshal(c.auth)
if err != nil {
return err
}
if err = conn.Send(data); err != nil {
return err
}
token, err := conn.Read()
c.token = string(token)
if err != io.EOF {
return err
}
}
return nil
}
func (c *clientAuthBasic) GetToken(context.Context) (string, error) {
return c.token, nil
}
type authBasicProtoTester struct {
flight.BaseFlightServer
}
func (s *authBasicProtoTester) RunClient(addr string, opts ...grpc.DialOption) error {
auth := &clientAuthBasic{}
client, err := flight.NewClientWithMiddleware(addr, auth, nil, opts...)
if err != nil {
return err
}
ctx := context.Background()
stream, err := client.DoAction(ctx, &flight.Action{})
if err != nil {
return err
}
// should fail unauthenticated
_, err = stream.Recv()
st, ok := status.FromError(err)
if !ok {
return err
}
if st.Code() != codes.Unauthenticated {
return fmt.Errorf("expected Unauthenticated, got %s", st.Code())
}
auth.auth = &flight.BasicAuth{Username: authUsername, Password: authPassword}
if err := client.Authenticate(ctx); err != nil {
return err
}
return CheckActionResults(ctx, client, &flight.Action{}, []string{authUsername})
}
func (s *authBasicProtoTester) MakeServer(port int) flight.Server {
s.SetAuthHandler(&authBasicValidator{
auth: flight.BasicAuth{Username: authUsername, Password: authPassword}})
srv := flight.NewServerWithMiddleware(nil)
srv.RegisterFlightService(s)
initServer(port, srv)
return srv
}
func (authBasicProtoTester) DoAction(_ *flight.Action, stream flight.FlightService_DoActionServer) error {
auth := flight.AuthFromContext(stream.Context())
stream.Send(&flight.Result{Body: []byte(auth.(string))})
return nil
}
type middlewareScenarioTester struct {
flight.BaseFlightServer
}
func (m *middlewareScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
tm := &testClientMiddleware{}
client, err := flight.NewClientWithMiddleware(addr, nil, []flight.ClientMiddleware{
flight.CreateClientMiddleware(tm)}, opts...)
if err != nil {
return err
}
ctx := context.Background()
// this call is expected to fail
_, err = client.GetFlightInfo(ctx, &flight.FlightDescriptor{Type: flight.DescriptorCMD})
if err == nil {
return xerrors.New("expected call to fail")
}
if tm.received != "expected value" {
return fmt.Errorf("expected to receive header 'x-middleware: expected value', but instead got %s", tm.received)
}
fmt.Fprintln(os.Stderr, "Headers received successfully on failing call.")
tm.received = ""
_, err = client.GetFlightInfo(ctx, &flight.FlightDescriptor{Type: flight.DescriptorCMD, Cmd: []byte("success")})
if err != nil {
return err
}
if tm.received != "expected value" {
return fmt.Errorf("expected to receive header 'x-middleware: expected value', but instead got %s", tm.received)
}
fmt.Fprintln(os.Stderr, "Headers received successfully on passing call.")
return nil
}
func (m *middlewareScenarioTester) MakeServer(port int) flight.Server {
srv := flight.NewServerWithMiddleware([]flight.ServerMiddleware{
flight.CreateServerMiddleware(testServerMiddleware{})})
srv.RegisterFlightService(m)
initServer(port, srv)
return srv
}
func (m *middlewareScenarioTester) GetFlightInfo(ctx context.Context, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
if desc.Type != flight.DescriptorCMD || string(desc.Cmd) != "success" {
return nil, status.Error(codes.Unknown, "unknown")
}
return &flight.FlightInfo{
Schema: flight.SerializeSchema(arrow.NewSchema([]arrow.Field{}, nil), memory.DefaultAllocator),
FlightDescriptor: desc,
Endpoint: []*flight.FlightEndpoint{{
Ticket: &flight.Ticket{Ticket: []byte("foo")},
Location: []*flight.Location{{Uri: "grpc+tcp://localhost:10010"}},
}},
TotalRecords: -1,
TotalBytes: -1,
}, nil
}
type orderedScenarioTester struct {
flight.BaseFlightServer
}
func (o *orderedScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flight.NewClientWithMiddleware(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
ctx := context.Background()
info, err := client.GetFlightInfo(ctx, &flight.FlightDescriptor{Type: flight.DescriptorCMD, Cmd: []byte("ordered")})
if err != nil {
return err
}
if !info.GetOrdered() {
return fmt.Errorf("expected to server return FlightInfo.ordered = true")
}
var recs []arrow.Record
for _, ep := range info.Endpoint {
if len(ep.Location) != 0 {
return fmt.Errorf("expected to receive empty locations to use the original service: %s",
ep.Location)
}
stream, err := client.DoGet(ctx, ep.Ticket)
if err != nil {
return err
}
rdr, err := flight.NewRecordReader(stream)
if err != nil {
return err
}
defer rdr.Release()
for rdr.Next() {
record := rdr.Record()
record.Retain()
defer record.Release()
recs = append(recs, record)
}
if rdr.Err() != nil {
return rdr.Err()
}
}
// Build expected records
mem := memory.DefaultAllocator
schema := arrow.NewSchema(
[]arrow.Field{
{Name: "number", Type: arrow.PrimitiveTypes.Int32},
},
nil,
)
expected_table, _ := array.TableFromJSON(mem, schema, []string{
`[
{"number": 1},
{"number": 2},
{"number": 3}
]`,
`[
{"number": 10},
{"number": 20},
{"number": 30}
]`,
`[
{"number": 100},
{"number": 200},
{"number": 300}
]`,
})
defer expected_table.Release()
table := array.NewTableFromRecords(schema, recs)
defer table.Release()
if !array.TableEqual(table, expected_table) {
return fmt.Errorf("read data isn't expected\n"+
"Expected:\n"+
"%s\n"+
"num-rows: %d\n"+
"num-cols: %d\n"+
"Actual:\n"+
"%s\n"+
"num-rows: %d\n"+
"num-cols: %d",
expected_table.Schema(),
expected_table.NumRows(),
expected_table.NumCols(),
table.Schema(),
table.NumRows(),
table.NumCols())
}
return nil
}
func (o *orderedScenarioTester) MakeServer(port int) flight.Server {
srv := flight.NewServerWithMiddleware(nil)
srv.RegisterFlightService(o)
initServer(port, srv)
return srv
}
func (o *orderedScenarioTester) GetFlightInfo(ctx context.Context, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
ordered := desc.Type == flight.DescriptorCMD && string(desc.Cmd) == "ordered"
schema := arrow.NewSchema(
[]arrow.Field{
{Name: "number", Type: arrow.PrimitiveTypes.Int32},
},
nil,
)
return &flight.FlightInfo{
Schema: flight.SerializeSchema(schema, memory.DefaultAllocator),
FlightDescriptor: desc,
Endpoint: []*flight.FlightEndpoint{
{
Ticket: &flight.Ticket{Ticket: []byte("1")},
Location: []*flight.Location{},
},
{
Ticket: &flight.Ticket{Ticket: []byte("2")},
Location: []*flight.Location{},
},
{
Ticket: &flight.Ticket{Ticket: []byte("3")},
Location: []*flight.Location{},
},
},
TotalRecords: -1,
TotalBytes: -1,
Ordered: ordered,
}, nil
}
func (o *orderedScenarioTester) DoGet(tkt *flight.Ticket, fs flight.FlightService_DoGetServer) error {
schema := arrow.NewSchema(
[]arrow.Field{
{Name: "number", Type: arrow.PrimitiveTypes.Int32},
},
nil,
)
b := array.NewRecordBuilder(memory.DefaultAllocator, schema)
defer b.Release()
if string(tkt.GetTicket()) == "1" {
b.Field(0).(*array.Int32Builder).AppendValues([]int32{1, 2, 3}, nil)
} else if string(tkt.GetTicket()) == "2" {
b.Field(0).(*array.Int32Builder).AppendValues([]int32{10, 20, 30}, nil)
} else if string(tkt.GetTicket()) == "3" {
b.Field(0).(*array.Int32Builder).AppendValues([]int32{100, 200, 300}, nil)
}
w := flight.NewRecordWriter(fs, ipc.WithSchema(schema))
rec := b.NewRecord()
defer rec.Release()
w.Write(rec)
return nil
}
type expirationTimeEndpointStatus struct {
expirationTime *time.Time
numGets uint32
cancelled bool
}
type expirationTimeScenarioTester struct {
flight.BaseFlightServer
statuses map[int]expirationTimeEndpointStatus
}
func (tester *expirationTimeScenarioTester) MakeServer(port int) flight.Server {
srv := flight.NewServerWithMiddleware(nil)
srv.RegisterFlightService(tester)
initServer(port, srv)
return srv
}
func (tester *expirationTimeScenarioTester) AppendGetFlightInfo(endpoints []*flight.FlightEndpoint, ticket string, expirationTime *time.Time) []*flight.FlightEndpoint {
index := len(tester.statuses)
endpoint := flight.FlightEndpoint{
Ticket: &flight.Ticket{Ticket: []byte(strconv.Itoa(index) + ": " + ticket)},
Location: []*flight.Location{},
}
if expirationTime != nil {
endpoint.ExpirationTime = timestamppb.New(*expirationTime)
}
endpoints = append(endpoints, &endpoint)
tester.statuses[index] = expirationTimeEndpointStatus{
expirationTime: expirationTime,
numGets: 0,
cancelled: false,
}
return endpoints
}
func (tester *expirationTimeScenarioTester) ExtractIndexFromTicket(ticket string) (int, error) {
indexString := strings.SplitN(ticket, ":", 2)[0]
index, err := strconv.Atoi(indexString)
if err != nil {
return 0, fmt.Errorf("invalid flight: no index: %s: %s", ticket, err)
}
if index >= len(tester.statuses) {
return 0, fmt.Errorf("invalid flight: out of index: %s", ticket)
}
return index, nil
}
func (tester *expirationTimeScenarioTester) GetFlightInfo(ctx context.Context, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
tester.statuses = make(map[int]expirationTimeEndpointStatus)
schema := arrow.NewSchema(
[]arrow.Field{
{Name: "number", Type: arrow.PrimitiveTypes.Uint32},
},
nil,
)
var endpoints []*flight.FlightEndpoint
endpoints = tester.AppendGetFlightInfo(endpoints, "No expiration time", nil)
expirationTime5 := time.Now().Add(time.Second * 5)
endpoints = tester.AppendGetFlightInfo(endpoints, "5 seconds", &expirationTime5)
expirationTime6 := time.Now().Add(time.Second * 6)
endpoints = tester.AppendGetFlightInfo(endpoints, "6 seconds", &expirationTime6)
return &flight.FlightInfo{
Schema: flight.SerializeSchema(schema, memory.DefaultAllocator),
FlightDescriptor: desc,
Endpoint: endpoints,
TotalRecords: -1,
TotalBytes: -1,
}, nil
}
func (tester *expirationTimeScenarioTester) DoGet(tkt *flight.Ticket, fs flight.FlightService_DoGetServer) error {
ticket := string(tkt.GetTicket())
index, err := tester.ExtractIndexFromTicket(ticket)
if err != nil {
return err
}
st := tester.statuses[index]
if st.cancelled {
return status.Errorf(codes.InvalidArgument,
"Invalid flight: cancelled: %s", ticket)
}
if st.expirationTime == nil {
if st.numGets > 0 {
return status.Errorf(codes.InvalidArgument,
"Invalid flight: "+
"can't read multiple times: %s", ticket)
}
} else {
availableDuration := time.Until(*st.expirationTime)
if availableDuration < 0 {
return status.Errorf(codes.InvalidArgument,
"Invalid flight: expired: %s", ticket)
}
}
st.numGets++
tester.statuses[index] = st
schema := arrow.NewSchema(
[]arrow.Field{
{Name: "number", Type: arrow.PrimitiveTypes.Uint32},
},
nil,
)
b := array.NewRecordBuilder(memory.DefaultAllocator, schema)
defer b.Release()
b.Field(0).(*array.Uint32Builder).AppendValues([]uint32{uint32(index)}, nil)
w := flight.NewRecordWriter(fs, ipc.WithSchema(schema))
rec := b.NewRecord()
defer rec.Release()
w.Write(rec)
return nil
}
func (tester *expirationTimeScenarioTester) ListActions(_ *flight.Empty, stream flight.FlightService_ListActionsServer) error {
actions := []string{
flight.CancelFlightInfoActionType,
flight.RenewFlightEndpointActionType,
}
for _, a := range actions {
if err := stream.Send(&flight.ActionType{Type: a}); err != nil {
return err
}
}
return nil
}
func packActionResult(msg proto.Message) (*flight.Result, error) {
ret := &flight.Result{}
var err error
if ret.Body, err = proto.Marshal(msg); err != nil {
return nil, fmt.Errorf("%w: unable to marshal final response", err)
}
return ret, nil
}
func (tester *expirationTimeScenarioTester) DoAction(cmd *flight.Action, stream flight.FlightService_DoActionServer) error {
switch cmd.Type {
case flight.CancelFlightInfoActionType:
var request flight.CancelFlightInfoRequest
if err := proto.Unmarshal(cmd.Body, &request); err != nil {
return status.Errorf(codes.InvalidArgument, "unable to parse command: %s", err.Error())
}
cancelStatus := flight.CancelStatusUnspecified
for _, ep := range request.Info.Endpoint {
ticket := string(ep.Ticket.Ticket)
index, err := tester.ExtractIndexFromTicket(ticket)
if err == nil {
st := tester.statuses[index]
if st.cancelled {
cancelStatus = flight.CancelStatusNotCancellable
} else {
st.cancelled = true
if cancelStatus == flight.CancelStatusUnspecified {
cancelStatus = flight.CancelStatusCancelled
}
tester.statuses[index] = st
}
} else {
cancelStatus = flight.CancelStatusNotCancellable
}
}
result := flight.CancelFlightInfoResult{Status: cancelStatus}
out, err := packActionResult(&result)
if err != nil {
return err
}
if err = stream.Send(out); err != nil {
return err
}
return nil
case flight.RenewFlightEndpointActionType:
var request flight.RenewFlightEndpointRequest
if err := proto.Unmarshal(cmd.Body, &request); err != nil {
return status.Errorf(codes.InvalidArgument, "unable to parse command: %s", err.Error())
}
endpoint := request.Endpoint
ticket := string(endpoint.Ticket.Ticket)
index, err := tester.ExtractIndexFromTicket(ticket)
if err != nil {
return err
}
endpoint.Ticket.Ticket = []byte(string(endpoint.Ticket.Ticket) + ": renewed (+ 10 seconds)")
renewedExpirationTime := time.Now().Add(time.Second * 10)
endpoint.ExpirationTime = timestamppb.New(renewedExpirationTime)
st := tester.statuses[index]
st.expirationTime = &renewedExpirationTime
tester.statuses[index] = st
out, err := packActionResult(endpoint)
if err != nil {
return err
}
if err = stream.Send(out); err != nil {
return err
}
return nil
default:
return status.Errorf(codes.InvalidArgument, "unsupported action: %s", cmd.Type)
}
}
type expirationTimeDoGetScenarioTester struct {
expirationTimeScenarioTester
}
func (tester *expirationTimeDoGetScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flight.NewClientWithMiddleware(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
ctx := context.Background()
info, err := client.GetFlightInfo(ctx, &flight.FlightDescriptor{Type: flight.DescriptorCMD, Cmd: []byte("expiration_time")})
if err != nil {
return err
}
var recs []arrow.Record
for _, ep := range info.Endpoint {
if len(recs) == 0 {
if ep.ExpirationTime != nil {
return fmt.Errorf("endpoints[0] must not have " +
"expiration time")
}
} else {
if ep.ExpirationTime == nil {
return fmt.Errorf("endpoints[1] must have " +
"expiration time")
}
}
if len(ep.Location) != 0 {
return fmt.Errorf("expected to receive empty locations to use the original service: %s",
ep.Location)
}
stream, err := client.DoGet(ctx, ep.Ticket)
if err != nil {
return err
}
rdr, err := flight.NewRecordReader(stream)
if err != nil {
return err
}
defer rdr.Release()
for rdr.Next() {
record := rdr.Record()
record.Retain()
defer record.Release()
recs = append(recs, record)
}
if rdr.Err() != nil {
return rdr.Err()
}
}
// Build expected records
mem := memory.DefaultAllocator
schema := arrow.NewSchema(
[]arrow.Field{
{Name: "number", Type: arrow.PrimitiveTypes.Uint32},
},
nil,
)
expectedTable, _ := array.TableFromJSON(mem, schema, []string{
`[{"number": 0}]`,
`[{"number": 1}]`,
`[{"number": 2}]`,
})
defer expectedTable.Release()
table := array.NewTableFromRecords(schema, recs)
defer table.Release()
if !array.TableEqual(table, expectedTable) {
return fmt.Errorf("read data isn't expected\n"+
"Expected:\n"+
"%s\n"+
"numRows: %d\n"+
"numCols: %d\n"+
"Actual:\n"+
"%s\n"+
"numRows: %d\n"+
"numCols: %d",
expectedTable.Schema(),
expectedTable.NumRows(),
expectedTable.NumCols(),
table.Schema(),
table.NumRows(),
table.NumCols())
}
return nil
}
type expirationTimeListActionsScenarioTester struct {
expirationTimeScenarioTester
}
func (tester *expirationTimeListActionsScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flight.NewClientWithMiddleware(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
ctx := context.Background()
stream, err := client.ListActions(ctx, &flight.Empty{})
if err != nil {
return err
}
var actionTypeNames []string
for {
actionType, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return err
}
actionTypeNames = append(actionTypeNames, actionType.Type)
}
sort.Strings(actionTypeNames)
expectedActionTypeNames := []string{
"CancelFlightInfo",
"RenewFlightEndpoint",
}
if !reflect.DeepEqual(actionTypeNames, expectedActionTypeNames) {
return fmt.Errorf("action types aren't expected\n"+
"Expected:\n"+
"%s\n"+
"Actual:\n"+
"%s",
expectedActionTypeNames,
actionTypeNames)
}
return nil
}
type expirationTimeCancelFlightInfoScenarioTester struct {
expirationTimeScenarioTester
}
func (tester *expirationTimeCancelFlightInfoScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flight.NewClientWithMiddleware(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
ctx := context.Background()
info, err := client.GetFlightInfo(ctx, &flight.FlightDescriptor{Type: flight.DescriptorCMD, Cmd: []byte("expiration_time")})
if err != nil {
return err
}
request := flight.CancelFlightInfoRequest{Info: info}
result, err := client.CancelFlightInfo(ctx, &request)
if err != nil && !errors.Is(err, io.EOF) {
return err
}
if result.Status != flight.CancelStatusCancelled {
return fmt.Errorf("invalid: CancelFlightInfo must return CANCEL_STATUS_CANCELLED: %s", result.Status)
}
for _, ep := range info.Endpoint {
stream, err := client.DoGet(ctx, ep.Ticket)
if err != nil {
return err
}
rdr, err := flight.NewRecordReader(stream)
if err == nil {
rdr.Release()
return fmt.Errorf("invalid: DoGet after CancelFlightInfo must be failed")
}
}
return nil
}
type expirationTimeRenewFlightEndpointScenarioTester struct {
expirationTimeScenarioTester
}
func (tester *expirationTimeRenewFlightEndpointScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flight.NewClientWithMiddleware(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
ctx := context.Background()
info, err := client.GetFlightInfo(ctx, &flight.FlightDescriptor{Type: flight.DescriptorCMD, Cmd: []byte("expiration_time")})
if err != nil {
return err
}
// Renew all endpoints that have expiration time
for _, ep := range info.Endpoint {
if ep.ExpirationTime == nil {
continue
}
expirationTime := ep.ExpirationTime.AsTime()
request := flight.RenewFlightEndpointRequest{Endpoint: ep}
renewedEndpoint, err := client.RenewFlightEndpoint(ctx, &request)
if err != nil {
return err
}
if renewedEndpoint.ExpirationTime == nil {
return fmt.Errorf("renewed endpoint must have expiration time: %s",
renewedEndpoint)
}
renewedExpirationTime := renewedEndpoint.ExpirationTime.AsTime()
if renewedExpirationTime.Sub(expirationTime) <= 0 {
return fmt.Errorf("renewed endpoint must have newer expiration time\n"+
"Original: %s\nRenewed: %s",
ep, renewedEndpoint)
}
}
return nil
}
type locationReuseConnectionScenarioTester struct {
flight.BaseFlightServer
}
func (m *locationReuseConnectionScenarioTester) GetFlightInfo(ctx context.Context, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
return &flight.FlightInfo{
Schema: flight.SerializeSchema(arrow.NewSchema([]arrow.Field{}, nil), memory.DefaultAllocator),
FlightDescriptor: desc,
Endpoint: []*flight.FlightEndpoint{{
Ticket: &flight.Ticket{Ticket: []byte("reuse")},
Location: []*flight.Location{{Uri: flight.LocationReuseConnection}},
}},
TotalRecords: -1,
TotalBytes: -1,
}, nil
}
func (tester *locationReuseConnectionScenarioTester) MakeServer(port int) flight.Server {
srv := flight.NewServerWithMiddleware(nil)
srv.RegisterFlightService(tester)
initServer(port, srv)
return srv
}
func (tester *locationReuseConnectionScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flight.NewClientWithMiddleware(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
ctx := context.Background()
info, err := client.GetFlightInfo(ctx, &flight.FlightDescriptor{Type: flight.DescriptorCMD, Cmd: []byte("reuse")})
if err != nil {
return err
}
if len(info.Endpoint) != 1 {
return fmt.Errorf("expected 1 endpoint, got %d", len(info.Endpoint))
}
endpoint := info.Endpoint[0]
if len(endpoint.Location) != 1 {
return fmt.Errorf("expected 1 location, got %d", len(endpoint.Location))
} else if endpoint.Location[0].Uri != flight.LocationReuseConnection {
return fmt.Errorf("expected %s, got %s", flight.LocationReuseConnection, endpoint.Location[0].Uri)
}
return nil
}
type pollFlightInfoScenarioTester struct {
flight.BaseFlightServer
}
func (tester *pollFlightInfoScenarioTester) MakeServer(port int) flight.Server {
srv := flight.NewServerWithMiddleware(nil)
srv.RegisterFlightService(tester)
initServer(port, srv)
return srv
}
func (tester *pollFlightInfoScenarioTester) PollFlightInfo(ctx context.Context, desc *flight.FlightDescriptor) (*flight.PollInfo, error) {
schema := arrow.NewSchema(
[]arrow.Field{
{Name: "number", Type: arrow.PrimitiveTypes.Uint32},
},
nil,
)
endpoints := []*flight.FlightEndpoint{
{
Ticket: &flight.Ticket{Ticket: []byte("long-running query")},
Location: []*flight.Location{},
},
}
info := &flight.FlightInfo{
Schema: flight.SerializeSchema(schema, memory.DefaultAllocator),
FlightDescriptor: desc,
Endpoint: endpoints,
TotalRecords: -1,
TotalBytes: -1,
}
pollDesc := flight.FlightDescriptor{
Type: flight.DescriptorCMD,
Cmd: []byte("poll"),
}
if desc.Type == pollDesc.Type && string(desc.Cmd) == string(pollDesc.Cmd) {
progress := float64(1.0)
return &flight.PollInfo{
Info: info,
FlightDescriptor: nil,
Progress: &progress,
ExpirationTime: nil,
}, nil
} else {
progress := float64(0.1)
return &flight.PollInfo{
Info: info,
FlightDescriptor: &pollDesc,
Progress: &progress,
ExpirationTime: timestamppb.New(time.Now().Add(time.Second * 10)),
}, nil
}
}
func (tester *pollFlightInfoScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flight.NewClientWithMiddleware(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
ctx := context.Background()
desc := flight.FlightDescriptor{
Type: flight.DescriptorCMD,
Cmd: []byte("heavy query"),
}
info, err := client.PollFlightInfo(ctx, &desc)
if err != nil {
return err
}
switch {
case info.FlightDescriptor == nil:
return fmt.Errorf("description is missing: %s", info.String())
case info.Progress == nil:
return fmt.Errorf("progress is missing: %s", info.String())
case !(0.0 <= *info.Progress && *info.Progress <= 1.0):
return fmt.Errorf("invalid progress: %s", info.String())
case info.ExpirationTime == nil:
return fmt.Errorf("expiration time is missing: %s", info.String())
}
info, err = client.PollFlightInfo(ctx, info.FlightDescriptor)
if err != nil {
return err
}
switch {
case info.FlightDescriptor != nil:
return fmt.Errorf("retried but no finished yet: %s", info.String())
case info.Progress == nil:
return fmt.Errorf("progress is missing in finished query: %s",
info.String())
case math.Abs(*info.Progress-1.0) > 1e-5:
return fmt.Errorf("progress for finished query isn't 1.0: %s",
info.String())
case info.ExpirationTime != nil:
return fmt.Errorf("expiration time must not be set for finished query: %s",
info.String())
}
return nil
}
type appMetadataFlightInfoEndpointScenarioTester struct {
flight.BaseFlightServer
}
func (tester *appMetadataFlightInfoEndpointScenarioTester) MakeServer(port int) flight.Server {
srv := flight.NewServerWithMiddleware(nil)
srv.RegisterFlightService(tester)
initServer(port, srv)
return srv
}
func (tester *appMetadataFlightInfoEndpointScenarioTester) GetFlightInfo(ctx context.Context, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
schema := arrow.NewSchema(
[]arrow.Field{
{Name: "number", Type: arrow.PrimitiveTypes.Uint32},
},
nil,
)
if desc.Type != flight.DescriptorCMD {
return nil, fmt.Errorf("%w: should have received CMD descriptor", arrow.ErrInvalid)
}
endpoints := []*flight.FlightEndpoint{{AppMetadata: desc.Cmd}}
return &flight.FlightInfo{
Schema: flight.SerializeSchema(schema, memory.DefaultAllocator),
FlightDescriptor: desc,
Endpoint: endpoints,
TotalRecords: -1,
TotalBytes: -1,
AppMetadata: desc.Cmd,
}, nil
}
func (tester *appMetadataFlightInfoEndpointScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flight.NewClientWithMiddleware(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
ctx := context.Background()
desc := flight.FlightDescriptor{
Type: flight.DescriptorCMD,
Cmd: []byte("foobar"),
}
info, err := client.GetFlightInfo(ctx, &desc)
if err != nil {
return err
}
switch {
case !bytes.Equal(desc.Cmd, info.AppMetadata):
return fmt.Errorf("invalid flight info app_metadata: %s, expected: %s", info.AppMetadata, desc.Cmd)
case len(info.Endpoint) != 1:
return fmt.Errorf("expected exactly 1 flight endpoint, got: %d", len(info.Endpoint))
case !bytes.Equal(desc.Cmd, info.Endpoint[0].AppMetadata):
return fmt.Errorf("invalid flight endpoint app_metadata: %s, expected: %s", info.Endpoint[0].AppMetadata, desc.Cmd)
}
return nil
}
const (
updateStatementExpectedRows int64 = 10000
updateStatementWithTransactionExpectedRows int64 = 15000
updatePreparedStatementExpectedRows int64 = 20000
updatePreparedStatementWithTransactionExpectedRows int64 = 25000
ingestStatementExpectedRows int64 = 3
)
type flightSqlScenarioTester struct {
flightsql.BaseServer
}
func (m *flightSqlScenarioTester) flightInfoForCommand(desc *flight.FlightDescriptor, schema *arrow.Schema) *flight.FlightInfo {
return &flight.FlightInfo{
Endpoint: []*flight.FlightEndpoint{
{Ticket: &flight.Ticket{Ticket: desc.Cmd}},
},
Schema: flight.SerializeSchema(schema, memory.DefaultAllocator),
FlightDescriptor: desc,
TotalRecords: -1,
TotalBytes: -1,
}
}
func (m *flightSqlScenarioTester) MakeServer(port int) flight.Server {
srv := flight.NewServerWithMiddleware(nil)
m.RegisterSqlInfo(flightsql.SqlInfoFlightSqlServerSql, false)
m.RegisterSqlInfo(flightsql.SqlInfoFlightSqlServerSubstrait, true)
m.RegisterSqlInfo(flightsql.SqlInfoFlightSqlServerSubstraitMinVersion, "min_version")
m.RegisterSqlInfo(flightsql.SqlInfoFlightSqlServerSubstraitMaxVersion, "max_version")
m.RegisterSqlInfo(flightsql.SqlInfoFlightSqlServerTransaction, int32(flightsql.SqlTransactionSavepoint))
m.RegisterSqlInfo(flightsql.SqlInfoFlightSqlServerCancel, true)
m.RegisterSqlInfo(flightsql.SqlInfoFlightSqlServerStatementTimeout, int32(42))
m.RegisterSqlInfo(flightsql.SqlInfoFlightSqlServerTransactionTimeout, int32(7))
srv.RegisterFlightService(flightsql.NewFlightServer(m))
initServer(port, srv)
return srv
}
func assertEq(expected, actual interface{}) error {
v := reflect.Indirect(reflect.ValueOf(actual))
if !reflect.DeepEqual(expected, v.Interface()) {
return fmt.Errorf("expected: '%s', got: '%s'", expected, actual)
}
return nil
}
func (m *flightSqlScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flightsql.NewClient(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
if err := m.ValidateMetadataRetrieval(client); err != nil {
return err
}
if err := m.ValidateStatementExecution(client); err != nil {
return err
}
return m.ValidatePreparedStatementExecution(client)
}
func (m *flightSqlScenarioTester) validate(expected *arrow.Schema, result *flight.FlightInfo, client *flightsql.Client) error {
rdr, err := client.DoGet(context.Background(), result.Endpoint[0].Ticket)
if err != nil {
return err
}
if !expected.Equal(rdr.Schema()) {
return fmt.Errorf("expected: %s, got: %s", expected, rdr.Schema())
}
for {
_, err := rdr.Read()
if err == io.EOF {
break
}
if err != nil {
return err
}
}
return nil
}
func (m *flightSqlScenarioTester) validateSchema(expected *arrow.Schema, result *flight.SchemaResult) error {
schema, err := flight.DeserializeSchema(result.GetSchema(), memory.DefaultAllocator)
if err != nil {
return err
}
if !expected.Equal(schema) {
return fmt.Errorf("expected: %s, got: %s", expected, schema)
}
return nil
}
func (m *flightSqlScenarioTester) ValidateMetadataRetrieval(client *flightsql.Client) error {
var (
catalog = "catalog"
dbSchemaFilterPattern = "db_schema_filter_pattern"
tableFilterPattern = "table_filter_pattern"
table = "table"
dbSchema = "db_schema"
tableTypes = []string{"table", "view"}
ref = flightsql.TableRef{Catalog: &catalog, DBSchema: &dbSchema, Table: table}
pkRef = flightsql.TableRef{Catalog: proto.String("pk_catalog"), DBSchema: proto.String("pk_db_schema"), Table: "pk_table"}
fkRef = flightsql.TableRef{Catalog: proto.String("fk_catalog"), DBSchema: proto.String("fk_db_schema"), Table: "fk_table"}
ctx = context.Background()
)
info, err := client.GetCatalogs(ctx)
if err != nil {
return err
}
if err := m.validate(schema_ref.Catalogs, info, client); err != nil {
return err
}
schema, err := client.GetCatalogsSchema(ctx)
if err != nil {
return err
}
if err := m.validateSchema(schema_ref.Catalogs, schema); err != nil {
return err
}
info, err = client.GetDBSchemas(ctx, &flightsql.GetDBSchemasOpts{Catalog: &catalog, DbSchemaFilterPattern: &dbSchemaFilterPattern})
if err != nil {
return err
}
if err = m.validate(schema_ref.DBSchemas, info, client); err != nil {
return err
}
schema, err = client.GetDBSchemasSchema(ctx)
if err != nil {
return err
}
if err = m.validateSchema(schema_ref.DBSchemas, schema); err != nil {
return err
}
info, err = client.GetTables(ctx, &flightsql.GetTablesOpts{Catalog: &catalog, DbSchemaFilterPattern: &dbSchemaFilterPattern, TableNameFilterPattern: &tableFilterPattern, IncludeSchema: true, TableTypes: tableTypes})
if err != nil {
return err
}
if err = m.validate(schema_ref.TablesWithIncludedSchema, info, client); err != nil {
return err
}
schema, err = client.GetTablesSchema(ctx, &flightsql.GetTablesOpts{IncludeSchema: true})
if err != nil {
return err
}
if err = m.validateSchema(schema_ref.TablesWithIncludedSchema, schema); err != nil {
return err
}
schema, err = client.GetTablesSchema(ctx, &flightsql.GetTablesOpts{IncludeSchema: false})
if err != nil {
return err
}
if err = m.validateSchema(schema_ref.Tables, schema); err != nil {
return err
}
info, err = client.GetTableTypes(ctx)
if err != nil {
return err
}
if err = m.validate(schema_ref.TableTypes, info, client); err != nil {
return err
}
schema, err = client.GetTableTypesSchema(ctx)
if err != nil {
return err
}
if err = m.validateSchema(schema_ref.TableTypes, schema); err != nil {
return err
}
info, err = client.GetPrimaryKeys(ctx, ref)
if err != nil {
return err
}
if err = m.validate(schema_ref.PrimaryKeys, info, client); err != nil {
return err
}
schema, err = client.GetPrimaryKeysSchema(ctx)
if err != nil {
return err
}
if err = m.validateSchema(schema_ref.PrimaryKeys, schema); err != nil {
return err
}
info, err = client.GetExportedKeys(ctx, ref)
if err != nil {
return err
}
if err = m.validate(schema_ref.ExportedKeys, info, client); err != nil {
return err
}
schema, err = client.GetExportedKeysSchema(ctx)
if err != nil {
return err
}
if err = m.validateSchema(schema_ref.ExportedKeys, schema); err != nil {
return err
}
info, err = client.GetImportedKeys(ctx, ref)
if err != nil {
return err
}
if err = m.validate(schema_ref.ImportedKeys, info, client); err != nil {
return err
}
schema, err = client.GetImportedKeysSchema(ctx)
if err != nil {
return err
}
if err = m.validateSchema(schema_ref.ImportedKeys, schema); err != nil {
return err
}
info, err = client.GetCrossReference(ctx, pkRef, fkRef)
if err != nil {
return err
}
if err = m.validate(schema_ref.CrossReference, info, client); err != nil {
return err
}
schema, err = client.GetCrossReferenceSchema(ctx)
if err != nil {
return err
}
if err = m.validateSchema(schema_ref.CrossReference, schema); err != nil {
return err
}
info, err = client.GetXdbcTypeInfo(ctx, nil)
if err != nil {
return err
}
if err = m.validate(schema_ref.XdbcTypeInfo, info, client); err != nil {
return err
}
schema, err = client.GetXdbcTypeInfoSchema(ctx)
if err != nil {
return err
}
if err = m.validateSchema(schema_ref.XdbcTypeInfo, schema); err != nil {
return err
}
info, err = client.GetSqlInfo(ctx, []flightsql.SqlInfo{flightsql.SqlInfoFlightSqlServerName, flightsql.SqlInfoFlightSqlServerReadOnly})
if err != nil {
return err
}
if err = m.validate(schema_ref.SqlInfo, info, client); err != nil {
return err
}
schema, err = client.GetSqlInfoSchema(ctx)
if err != nil {
return err
}
if err = m.validateSchema(schema_ref.SqlInfo, schema); err != nil {
return err
}
return nil
}
func (m *flightSqlScenarioTester) ValidateStatementExecution(client *flightsql.Client) error {
ctx := context.Background()
info, err := client.Execute(ctx, "SELECT STATEMENT")
if err != nil {
return err
}
if err = m.validate(getQuerySchema(), info, client); err != nil {
return err
}
schema, err := client.GetExecuteSchema(ctx, "SELECT STATEMENT")
if err != nil {
return err
}
if err = m.validateSchema(getQuerySchema(), schema); err != nil {
return err
}
updateResult, err := client.ExecuteUpdate(ctx, "UPDATE STATEMENT")
if err != nil {
return err
}
if updateResult != updateStatementExpectedRows {
return fmt.Errorf("expected 'UPDATE STATEMENT' return %d got %d", updateStatementExpectedRows, updateResult)
}
return nil
}
func (m *flightSqlScenarioTester) ValidatePreparedStatementExecution(client *flightsql.Client) error {
ctx := context.Background()
prepared, err := client.Prepare(ctx, "SELECT PREPARED STATEMENT")
if err != nil {
return err
}
arr, _, _ := array.FromJSON(memory.DefaultAllocator, arrow.PrimitiveTypes.Int64, strings.NewReader("[1]"))
defer arr.Release()
params := array.NewRecord(getQuerySchema(), []arrow.Array{arr}, 1)
defer params.Release()
prepared.SetParameters(params)
info, err := prepared.Execute(ctx)
if err != nil {
return err
}
if err = m.validate(getQuerySchema(), info, client); err != nil {
return err
}
schema, err := prepared.GetSchema(ctx)
if err != nil {
return err
}
if err = m.validateSchema(getQuerySchema(), schema); err != nil {
return err
}
if err = prepared.Close(ctx); err != nil {
return err
}
updatePrepared, err := client.Prepare(ctx, "UPDATE PREPARED STATEMENT")
if err != nil {
return err
}
updateResult, err := updatePrepared.ExecuteUpdate(ctx)
if err != nil {
return err
}
if updateResult != updatePreparedStatementExpectedRows {
return fmt.Errorf("expected 'UPDATE STATEMENT' return %d got %d", updatePreparedStatementExpectedRows, updateResult)
}
return updatePrepared.Close(ctx)
}
func (m *flightSqlScenarioTester) doGetForTestCase(schema *arrow.Schema) chan flight.StreamChunk {
ch := make(chan flight.StreamChunk)
close(ch)
return ch
}
func (m *flightSqlScenarioTester) GetFlightInfoStatement(ctx context.Context, cmd flightsql.StatementQuery, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
if err := assertEq(selectStatement, cmd.GetQuery()); err != nil {
return nil, err
}
var (
ticket []byte
schema *arrow.Schema
)
if len(cmd.GetTransactionId()) == 0 {
ticket = []byte("SELECT STATEMENT HANDLE")
schema = getQuerySchema()
} else {
ticket = []byte("SELECT STATEMENT WITH TXN HANDLE")
schema = getQueryWithTransactionSchema()
}
handle, err := flightsql.CreateStatementQueryTicket(ticket)
if err != nil {
return nil, err
}
return &flight.FlightInfo{
Endpoint: []*flight.FlightEndpoint{
{Ticket: &flight.Ticket{Ticket: handle}},
},
Schema: flight.SerializeSchema(schema, memory.DefaultAllocator),
FlightDescriptor: desc,
TotalRecords: -1,
TotalBytes: -1,
}, nil
}
func (m *flightSqlScenarioTester) GetFlightInfoSubstraitPlan(ctx context.Context, cmd flightsql.StatementSubstraitPlan, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
if err := assertEq([]byte(substraitPlanText), cmd.GetPlan().Plan); err != nil {
return nil, fmt.Errorf("%w: unexpected plan in GetFlightInfoSubstraitPlan", err)
}
if err := assertEq(substraitPlanVersion, cmd.GetPlan().Version); err != nil {
return nil, fmt.Errorf("%w: unexpected version in GetFlightInfoSubstraitPlan", err)
}
var (
ticket []byte
schema *arrow.Schema
)
if len(cmd.GetTransactionId()) == 0 {
ticket = []byte("PLAN HANDLE")
schema = getQuerySchema()
} else {
ticket = []byte("PLAN WITH TXN HANDLE")
schema = getQueryWithTransactionSchema()
}
handle, err := flightsql.CreateStatementQueryTicket(ticket)
if err != nil {
return nil, err
}
return &flight.FlightInfo{
Endpoint: []*flight.FlightEndpoint{
{Ticket: &flight.Ticket{Ticket: handle}},
},
Schema: flight.SerializeSchema(schema, memory.DefaultAllocator),
FlightDescriptor: desc,
TotalRecords: -1,
TotalBytes: -1,
}, nil
}
func (m *flightSqlScenarioTester) GetSchemaStatement(ctx context.Context, cmd flightsql.StatementQuery, desc *flight.FlightDescriptor) (*flight.SchemaResult, error) {
if err := assertEq(selectStatement, cmd.GetQuery()); err != nil {
return nil, fmt.Errorf("%w: unexpected statement in GetSchemaStatement", err)
}
if len(cmd.GetTransactionId()) == 0 {
return &flight.SchemaResult{Schema: flight.SerializeSchema(getQuerySchema(), memory.DefaultAllocator)}, nil
}
return &flight.SchemaResult{Schema: flight.SerializeSchema(getQueryWithTransactionSchema(), memory.DefaultAllocator)}, nil
}
func (m *flightSqlScenarioTester) GetSchemaSubstraitPlan(ctx context.Context, cmd flightsql.StatementSubstraitPlan, desc *flight.FlightDescriptor) (*flight.SchemaResult, error) {
if err := assertEq([]byte(substraitPlanText), cmd.GetPlan().Plan); err != nil {
return nil, fmt.Errorf("%w: unexpected plan in GetFlightInfoSubstraitPlan", err)
}
if err := assertEq(substraitPlanVersion, cmd.GetPlan().Version); err != nil {
return nil, fmt.Errorf("%w: unexpected version in GetFlightInfoSubstraitPlan", err)
}
if len(cmd.GetTransactionId()) == 0 {
return &flight.SchemaResult{Schema: flight.SerializeSchema(getQuerySchema(), memory.DefaultAllocator)}, nil
}
return &flight.SchemaResult{Schema: flight.SerializeSchema(getQueryWithTransactionSchema(), memory.DefaultAllocator)}, nil
}
func (m *flightSqlScenarioTester) DoGetStatement(ctx context.Context, cmd flightsql.StatementQueryTicket) (*arrow.Schema, <-chan flight.StreamChunk, error) {
switch string(cmd.GetStatementHandle()) {
case "SELECT STATEMENT HANDLE", "PLAN HANDLE":
return getQuerySchema(), m.doGetForTestCase(getQuerySchema()), nil
case "SELECT STATEMENT WITH TXN HANDLE", "PLAN WITH TXN HANDLE":
return getQueryWithTransactionSchema(), m.doGetForTestCase(getQueryWithTransactionSchema()), nil
}
return nil, nil, fmt.Errorf("%w: unknown handle %s", arrow.ErrInvalid, string(cmd.GetStatementHandle()))
}
func (m *flightSqlScenarioTester) GetFlightInfoPreparedStatement(_ context.Context, cmd flightsql.PreparedStatementQuery, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
switch string(cmd.GetPreparedStatementHandle()) {
case "SELECT PREPARED STATEMENT HANDLE", "PLAN HANDLE":
return m.flightInfoForCommand(desc, getQuerySchema()), nil
case "SELECT PREPARED STATEMENT WITH TXN HANDLE", "PLAN WITH TXN HANDLE":
return m.flightInfoForCommand(desc, getQueryWithTransactionSchema()), nil
}
return nil, fmt.Errorf("%w: invalid handle for GetFlightInfoPreparedStatement %s",
arrow.ErrInvalid, string(cmd.GetPreparedStatementHandle()))
}
func (m *flightSqlScenarioTester) GetSchemaPreparedStatement(ctx context.Context, cmd flightsql.PreparedStatementQuery, desc *flight.FlightDescriptor) (*flight.SchemaResult, error) {
switch string(cmd.GetPreparedStatementHandle()) {
case "SELECT PREPARED STATEMENT HANDLE", "PLAN HANDLE":
return &flight.SchemaResult{Schema: flight.SerializeSchema(getQuerySchema(), memory.DefaultAllocator)}, nil
case "SELECT PREPARED STATEMENT WITH TXN HANDLE", "PLAN WITH TXN HANDLE":
return &flight.SchemaResult{Schema: flight.SerializeSchema(getQueryWithTransactionSchema(), memory.DefaultAllocator)}, nil
}
return nil, fmt.Errorf("%w: invalid handle for GetSchemaPreparedStatement %s",
arrow.ErrInvalid, string(cmd.GetPreparedStatementHandle()))
}
func (m *flightSqlScenarioTester) DoGetPreparedStatement(_ context.Context, cmd flightsql.PreparedStatementQuery) (*arrow.Schema, <-chan flight.StreamChunk, error) {
switch string(cmd.GetPreparedStatementHandle()) {
case "SELECT PREPARED STATEMENT HANDLE", "PLAN HANDLE":
return getQuerySchema(), m.doGetForTestCase(getQuerySchema()), nil
case "SELECT PREPARED STATEMENT WITH TXN HANDLE", "PLAN WITH TXN HANDLE":
return getQueryWithTransactionSchema(), m.doGetForTestCase(getQueryWithTransactionSchema()), nil
}
return nil, nil, fmt.Errorf("%w: invalid handle: %s",
arrow.ErrInvalid, string(cmd.GetPreparedStatementHandle()))
}
func (m *flightSqlScenarioTester) GetFlightInfoCatalogs(_ context.Context, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
return m.flightInfoForCommand(desc, schema_ref.Catalogs), nil
}
func (m *flightSqlScenarioTester) DoGetCatalogs(_ context.Context) (*arrow.Schema, <-chan flight.StreamChunk, error) {
return schema_ref.Catalogs, m.doGetForTestCase(schema_ref.Catalogs), nil
}
func (m *flightSqlScenarioTester) GetFlightInfoXdbcTypeInfo(_ context.Context, cmd flightsql.GetXdbcTypeInfo, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
return m.flightInfoForCommand(desc, schema_ref.XdbcTypeInfo), nil
}
func (m *flightSqlScenarioTester) DoGetXdbcTypeInfo(context.Context, flightsql.GetXdbcTypeInfo) (*arrow.Schema, <-chan flight.StreamChunk, error) {
return schema_ref.XdbcTypeInfo, m.doGetForTestCase(schema_ref.XdbcTypeInfo), nil
}
func (m *flightSqlScenarioTester) GetFlightInfoSqlInfo(ctx context.Context, cmd flightsql.GetSqlInfo, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
if len(cmd.GetInfo()) == 2 {
// integration test for the protocol messages
if err := assertEq(int(2), len(cmd.GetInfo())); err != nil {
return nil, err
}
if err := assertEq(flightsql.SqlInfoFlightSqlServerName, flightsql.SqlInfo(cmd.GetInfo()[0])); err != nil {
return nil, err
}
if err := assertEq(flightsql.SqlInfoFlightSqlServerReadOnly, flightsql.SqlInfo(cmd.GetInfo()[1])); err != nil {
return nil, err
}
return m.flightInfoForCommand(desc, schema_ref.SqlInfo), nil
}
// integration test for the values themselves
return m.BaseServer.GetFlightInfoSqlInfo(ctx, cmd, desc)
}
func (m *flightSqlScenarioTester) DoGetSqlInfo(ctx context.Context, cmd flightsql.GetSqlInfo) (*arrow.Schema, <-chan flight.StreamChunk, error) {
if len(cmd.GetInfo()) == 2 {
return schema_ref.SqlInfo, m.doGetForTestCase(schema_ref.SqlInfo), nil
}
return m.BaseServer.DoGetSqlInfo(ctx, cmd)
}
func (m *flightSqlScenarioTester) GetFlightInfoSchemas(_ context.Context, cmd flightsql.GetDBSchemas, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
if err := assertEq("catalog", cmd.GetCatalog()); err != nil {
return nil, err
}
if err := assertEq("db_schema_filter_pattern", cmd.GetDBSchemaFilterPattern()); err != nil {
return nil, err
}
return m.flightInfoForCommand(desc, schema_ref.DBSchemas), nil
}
func (m *flightSqlScenarioTester) DoGetDBSchemas(context.Context, flightsql.GetDBSchemas) (*arrow.Schema, <-chan flight.StreamChunk, error) {
return schema_ref.DBSchemas, m.doGetForTestCase(schema_ref.DBSchemas), nil
}
func (m *flightSqlScenarioTester) GetFlightInfoTables(_ context.Context, cmd flightsql.GetTables, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
if err := assertEq("catalog", cmd.GetCatalog()); err != nil {
return nil, err
}
if err := assertEq("db_schema_filter_pattern", cmd.GetDBSchemaFilterPattern()); err != nil {
return nil, err
}
if err := assertEq("table_filter_pattern", cmd.GetTableNameFilterPattern()); err != nil {
return nil, err
}
if err := assertEq(int(2), len(cmd.GetTableTypes())); err != nil {
return nil, err
}
if err := assertEq("table", cmd.GetTableTypes()[0]); err != nil {
return nil, err
}
if err := assertEq("view", cmd.GetTableTypes()[1]); err != nil {
return nil, err
}
if err := assertEq(true, cmd.GetIncludeSchema()); err != nil {
return nil, err
}
return m.flightInfoForCommand(desc, schema_ref.TablesWithIncludedSchema), nil
}
func (m *flightSqlScenarioTester) DoGetTables(context.Context, flightsql.GetTables) (*arrow.Schema, <-chan flight.StreamChunk, error) {
return schema_ref.TablesWithIncludedSchema, m.doGetForTestCase(schema_ref.TablesWithIncludedSchema), nil
}
func (m *flightSqlScenarioTester) GetFlightInfoTableTypes(_ context.Context, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
return m.flightInfoForCommand(desc, schema_ref.TableTypes), nil
}
func (m *flightSqlScenarioTester) DoGetTableTypes(context.Context) (*arrow.Schema, <-chan flight.StreamChunk, error) {
return schema_ref.TableTypes, m.doGetForTestCase(schema_ref.TableTypes), nil
}
func (m *flightSqlScenarioTester) GetFlightInfoPrimaryKeys(_ context.Context, cmd flightsql.TableRef, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
if err := assertEq("catalog", cmd.Catalog); err != nil {
return nil, err
}
if err := assertEq("db_schema", cmd.DBSchema); err != nil {
return nil, err
}
if err := assertEq("table", cmd.Table); err != nil {
return nil, err
}
return m.flightInfoForCommand(desc, schema_ref.PrimaryKeys), nil
}
func (m *flightSqlScenarioTester) DoGetPrimaryKeys(context.Context, flightsql.TableRef) (*arrow.Schema, <-chan flight.StreamChunk, error) {
return schema_ref.PrimaryKeys, m.doGetForTestCase(schema_ref.PrimaryKeys), nil
}
func (m *flightSqlScenarioTester) GetFlightInfoExportedKeys(_ context.Context, cmd flightsql.TableRef, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
if err := assertEq("catalog", cmd.Catalog); err != nil {
return nil, err
}
if err := assertEq("db_schema", cmd.DBSchema); err != nil {
return nil, err
}
if err := assertEq("table", cmd.Table); err != nil {
return nil, err
}
return m.flightInfoForCommand(desc, schema_ref.ExportedKeys), nil
}
func (m *flightSqlScenarioTester) DoGetExportedKeys(context.Context, flightsql.TableRef) (*arrow.Schema, <-chan flight.StreamChunk, error) {
return schema_ref.ExportedKeys, m.doGetForTestCase(schema_ref.ExportedKeys), nil
}
func (m *flightSqlScenarioTester) GetFlightInfoImportedKeys(_ context.Context, cmd flightsql.TableRef, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
if err := assertEq("catalog", cmd.Catalog); err != nil {
return nil, err
}
if err := assertEq("db_schema", cmd.DBSchema); err != nil {
return nil, err
}
if err := assertEq("table", cmd.Table); err != nil {
return nil, err
}
return m.flightInfoForCommand(desc, schema_ref.ImportedKeys), nil
}
func (m *flightSqlScenarioTester) DoGetImportedKeys(context.Context, flightsql.TableRef) (*arrow.Schema, <-chan flight.StreamChunk, error) {
return schema_ref.ImportedKeys, m.doGetForTestCase(schema_ref.ImportedKeys), nil
}
func (m *flightSqlScenarioTester) GetFlightInfoCrossReference(_ context.Context, cmd flightsql.CrossTableRef, desc *flight.FlightDescriptor) (*flight.FlightInfo, error) {
if err := assertEq("pk_catalog", cmd.PKRef.Catalog); err != nil {
return nil, err
}
if err := assertEq("pk_db_schema", cmd.PKRef.DBSchema); err != nil {
return nil, err
}
if err := assertEq("pk_table", cmd.PKRef.Table); err != nil {
return nil, err
}
if err := assertEq("fk_catalog", cmd.FKRef.Catalog); err != nil {
return nil, err
}
if err := assertEq("fk_db_schema", cmd.FKRef.DBSchema); err != nil {
return nil, err
}
if err := assertEq("fk_table", cmd.FKRef.Table); err != nil {
return nil, err
}
return m.flightInfoForCommand(desc, schema_ref.TableTypes), nil
}
func (m *flightSqlScenarioTester) DoGetCrossReference(context.Context, flightsql.CrossTableRef) (*arrow.Schema, <-chan flight.StreamChunk, error) {
return schema_ref.CrossReference, m.doGetForTestCase(schema_ref.CrossReference), nil
}
func (m *flightSqlScenarioTester) DoPutCommandStatementUpdate(_ context.Context, cmd flightsql.StatementUpdate) (int64, error) {
if err := assertEq("UPDATE STATEMENT", cmd.GetQuery()); err != nil {
return 0, err
}
if len(cmd.GetTransactionId()) == 0 {
return updateStatementExpectedRows, nil
}
return updateStatementWithTransactionExpectedRows, nil
}
func (m *flightSqlScenarioTester) DoPutCommandSubstraitPlan(_ context.Context, cmd flightsql.StatementSubstraitPlan) (int64, error) {
if err := assertEq([]byte(substraitPlanText), cmd.GetPlan().Plan); err != nil {
return 0, fmt.Errorf("%w: wrong plan for DoPutCommandSubstraitPlan", err)
}
if err := assertEq(substraitPlanVersion, cmd.GetPlan().Version); err != nil {
return 0, fmt.Errorf("%w: unexpected version in DoPutCommandSubstraitPlan", err)
}
if len(cmd.GetTransactionId()) == 0 {
return updateStatementExpectedRows, nil
}
return updateStatementWithTransactionExpectedRows, nil
}
func (m *flightSqlScenarioTester) CreatePreparedStatement(_ context.Context, request flightsql.ActionCreatePreparedStatementRequest) (res flightsql.ActionCreatePreparedStatementResult, err error) {
switch request.GetQuery() {
case "SELECT PREPARED STATEMENT", "UPDATE PREPARED STATEMENT":
default:
return res, fmt.Errorf("%w: unexpected query %s", arrow.ErrInvalid, request.GetQuery())
}
handle := request.GetQuery()
if len(request.GetTransactionId()) != 0 {
handle += " WITH TXN"
}
res.Handle = []byte(handle + " HANDLE")
return
}
func (m *flightSqlScenarioTester) CreatePreparedSubstraitPlan(_ context.Context, request flightsql.ActionCreatePreparedSubstraitPlanRequest) (res flightsql.ActionCreatePreparedStatementResult, err error) {
if err := assertEq([]byte(substraitPlanText), request.GetPlan().Plan); err != nil {
return res, fmt.Errorf("%w: wrong plan for CreatePreparedSubstraitPlan", err)
}
if err := assertEq(substraitPlanVersion, request.GetPlan().Version); err != nil {
return res, fmt.Errorf("%w: unexpected version in DoPutCommandSubstraitPlan", err)
}
if len(request.GetTransactionId()) == 0 {
res.Handle = []byte("PLAN HANDLE")
} else {
res.Handle = []byte("PLAN WITH TXN HANDLE")
}
return
}
func (m *flightSqlScenarioTester) ClosePreparedStatement(_ context.Context, request flightsql.ActionClosePreparedStatementRequest) error {
switch string(request.GetPreparedStatementHandle()) {
case "SELECT PREPARED STATEMENT HANDLE",
"UPDATE PREPARED STATEMENT HANDLE",
"PLAN HANDLE",
"SELECT PREPARED STATEMENT WITH TXN HANDLE",
"UPDATE PREPARED STATEMENT WITH TXN HANDLE",
"PLAN WITH TXN HANDLE":
default:
return fmt.Errorf("%w: invalid handle for ClosePreparedStatement: %s",
arrow.ErrInvalid, string(request.GetPreparedStatementHandle()))
}
return nil
}
func (m *flightSqlScenarioTester) DoPutPreparedStatementQuery(_ context.Context, cmd flightsql.PreparedStatementQuery, rdr flight.MessageReader, _ flight.MetadataWriter) ([]byte, error) {
switch string(cmd.GetPreparedStatementHandle()) {
case "SELECT PREPARED STATEMENT HANDLE",
"SELECT PREPARED STATEMENT WITH TXN HANDLE",
"PLAN HANDLE", "PLAN WITH TXN HANDLE":
actualSchema := rdr.Schema()
return cmd.GetPreparedStatementHandle(), assertEq(true, actualSchema.Equal(getQuerySchema()))
}
return cmd.GetPreparedStatementHandle(), fmt.Errorf("%w: handle for DoPutPreparedStatementQuery '%s'",
arrow.ErrInvalid, string(cmd.GetPreparedStatementHandle()))
}
func (m *flightSqlScenarioTester) DoPutPreparedStatementUpdate(_ context.Context, cmd flightsql.PreparedStatementUpdate, _ flight.MessageReader) (int64, error) {
switch string(cmd.GetPreparedStatementHandle()) {
case "UPDATE PREPARED STATEMENT HANDLE", "PLAN HANDLE":
return updatePreparedStatementExpectedRows, nil
case "UPDATE PREPARED STATEMENT WITH TXN HANDLE", "PLAN WITH TXN HANDLE":
return updatePreparedStatementWithTransactionExpectedRows, nil
}
return 0, fmt.Errorf("%w: handle for DoPutPreparedStatementUpdate '%s'",
arrow.ErrInvalid, string(cmd.GetPreparedStatementHandle()))
}
func (m *flightSqlScenarioTester) BeginSavepoint(_ context.Context, request flightsql.ActionBeginSavepointRequest) ([]byte, error) {
if err := assertEq(savepointName, request.GetName()); err != nil {
return nil, fmt.Errorf("%w: unexpected savepoint name in BeginSavepoint", err)
}
if err := assertEq([]byte(transactionID), request.GetTransactionId()); err != nil {
return nil, fmt.Errorf("%w: unexpected transaction ID in BeginSavepoint", err)
}
return []byte(savepointID), nil
}
func (m *flightSqlScenarioTester) BeginTransaction(context.Context, flightsql.ActionBeginTransactionRequest) ([]byte, error) {
return []byte(transactionID), nil
}
func (m *flightSqlScenarioTester) CancelFlightInfo(_ context.Context, request *flight.CancelFlightInfoRequest) (flight.CancelFlightInfoResult, error) {
result := flight.CancelFlightInfoResult{Status: flight.CancelStatusUnspecified}
if err := assertEq(1, len(request.Info.Endpoint)); err != nil {
return result, fmt.Errorf("%w: expected 1 endpoint for CancelQuery", err)
}
endpoint := request.Info.Endpoint[0]
tkt, err := flightsql.GetStatementQueryTicket(endpoint.Ticket)
if err != nil {
return result, err
}
if err := assertEq([]byte("PLAN HANDLE"), tkt.GetStatementHandle()); err != nil {
return result, fmt.Errorf("%w: unexpected ticket in CancelQuery", err)
}
result.Status = flight.CancelStatusCancelled
return result, nil
}
func (m *flightSqlScenarioTester) EndSavepoint(_ context.Context, request flightsql.ActionEndSavepointRequest) error {
switch request.GetAction() {
case flightsql.EndSavepointRelease, flightsql.EndSavepointRollback:
if err := assertEq([]byte(savepointID), request.GetSavepointId()); err != nil {
return fmt.Errorf("%w: unexpected savepoint ID in EndSavepoint", err)
}
return nil
}
return fmt.Errorf("%w: unknown action %v", arrow.ErrInvalid, request.GetAction())
}
func (m *flightSqlScenarioTester) EndTransaction(_ context.Context, request flightsql.ActionEndTransactionRequest) error {
switch request.GetAction() {
case flightsql.EndTransactionCommit, flightsql.EndTransactionRollback:
if err := assertEq([]byte(transactionID), request.GetTransactionId()); err != nil {
return fmt.Errorf("%w: unexpected transaction ID in EndTransaction", err)
}
return nil
}
return fmt.Errorf("%w: unknown action %v", arrow.ErrInvalid, request.GetAction())
}
// schema to be returned for mocking the statement/prepared statement results
func getQuerySchema() *arrow.Schema {
return arrow.NewSchema([]arrow.Field{
{Name: "id", Type: arrow.PrimitiveTypes.Int64, Nullable: true,
Metadata: *flightsql.NewColumnMetadataBuilder().
TableName("test").
IsAutoIncrement(true).
IsCaseSensitive(false).
TypeName("type_test").
SchemaName("schema_test").
IsSearchable(true).
CatalogName("catalog_test").
Precision(100).
Build().Data}}, nil)
}
func getQueryWithTransactionSchema() *arrow.Schema {
return arrow.NewSchema([]arrow.Field{
{Name: "pkey", Type: arrow.PrimitiveTypes.Int32, Nullable: true,
Metadata: *flightsql.NewColumnMetadataBuilder().
TableName("test").
IsAutoIncrement(true).
IsCaseSensitive(false).
TypeName("type_test").
SchemaName("schema_test").
IsSearchable(true).
CatalogName("catalog_test").
Precision(100).Build().Data}}, nil)
}
const (
substraitPlanText = "plan"
substraitPlanVersion = "version"
selectStatement = "SELECT STATEMENT"
savepointID = "savepoint_id"
savepointName = "savepoint_name"
transactionID = "transaction_id"
)
var substraitPlan = flightsql.SubstraitPlan{
Plan: []byte(substraitPlanText), Version: substraitPlanVersion}
type flightSqlExtensionScenarioTester struct {
flightSqlScenarioTester
}
func (m *flightSqlExtensionScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flightsql.NewClient(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
if err := m.ValidateMetadataRetrieval(client); err != nil {
return err
}
if err := m.ValidateStatementExecution(client); err != nil {
return err
}
if err := m.ValidatePreparedStatementExecution(client); err != nil {
return err
}
return m.ValidateTransactions(client)
}
func (m *flightSqlExtensionScenarioTester) ValidateMetadataRetrieval(client *flightsql.Client) error {
sqlInfo := []flightsql.SqlInfo{
flightsql.SqlInfoFlightSqlServerSql,
flightsql.SqlInfoFlightSqlServerSubstrait,
flightsql.SqlInfoFlightSqlServerSubstraitMinVersion,
flightsql.SqlInfoFlightSqlServerSubstraitMaxVersion,
flightsql.SqlInfoFlightSqlServerTransaction,
flightsql.SqlInfoFlightSqlServerCancel,
flightsql.SqlInfoFlightSqlServerStatementTimeout,
flightsql.SqlInfoFlightSqlServerTransactionTimeout,
}
ctx := context.Background()
info, err := client.GetSqlInfo(ctx, sqlInfo)
if err != nil {
return err
}
rdr, err := client.DoGet(ctx, info.Endpoint[0].Ticket)
if err != nil {
return err
}
defer rdr.Release()
actualSchema := rdr.Schema()
if !schema_ref.SqlInfo.Equal(actualSchema) {
return fmt.Errorf("%w: schemas did not match. expected: %s\n got: %s",
arrow.ErrInvalid, schema_ref.SqlInfo, actualSchema)
}
infoValues := make(flightsql.SqlInfoResultMap)
for rdr.Next() {
rec := rdr.Record()
names, values := rec.Column(0).(*array.Uint32), rec.Column(1).(*array.DenseUnion)
for i := 0; i < int(rec.NumRows()); i++ {
code := names.Value(i)
if _, ok := infoValues[code]; ok {
return fmt.Errorf("%w: duplicate SqlInfo value %d", arrow.ErrInvalid, code)
}
switch values.TypeCode(i) {
case 0: // string
infoValues[code] = values.Field(0).(*array.String).
Value(int(values.ValueOffset(i)))
case 1: // bool
infoValues[code] = values.Field(1).(*array.Boolean).
Value(int(values.ValueOffset(i)))
case 2: // int64
infoValues[code] = values.Field(2).(*array.Int64).
Value(int(values.ValueOffset(i)))
case 3: // int32
infoValues[code] = values.Field(3).(*array.Int32).
Value(int(values.ValueOffset(i)))
default:
return fmt.Errorf("%w: decoding SqlInfoResult of type code %d",
arrow.ErrNotImplemented, values.TypeCode(i))
}
}
}
if rdr.Err() != nil {
return rdr.Err()
}
for k, v := range infoValues {
switch k {
case uint32(flightsql.SqlInfoFlightSqlServerSql):
if err := assertEq(false, v); err != nil {
return fmt.Errorf("%w: %v did not match", err, k)
}
case uint32(flightsql.SqlInfoFlightSqlServerSubstrait):
if err := assertEq(true, v); err != nil {
return fmt.Errorf("%w: %v did not match", err, k)
}
case uint32(flightsql.SqlInfoFlightSqlServerSubstraitMinVersion):
if err := assertEq("min_version", v); err != nil {
return fmt.Errorf("%w: %v did not match", err, k)
}
case uint32(flightsql.SqlInfoFlightSqlServerSubstraitMaxVersion):
if err := assertEq("max_version", v); err != nil {
return fmt.Errorf("%w: %v did not match", err, k)
}
case uint32(flightsql.SqlInfoFlightSqlServerTransaction):
if err := assertEq(int32(flightsql.SqlTransactionSavepoint), v); err != nil {
return fmt.Errorf("%w: %v did not match", err, k)
}
case uint32(flightsql.SqlInfoFlightSqlServerCancel):
if err := assertEq(true, v); err != nil {
return fmt.Errorf("%w: %v did not match", err, k)
}
case uint32(flightsql.SqlInfoFlightSqlServerStatementTimeout):
if err := assertEq(int32(42), v); err != nil {
return fmt.Errorf("%w: %v did not match", err, k)
}
case uint32(flightsql.SqlInfoFlightSqlServerTransactionTimeout):
if err := assertEq(int32(7), v); err != nil {
return fmt.Errorf("%w: %v did not match", err, k)
}
}
}
return nil
}
func (m *flightSqlExtensionScenarioTester) ValidateStatementExecution(client *flightsql.Client) error {
ctx := context.Background()
info, err := client.ExecuteSubstrait(ctx, substraitPlan)
if err != nil {
return err
}
if err := m.validate(getQuerySchema(), info, client); err != nil {
return err
}
schema, err := client.GetExecuteSubstraitSchema(ctx, substraitPlan)
if err != nil {
return err
}
if err := m.validateSchema(getQuerySchema(), schema); err != nil {
return err
}
info, err = client.ExecuteSubstrait(ctx, substraitPlan)
if err != nil {
return err
}
//nolint:staticcheck,SA1019 for backward compatibility
cancelResult, err := client.CancelQuery(ctx, info)
if err != nil {
return err
}
if err := assertEq(flightsql.CancelResultCancelled, cancelResult); err != nil {
return fmt.Errorf("%w: wrong cancel result", err)
}
updatedRows, err := client.ExecuteSubstraitUpdate(ctx, substraitPlan)
if err != nil {
return err
}
if err := assertEq(updateStatementExpectedRows, updatedRows); err != nil {
return fmt.Errorf("%w: wrong number of updated rows for ExecuteSubstraitUpdate", err)
}
return nil
}
func (m *flightSqlExtensionScenarioTester) ValidatePreparedStatementExecution(client *flightsql.Client) error {
arr, _, _ := array.FromJSON(memory.DefaultAllocator, arrow.PrimitiveTypes.Int64, strings.NewReader("[1]"))
defer arr.Release()
params := array.NewRecord(getQuerySchema(), []arrow.Array{arr}, 1)
defer params.Release()
ctx := context.Background()
stmt, err := client.PrepareSubstrait(ctx, substraitPlan)
if err != nil {
return err
}
stmt.SetParameters(params)
info, err := stmt.Execute(ctx)
if err != nil {
return err
}
if err := m.validate(getQuerySchema(), info, client); err != nil {
return err
}
schema, err := stmt.GetSchema(ctx)
if err != nil {
return err
}
if err := m.validateSchema(getQuerySchema(), schema); err != nil {
return err
}
if err := stmt.Close(ctx); err != nil {
return err
}
updateStmt, err := client.PrepareSubstrait(ctx, substraitPlan)
if err != nil {
return err
}
updatedRows, err := updateStmt.ExecuteUpdate(ctx)
if err != nil {
return err
}
if err := assertEq(updatePreparedStatementExpectedRows, updatedRows); err != nil {
return err
}
return updateStmt.Close(ctx)
}
func (m *flightSqlExtensionScenarioTester) ValidateTransactions(client *flightsql.Client) error {
ctx := context.Background()
txn, err := client.BeginTransaction(ctx)
if err != nil {
return err
}
if err := assertEq([]byte(transactionID), []byte(txn.ID())); err != nil {
return err
}
sp, err := txn.BeginSavepoint(ctx, savepointName)
if err != nil {
return err
}
if err := assertEq([]byte(savepointID), []byte(sp)); err != nil {
return err
}
info, err := txn.Execute(ctx, selectStatement)
if err != nil {
return err
}
if err := m.validate(getQueryWithTransactionSchema(), info, client); err != nil {
return err
}
info, err = txn.ExecuteSubstrait(ctx, substraitPlan)
if err != nil {
return err
}
if err := m.validate(getQueryWithTransactionSchema(), info, client); err != nil {
return err
}
schema, err := txn.GetExecuteSchema(ctx, selectStatement)
if err != nil {
return err
}
if err := m.validateSchema(getQueryWithTransactionSchema(), schema); err != nil {
return err
}
schema, err = txn.GetExecuteSubstraitSchema(ctx, substraitPlan)
if err != nil {
return err
}
if err := m.validateSchema(getQueryWithTransactionSchema(), schema); err != nil {
return err
}
updated, err := txn.ExecuteUpdate(ctx, "UPDATE STATEMENT")
if err != nil {
return err
}
if err := assertEq(updateStatementWithTransactionExpectedRows, updated); err != nil {
return err
}
updated, err = txn.ExecuteSubstraitUpdate(ctx, substraitPlan)
if err != nil {
return err
}
if err := assertEq(updateStatementWithTransactionExpectedRows, updated); err != nil {
return err
}
arr, _, _ := array.FromJSON(memory.DefaultAllocator, arrow.PrimitiveTypes.Int64, strings.NewReader("[1]"))
defer arr.Release()
params := array.NewRecord(getQuerySchema(), []arrow.Array{arr}, 1)
defer params.Release()
prepared, err := txn.Prepare(ctx, "SELECT PREPARED STATEMENT")
if err != nil {
return err
}
prepared.SetParameters(params)
info, err = prepared.Execute(ctx)
if err != nil {
return err
}
if err := m.validate(getQueryWithTransactionSchema(), info, client); err != nil {
return err
}
schema, err = prepared.GetSchema(ctx)
if err != nil {
return err
}
if err := m.validateSchema(getQueryWithTransactionSchema(), schema); err != nil {
return err
}
if err := prepared.Close(ctx); err != nil {
return err
}
prepared, err = txn.PrepareSubstrait(ctx, substraitPlan)
if err != nil {
return err
}
prepared.SetParameters(params)
info, err = prepared.Execute(ctx)
if err != nil {
return err
}
if err := m.validate(getQueryWithTransactionSchema(), info, client); err != nil {
return err
}
schema, err = prepared.GetSchema(ctx)
if err != nil {
return err
}
if err := m.validateSchema(getQueryWithTransactionSchema(), schema); err != nil {
return err
}
if err := prepared.Close(ctx); err != nil {
return err
}
prepared, err = txn.Prepare(ctx, "UPDATE PREPARED STATEMENT")
if err != nil {
return err
}
updated, err = prepared.ExecuteUpdate(ctx)
if err != nil {
return err
}
if err := assertEq(updatePreparedStatementWithTransactionExpectedRows, updated); err != nil {
return err
}
if err := prepared.Close(ctx); err != nil {
return err
}
prepared, err = txn.PrepareSubstrait(ctx, substraitPlan)
if err != nil {
return err
}
updated, err = prepared.ExecuteUpdate(ctx)
if err != nil {
return err
}
if err := assertEq(updatePreparedStatementWithTransactionExpectedRows, updated); err != nil {
return err
}
if err := prepared.Close(ctx); err != nil {
return err
}
if err := txn.RollbackSavepoint(ctx, sp); err != nil {
return err
}
sp2, err := txn.BeginSavepoint(ctx, savepointName)
if err != nil {
return err
}
if err := assertEq([]byte(savepointID), []byte(sp2)); err != nil {
return err
}
if err := txn.ReleaseSavepoint(ctx, sp); err != nil {
return err
}
if err := txn.Commit(ctx); err != nil {
return err
}
txn, err = client.BeginTransaction(ctx)
if err != nil {
return err
}
if err := assertEq([]byte(transactionID), []byte(txn.ID())); err != nil {
return err
}
return txn.Rollback(ctx)
}
type sessionOptionsScenarioTester struct {
flightsql.BaseServer
}
func (tester *sessionOptionsScenarioTester) MakeServer(port int) flight.Server {
srv := flight.NewServerWithMiddleware([]flight.ServerMiddleware{
flight.CreateServerMiddleware(session.NewServerSessionMiddleware(nil)),
})
srv.RegisterFlightService(flightsql.NewFlightServer(tester))
initServer(port, srv)
return srv
}
func (tester *sessionOptionsScenarioTester) SetSessionOptions(ctx context.Context, req *flight.SetSessionOptionsRequest) (*flight.SetSessionOptionsResult, error) {
session, err := session.GetSessionFromContext(ctx)
if err != nil {
return nil, err
}
errors := make(map[string]*flight.SetSessionOptionsResultError)
for key, val := range req.GetSessionOptions() {
if key == "lol_invalid" {
errors[key] = &flight.SetSessionOptionsResultError{Value: flight.SetSessionOptionsResultErrorInvalidName}
continue
}
if val.GetStringValue() == "lol_invalid" {
errors[key] = &flight.SetSessionOptionsResultError{Value: flight.SetSessionOptionsResultErrorInvalidValue}
continue
}
session.SetSessionOption(key, val)
}
return &flight.SetSessionOptionsResult{Errors: errors}, nil
}
func (tester *sessionOptionsScenarioTester) GetSessionOptions(ctx context.Context, req *flight.GetSessionOptionsRequest) (*flight.GetSessionOptionsResult, error) {
session, err := session.GetSessionFromContext(ctx)
if err != nil {
return nil, err
}
return &flight.GetSessionOptionsResult{SessionOptions: session.GetSessionOptions()}, nil
}
func (tester *sessionOptionsScenarioTester) CloseSession(ctx context.Context, req *flight.CloseSessionRequest) (*flight.CloseSessionResult, error) {
session, err := session.GetSessionFromContext(ctx)
if err != nil {
return nil, err
}
if err = session.Close(); err != nil {
return nil, err
}
return &flight.CloseSessionResult{Status: flight.CloseSessionResultClosed}, nil
}
func (tester *sessionOptionsScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
middleware := []flight.ClientMiddleware{
flight.NewClientCookieMiddleware(),
}
client, err := flight.NewClientWithMiddleware(addr, nil, middleware, opts...)
if err != nil {
return err
}
defer client.Close()
// Run validations in order. We are changing session state in each step, so order is made explicit.
ctx := context.Background()
if err = tester.ValidateFirstGetSessionOptions(ctx, client); err != nil {
return err
}
if err = tester.ValidateSecondSetSessionOptions(ctx, client); err != nil {
return err
}
if err = tester.ValidateThirdGetSessionOptions(ctx, client); err != nil {
return err
}
if err = tester.ValidateFourthRemoveOption(ctx, client); err != nil {
return err
}
if err = tester.ValidateFifthGetSessionOptions(ctx, client); err != nil {
return err
}
if err = tester.ValidateSixthCloseSession(ctx, client); err != nil {
return err
}
// C++ impl currently fails with "Invalid or expired arrow_flight_session_id cookie", likely related to GH-39791
// if err = tester.ValidateSeventhGetSessionOptions(ctx, client); err != nil {
// return err
// }
return nil
}
func (tester *sessionOptionsScenarioTester) ValidateFirstGetSessionOptions(ctx context.Context, client flight.Client) error {
res, err := client.GetSessionOptions(ctx, &flight.GetSessionOptionsRequest{})
if err != nil {
return err
}
opts := res.GetSessionOptions()
if len(opts) != 0 {
return fmt.Errorf("expected new session to be empty, but found %d options already set", len(opts))
}
return nil
}
func (tester *sessionOptionsScenarioTester) ValidateSecondSetSessionOptions(ctx context.Context, client flight.Client) error {
opts, err := flight.NewSessionOptionValues(map[string]any{
"foolong": int64(123),
"bardouble": 456.0,
"lol_invalid": "this won't get set",
"key_with_invalid_value": "lol_invalid",
"big_ol_string_list": []string{"a", "b", "sea", "dee", " ", " ", "geee", "(づ。◕‿‿◕。)づ"},
})
if err != nil {
return err
}
res, err := client.SetSessionOptions(ctx, &flight.SetSessionOptionsRequest{SessionOptions: opts})
if err != nil {
return err
}
expectedErrs := map[string]*flight.SetSessionOptionsResultError{
"lol_invalid": {Value: flight.SetSessionOptionsResultErrorInvalidName},
"key_with_invalid_value": {Value: flight.SetSessionOptionsResultErrorInvalidValue},
}
errs := res.GetErrors()
if len(errs) != len(expectedErrs) {
return fmt.Errorf("errors expected: %d, got: %d", len(expectedErrs), len(errs))
}
for key, val := range errs {
if !reflect.DeepEqual(val, expectedErrs[key]) {
return fmt.Errorf("error mismatch for key %s. expected: %s, got: %s", key, expectedErrs[key], val)
}
}
return nil
}
func (tester *sessionOptionsScenarioTester) ValidateThirdGetSessionOptions(ctx context.Context, client flight.Client) error {
res, err := client.GetSessionOptions(ctx, &flight.GetSessionOptionsRequest{})
if err != nil {
return err
}
expectedOpts, err := flight.NewSessionOptionValues(map[string]any{
"foolong": int64(123),
"bardouble": 456.0,
"big_ol_string_list": []string{"a", "b", "sea", "dee", " ", " ", "geee", "(づ。◕‿‿◕。)づ"},
})
if err != nil {
return err
}
opts := res.GetSessionOptions()
if len(opts) != len(expectedOpts) {
return fmt.Errorf("options expected: %d, got: %d", len(expectedOpts), len(opts))
}
for key, val := range opts {
if !reflect.DeepEqual(val, expectedOpts[key]) {
return fmt.Errorf("session options mismatch for key %s. expected: %s, got: %s", key, expectedOpts[key], val)
}
}
return nil
}
func (tester *sessionOptionsScenarioTester) ValidateFourthRemoveOption(ctx context.Context, client flight.Client) error {
opts, err := flight.NewSessionOptionValues(map[string]any{
"foolong": nil,
})
if err != nil {
return err
}
res, err := client.SetSessionOptions(ctx, &flight.SetSessionOptionsRequest{SessionOptions: opts})
if err != nil {
return err
}
errs := res.GetErrors()
if len(errs) != 0 {
return fmt.Errorf("errors expected: %d, got: %d", 0, len(errs))
}
return nil
}
func (tester *sessionOptionsScenarioTester) ValidateFifthGetSessionOptions(ctx context.Context, client flight.Client) error {
res, err := client.GetSessionOptions(ctx, &flight.GetSessionOptionsRequest{})
if err != nil {
return err
}
expectedOpts, err := flight.NewSessionOptionValues(map[string]any{
"bardouble": 456.0,
"big_ol_string_list": []string{"a", "b", "sea", "dee", " ", " ", "geee", "(づ。◕‿‿◕。)づ"},
})
if err != nil {
return err
}
opts := res.GetSessionOptions()
if len(opts) != len(expectedOpts) {
return fmt.Errorf("options expected: %d, got: %d", len(expectedOpts), len(opts))
}
for key, val := range opts {
if !reflect.DeepEqual(val, expectedOpts[key]) {
return fmt.Errorf("session options mismatch for key %s. expected: %s, got: %s", key, expectedOpts[key], val)
}
}
return nil
}
func (tester *sessionOptionsScenarioTester) ValidateSixthCloseSession(ctx context.Context, client flight.Client) error {
res, err := client.CloseSession(ctx, &flight.CloseSessionRequest{})
if err != nil {
return err
}
if res.GetStatus() != flight.CloseSessionResultClosed {
return fmt.Errorf("expected session to successfully close, but found status: %s", res.GetStatus())
}
return nil
}
func (tester *sessionOptionsScenarioTester) ValidateSeventhGetSessionOptions(ctx context.Context, client flight.Client) error {
res, err := client.GetSessionOptions(ctx, &flight.GetSessionOptionsRequest{})
if err != nil {
return err
}
opts := res.GetSessionOptions()
if len(opts) != 0 {
return fmt.Errorf("expected new session to be empty, but found %d options already set", len(opts))
}
return nil
}
type flightSqlIngestionScenarioTester struct {
flightsql.BaseServer
}
func (m *flightSqlIngestionScenarioTester) MakeServer(port int) flight.Server {
srv := flight.NewServerWithMiddleware(nil)
m.RegisterSqlInfo(flightsql.SqlInfoFlightSqlServerBulkIngestion, true)
m.RegisterSqlInfo(flightsql.SqlInfoFlightSqlServerIngestTransactionsSupported, true)
srv.RegisterFlightService(flightsql.NewFlightServer(m))
initServer(port, srv)
return srv
}
func (m *flightSqlIngestionScenarioTester) RunClient(addr string, opts ...grpc.DialOption) error {
client, err := flightsql.NewClient(addr, nil, nil, opts...)
if err != nil {
return err
}
defer client.Close()
return m.ValidateIngestion(client)
}
func (m *flightSqlIngestionScenarioTester) ValidateIngestion(client *flightsql.Client) error {
ctx := context.Background()
opts := getIngestOptions()
ingestResult, err := client.ExecuteIngest(ctx, getIngestRecords(), opts)
if err != nil {
return err
}
if ingestResult != ingestStatementExpectedRows {
return fmt.Errorf("expected ingest return %d got %d", ingestStatementExpectedRows, ingestResult)
}
return nil
}
func (m *flightSqlIngestionScenarioTester) DoPutCommandStatementIngest(ctx context.Context, cmd flightsql.StatementIngest, rdr flight.MessageReader) (int64, error) {
expectedSchema := getIngestSchema()
expectedOpts := getIngestOptions()
if err := assertEq(expectedOpts.TableDefinitionOptions.IfExists, cmd.GetTableDefinitionOptions().IfExists); err != nil {
return 0, err
}
if err := assertEq(expectedOpts.TableDefinitionOptions.IfNotExist, cmd.GetTableDefinitionOptions().IfNotExist); err != nil {
return 0, err
}
if err := assertEq(expectedOpts.Table, cmd.GetTable()); err != nil {
return 0, err
}
if err := assertEq(*expectedOpts.Schema, cmd.GetSchema()); err != nil {
return 0, err
}
if err := assertEq(*expectedOpts.Catalog, cmd.GetCatalog()); err != nil {
return 0, err
}
if err := assertEq(expectedOpts.Temporary, cmd.GetTemporary()); err != nil {
return 0, err
}
if err := assertEq(expectedOpts.TransactionId, cmd.GetTransactionId()); err != nil {
return 0, err
}
if err := assertEq(expectedOpts.Options, cmd.GetOptions()); err != nil {
return 0, err
}
var nRecords int64
for rdr.Next() {
rec := rdr.Record()
nRecords += rec.NumRows()
if err := assertEq(true, expectedSchema.Equal(rec.Schema())); err != nil {
return 0, err
}
}
return nRecords, nil
}
// Options to assert before/after mocked ingest call
func getIngestOptions() *flightsql.ExecuteIngestOpts {
tableDefinitionOptions := flightsql.TableDefinitionOptions{
IfNotExist: flightsql.TableDefinitionOptionsTableNotExistOptionCreate,
IfExists: flightsql.TableDefinitionOptionsTableExistsOptionReplace,
}
table := "test_table"
schema := "test_schema"
catalog := "test_catalog"
temporary := true
transactionId := []byte("123")
options := map[string]string{
"key1": "val1",
"key2": "val2",
}
return &flightsql.ExecuteIngestOpts{
TableDefinitionOptions: &tableDefinitionOptions,
Table: table,
Schema: &schema,
Catalog: &catalog,
Temporary: temporary,
TransactionId: transactionId,
Options: options,
}
}
// Schema for ingest records; asserted on records received by handler
func getIngestSchema() *arrow.Schema {
return arrow.NewSchema([]arrow.Field{{Name: "test_field", Type: arrow.PrimitiveTypes.Int64, Nullable: true}}, nil)
}
// Prepare records for ingestion with known length and schema
func getIngestRecords() array.RecordReader {
schema := getIngestSchema()
arr := array.MakeArrayOfNull(memory.DefaultAllocator, arrow.PrimitiveTypes.Int64, int(ingestStatementExpectedRows))
defer arr.Release()
rec := array.NewRecord(schema, []arrow.Array{arr}, ingestStatementExpectedRows)
defer rec.Release()
rdr, _ := array.NewRecordReader(schema, []arrow.Record{rec})
return rdr
}
|