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
|
// +build all integration
package gocql
import (
"bytes"
"context"
"io"
"math"
"math/big"
"net"
"reflect"
"strconv"
"strings"
"sync"
"testing"
"time"
"unicode"
"gopkg.in/inf.v0"
)
// TestAuthentication verifies that gocql will work with a host configured to only accept authenticated connections
func TestAuthentication(t *testing.T) {
if *flagProto < 2 {
t.Skip("Authentication is not supported with protocol < 2")
}
if !*flagRunAuthTest {
t.Skip("Authentication is not configured in the target cluster")
}
cluster := createCluster()
cluster.Authenticator = PasswordAuthenticator{
Username: "cassandra",
Password: "cassandra",
}
session, err := cluster.CreateSession()
if err != nil {
t.Fatalf("Authentication error: %s", err)
}
session.Close()
}
//TestRingDiscovery makes sure that you can autodiscover other cluster members when you seed a cluster config with just one node
func TestRingDiscovery(t *testing.T) {
cluster := createCluster()
cluster.Hosts = clusterHosts[:1]
session := createSessionFromCluster(cluster, t)
defer session.Close()
if *clusterSize > 1 {
// wait for autodiscovery to update the pool with the list of known hosts
time.Sleep(*flagAutoWait)
}
session.pool.mu.RLock()
defer session.pool.mu.RUnlock()
size := len(session.pool.hostConnPools)
if *clusterSize != size {
for p, pool := range session.pool.hostConnPools {
t.Logf("p=%q host=%v ips=%s", p, pool.host, pool.host.ConnectAddress().String())
}
t.Errorf("Expected a cluster size of %d, but actual size was %d", *clusterSize, size)
}
}
func TestEmptyHosts(t *testing.T) {
cluster := createCluster()
cluster.Hosts = nil
if session, err := cluster.CreateSession(); err == nil {
session.Close()
t.Error("expected err, got nil")
}
}
func TestInvalidPeerEntry(t *testing.T) {
session := createSession(t)
// rack, release_version, schema_version, tokens are all null
query := session.Query("INSERT into system.peers (peer, data_center, host_id, rpc_address) VALUES (?, ?, ?, ?)",
"169.254.235.45",
"datacenter1",
"35c0ec48-5109-40fd-9281-9e9d4add2f1e",
"169.254.235.45",
)
if err := query.Exec(); err != nil {
t.Fatal(err)
}
session.Close()
cluster := createCluster()
cluster.PoolConfig.HostSelectionPolicy = TokenAwareHostPolicy(RoundRobinHostPolicy())
session = createSessionFromCluster(cluster, t)
defer func() {
session.Query("DELETE from system.peers where peer = ?", "169.254.235.45").Exec()
session.Close()
}()
// check we can perform a query
iter := session.Query("select peer from system.peers").Iter()
var peer string
for iter.Scan(&peer) {
}
if err := iter.Close(); err != nil {
t.Fatal(err)
}
}
//TestUseStatementError checks to make sure the correct error is returned when the user tries to execute a use statement.
func TestUseStatementError(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := session.Query("USE gocql_test").Exec(); err != nil {
if err != ErrUseStmt {
t.Fatalf("expected ErrUseStmt, got " + err.Error())
}
} else {
t.Fatal("expected err, got nil.")
}
}
//TestInvalidKeyspace checks that an invalid keyspace will return promptly and without a flood of connections
func TestInvalidKeyspace(t *testing.T) {
cluster := createCluster()
cluster.Keyspace = "invalidKeyspace"
session, err := cluster.CreateSession()
if err != nil {
if err != ErrNoConnectionsStarted {
t.Fatalf("Expected ErrNoConnections but got %v", err)
}
} else {
session.Close() //Clean up the session
t.Fatal("expected err, got nil.")
}
}
func TestTracing(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.trace (id int primary key)`); err != nil {
t.Fatal("create:", err)
}
buf := &bytes.Buffer{}
trace := NewTraceWriter(session, buf)
if err := session.Query(`INSERT INTO trace (id) VALUES (?)`, 42).Trace(trace).Exec(); err != nil {
t.Fatal("insert:", err)
} else if buf.Len() == 0 {
t.Fatal("insert: failed to obtain any tracing")
}
buf.Reset()
var value int
if err := session.Query(`SELECT id FROM trace WHERE id = ?`, 42).Trace(trace).Scan(&value); err != nil {
t.Fatal("select:", err)
} else if value != 42 {
t.Fatalf("value: expected %d, got %d", 42, value)
} else if buf.Len() == 0 {
t.Fatal("select: failed to obtain any tracing")
}
// also works from session tracer
session.SetTrace(trace)
buf.Reset()
if err := session.Query(`SELECT id FROM trace WHERE id = ?`, 42).Scan(&value); err != nil {
t.Fatal("select:", err)
}
if buf.Len() == 0 {
t.Fatal("select: failed to obtain any tracing")
}
}
func TestPaging(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("Paging not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, "CREATE TABLE gocql_test.paging (id int primary key)"); err != nil {
t.Fatal("create table:", err)
}
for i := 0; i < 100; i++ {
if err := session.Query("INSERT INTO paging (id) VALUES (?)", i).Exec(); err != nil {
t.Fatal("insert:", err)
}
}
iter := session.Query("SELECT id FROM paging").PageSize(10).Iter()
var id int
count := 0
for iter.Scan(&id) {
count++
}
if err := iter.Close(); err != nil {
t.Fatal("close:", err)
}
if count != 100 {
t.Fatalf("expected %d, got %d", 100, count)
}
}
func TestCAS(t *testing.T) {
cluster := createCluster()
cluster.SerialConsistency = LocalSerial
session := createSessionFromCluster(cluster, t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.cas_table (
title varchar,
revid timeuuid,
last_modified timestamp,
PRIMARY KEY (title, revid)
)`); err != nil {
t.Fatal("create:", err)
}
title, revid, modified := "baz", TimeUUID(), time.Now()
var titleCAS string
var revidCAS UUID
var modifiedCAS time.Time
if applied, err := session.Query(`INSERT INTO cas_table (title, revid, last_modified)
VALUES (?, ?, ?) IF NOT EXISTS`,
title, revid, modified).ScanCAS(&titleCAS, &revidCAS, &modifiedCAS); err != nil {
t.Fatal("insert:", err)
} else if !applied {
t.Fatal("insert should have been applied")
}
if applied, err := session.Query(`INSERT INTO cas_table (title, revid, last_modified)
VALUES (?, ?, ?) IF NOT EXISTS`,
title, revid, modified).ScanCAS(&titleCAS, &revidCAS, &modifiedCAS); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatal("insert should not have been applied")
} else if title != titleCAS || revid != revidCAS {
t.Fatalf("expected %s/%v/%v but got %s/%v/%v", title, revid, modified, titleCAS, revidCAS, modifiedCAS)
}
tenSecondsLater := modified.Add(10 * time.Second)
if applied, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
title, revid, tenSecondsLater).ScanCAS(&modifiedCAS); err != nil {
t.Fatal("delete:", err)
} else if applied {
t.Fatal("delete should have not been applied")
}
if modifiedCAS.Unix() != tenSecondsLater.Add(-10*time.Second).Unix() {
t.Fatalf("Was expecting modified CAS to be %v; but was one second later", modifiedCAS.UTC())
}
if _, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
title, revid, tenSecondsLater).ScanCAS(); !strings.HasPrefix(err.Error(), "gocql: not enough columns to scan into") {
t.Fatalf("delete: was expecting count mismatch error but got: %q", err.Error())
}
if applied, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`,
title, revid, modified).ScanCAS(&modifiedCAS); err != nil {
t.Fatal("delete:", err)
} else if !applied {
t.Fatal("delete should have been applied")
}
if err := session.Query(`TRUNCATE cas_table`).Exec(); err != nil {
t.Fatal("truncate:", err)
}
successBatch := session.NewBatch(LoggedBatch)
successBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES (?, ?, ?) IF NOT EXISTS", title, revid, modified)
if applied, _, err := session.ExecuteBatchCAS(successBatch, &titleCAS, &revidCAS, &modifiedCAS); err != nil {
t.Fatal("insert:", err)
} else if !applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
}
successBatch = session.NewBatch(LoggedBatch)
successBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES (?, ?, ?) IF NOT EXISTS", title+"_foo", revid, modified)
casMap := make(map[string]interface{})
if applied, _, err := session.MapExecuteBatchCAS(successBatch, casMap); err != nil {
t.Fatal("insert:", err)
} else if !applied {
t.Fatal("insert should have been applied")
}
failBatch := session.NewBatch(LoggedBatch)
failBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES (?, ?, ?) IF NOT EXISTS", title, revid, modified)
if applied, _, err := session.ExecuteBatchCAS(successBatch, &titleCAS, &revidCAS, &modifiedCAS); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
}
insertBatch := session.NewBatch(LoggedBatch)
insertBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES ('_foo', 2c3af400-73a4-11e5-9381-29463d90c3f0, DATEOF(NOW()))")
insertBatch.Query("INSERT INTO cas_table (title, revid, last_modified) VALUES ('_foo', 3e4ad2f1-73a4-11e5-9381-29463d90c3f0, DATEOF(NOW()))")
if err := session.ExecuteBatch(insertBatch); err != nil {
t.Fatal("insert:", err)
}
failBatch = session.NewBatch(LoggedBatch)
failBatch.Query("UPDATE cas_table SET last_modified = DATEOF(NOW()) WHERE title='_foo' AND revid=2c3af400-73a4-11e5-9381-29463d90c3f0 IF last_modified=DATEOF(NOW());")
failBatch.Query("UPDATE cas_table SET last_modified = DATEOF(NOW()) WHERE title='_foo' AND revid=3e4ad2f1-73a4-11e5-9381-29463d90c3f0 IF last_modified=DATEOF(NOW());")
if applied, iter, err := session.ExecuteBatchCAS(failBatch, &titleCAS, &revidCAS, &modifiedCAS); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
} else {
if scan := iter.Scan(&applied, &titleCAS, &revidCAS, &modifiedCAS); scan && applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", titleCAS, revidCAS, modifiedCAS)
} else if !scan {
t.Fatal("should have scanned another row")
}
if err := iter.Close(); err != nil {
t.Fatal("scan:", err)
}
}
}
func TestMapScanCAS(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.cas_table2 (
title varchar,
revid timeuuid,
last_modified timestamp,
deleted boolean,
PRIMARY KEY (title, revid)
)`); err != nil {
t.Fatal("create:", err)
}
title, revid, modified, deleted := "baz", TimeUUID(), time.Now(), false
mapCAS := map[string]interface{}{}
if applied, err := session.Query(`INSERT INTO cas_table2 (title, revid, last_modified, deleted)
VALUES (?, ?, ?, ?) IF NOT EXISTS`,
title, revid, modified, deleted).MapScanCAS(mapCAS); err != nil {
t.Fatal("insert:", err)
} else if !applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", title, revid, modified)
}
mapCAS = map[string]interface{}{}
if applied, err := session.Query(`INSERT INTO cas_table2 (title, revid, last_modified, deleted)
VALUES (?, ?, ?, ?) IF NOT EXISTS`,
title, revid, modified, deleted).MapScanCAS(mapCAS); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatalf("insert should have been applied: title=%v revID=%v modified=%v", title, revid, modified)
} else if title != mapCAS["title"] || revid != mapCAS["revid"] || deleted != mapCAS["deleted"] {
t.Fatalf("expected %s/%v/%v/%v but got %s/%v/%v%v", title, revid, modified, false, mapCAS["title"], mapCAS["revid"], mapCAS["last_modified"], mapCAS["deleted"])
}
}
func TestBatch(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.batch_table (id int primary key)`); err != nil {
t.Fatal("create table:", err)
}
batch := NewBatch(LoggedBatch)
for i := 0; i < 100; i++ {
batch.Query(`INSERT INTO batch_table (id) VALUES (?)`, i)
}
if err := session.ExecuteBatch(batch); err != nil {
t.Fatal("execute batch:", err)
}
count := 0
if err := session.Query(`SELECT COUNT(*) FROM batch_table`).Scan(&count); err != nil {
t.Fatal("select count:", err)
} else if count != 100 {
t.Fatalf("count: expected %d, got %d\n", 100, count)
}
}
func TestUnpreparedBatch(t *testing.T) {
t.Skip("FLAKE skipping")
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.batch_unprepared (id int primary key, c counter)`); err != nil {
t.Fatal("create table:", err)
}
var batch *Batch
if session.cfg.ProtoVersion == 2 {
batch = NewBatch(CounterBatch)
} else {
batch = NewBatch(UnloggedBatch)
}
for i := 0; i < 100; i++ {
batch.Query(`UPDATE batch_unprepared SET c = c + 1 WHERE id = 1`)
}
if err := session.ExecuteBatch(batch); err != nil {
t.Fatal("execute batch:", err)
}
count := 0
if err := session.Query(`SELECT COUNT(*) FROM batch_unprepared`).Scan(&count); err != nil {
t.Fatal("select count:", err)
} else if count != 1 {
t.Fatalf("count: expected %d, got %d\n", 100, count)
}
if err := session.Query(`SELECT c FROM batch_unprepared`).Scan(&count); err != nil {
t.Fatal("select count:", err)
} else if count != 100 {
t.Fatalf("count: expected %d, got %d\n", 100, count)
}
}
// TestBatchLimit tests gocql to make sure batch operations larger than the maximum
// statement limit are not submitted to a cassandra node.
func TestBatchLimit(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.batch_table2 (id int primary key)`); err != nil {
t.Fatal("create table:", err)
}
batch := NewBatch(LoggedBatch)
for i := 0; i < 65537; i++ {
batch.Query(`INSERT INTO batch_table2 (id) VALUES (?)`, i)
}
if err := session.ExecuteBatch(batch); err != ErrTooManyStmts {
t.Fatal("gocql attempted to execute a batch larger than the support limit of statements.")
}
}
func TestWhereIn(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.where_in_table (id int, cluster int, primary key (id,cluster))`); err != nil {
t.Fatal("create table:", err)
}
if err := session.Query("INSERT INTO where_in_table (id, cluster) VALUES (?,?)", 100, 200).Exec(); err != nil {
t.Fatal("insert:", err)
}
iter := session.Query("SELECT * FROM where_in_table WHERE id = ? AND cluster IN (?)", 100, 200).Iter()
var id, cluster int
count := 0
for iter.Scan(&id, &cluster) {
count++
}
if id != 100 || cluster != 200 {
t.Fatalf("Was expecting id and cluster to be (100,200) but were (%d,%d)", id, cluster)
}
}
// TestTooManyQueryArgs tests to make sure the library correctly handles the application level bug
// whereby too many query arguments are passed to a query
func TestTooManyQueryArgs(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.too_many_query_args (id int primary key, value int)`); err != nil {
t.Fatal("create table:", err)
}
_, err := session.Query(`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2).Iter().SliceMap()
if err == nil {
t.Fatal("'`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2' should return an error")
}
batch := session.NewBatch(UnloggedBatch)
batch.Query("INSERT INTO too_many_query_args (id, value) VALUES (?, ?)", 1, 2, 3)
err = session.ExecuteBatch(batch)
if err == nil {
t.Fatal("'`INSERT INTO too_many_query_args (id, value) VALUES (?, ?)`, 1, 2, 3' should return an error")
}
// TODO: should indicate via an error code that it is an invalid arg?
}
// TestNotEnoughQueryArgs tests to make sure the library correctly handles the application level bug
// whereby not enough query arguments are passed to a query
func TestNotEnoughQueryArgs(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.not_enough_query_args (id int, cluster int, value int, primary key (id, cluster))`); err != nil {
t.Fatal("create table:", err)
}
_, err := session.Query(`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1).Iter().SliceMap()
if err == nil {
t.Fatal("'`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1' should return an error")
}
batch := session.NewBatch(UnloggedBatch)
batch.Query("INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)", 1, 2)
err = session.ExecuteBatch(batch)
if err == nil {
t.Fatal("'`INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)`, 1, 2' should return an error")
}
}
// TestCreateSessionTimeout tests to make sure the CreateSession function timeouts out correctly
// and prevents an infinite loop of connection retries.
func TestCreateSessionTimeout(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
select {
case <-time.After(2 * time.Second):
t.Error("no startup timeout")
case <-ctx.Done():
}
}()
cluster := createCluster()
cluster.Hosts = []string{"127.0.0.1:1"}
session, err := cluster.CreateSession()
if err == nil {
session.Close()
t.Fatal("expected ErrNoConnectionsStarted, but no error was returned.")
}
}
func TestReconnection(t *testing.T) {
cluster := createCluster()
cluster.ReconnectInterval = 1 * time.Second
session := createSessionFromCluster(cluster, t)
defer session.Close()
h := session.ring.allHosts()[0]
session.handleNodeDown(h.ConnectAddress(), h.Port())
if h.State() != NodeDown {
t.Fatal("Host should be NodeDown but not.")
}
time.Sleep(cluster.ReconnectInterval + h.Version().nodeUpDelay() + 1*time.Second)
if h.State() != NodeUp {
t.Fatal("Host should be NodeUp but not. Failed to reconnect.")
}
}
type FullName struct {
FirstName string
LastName string
}
func (n FullName) MarshalCQL(info TypeInfo) ([]byte, error) {
return []byte(n.FirstName + " " + n.LastName), nil
}
func (n *FullName) UnmarshalCQL(info TypeInfo, data []byte) error {
t := strings.SplitN(string(data), " ", 2)
n.FirstName, n.LastName = t[0], t[1]
return nil
}
func TestMapScanWithRefMap(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.scan_map_ref_table (
testtext text PRIMARY KEY,
testfullname text,
testint int,
)`); err != nil {
t.Fatal("create table:", err)
}
m := make(map[string]interface{})
m["testtext"] = "testtext"
m["testfullname"] = FullName{"John", "Doe"}
m["testint"] = 100
if err := session.Query(`INSERT INTO scan_map_ref_table (testtext, testfullname, testint) values (?,?,?)`,
m["testtext"], m["testfullname"], m["testint"]).Exec(); err != nil {
t.Fatal("insert:", err)
}
var testText string
var testFullName FullName
ret := map[string]interface{}{
"testtext": &testText,
"testfullname": &testFullName,
// testint is not set here.
}
iter := session.Query(`SELECT * FROM scan_map_ref_table`).Iter()
if ok := iter.MapScan(ret); !ok {
t.Fatal("select:", iter.Close())
} else {
if ret["testtext"] != "testtext" {
t.Fatal("returned testtext did not match")
}
f := ret["testfullname"].(FullName)
if f.FirstName != "John" || f.LastName != "Doe" {
t.Fatal("returned testfullname did not match")
}
if ret["testint"] != 100 {
t.Fatal("returned testinit did not match")
}
}
if testText != "testtext" {
t.Fatal("returned testtext did not match")
}
if testFullName.FirstName != "John" || testFullName.LastName != "Doe" {
t.Fatal("returned testfullname did not match")
}
// using MapScan to read a nil int value
intp := new(int64)
ret = map[string]interface{}{
"testint": &intp,
}
if err := session.Query("INSERT INTO scan_map_ref_table(testtext, testint) VALUES(?, ?)", "null-int", nil).Exec(); err != nil {
t.Fatal(err)
}
err := session.Query(`SELECT testint FROM scan_map_ref_table WHERE testtext = ?`, "null-int").MapScan(ret)
if err != nil {
t.Fatal(err)
} else if v := ret["testint"].(*int64); v != nil {
t.Fatalf("testint should be nil got %+#v", v)
}
}
func TestMapScan(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.scan_map_table (
fullname text PRIMARY KEY,
age int,
address inet,
)`); err != nil {
t.Fatal("create table:", err)
}
if err := session.Query(`INSERT INTO scan_map_table (fullname, age, address) values (?,?,?)`,
"Grace Hopper", 31, net.ParseIP("10.0.0.1")).Exec(); err != nil {
t.Fatal("insert:", err)
}
if err := session.Query(`INSERT INTO scan_map_table (fullname, age, address) values (?,?,?)`,
"Ada Lovelace", 30, net.ParseIP("10.0.0.2")).Exec(); err != nil {
t.Fatal("insert:", err)
}
iter := session.Query(`SELECT * FROM scan_map_table`).Iter()
// First iteration
row := make(map[string]interface{})
if !iter.MapScan(row) {
t.Fatal("select:", iter.Close())
}
assertEqual(t, "fullname", "Ada Lovelace", row["fullname"])
assertEqual(t, "age", 30, row["age"])
assertEqual(t, "address", "10.0.0.2", row["address"])
// Second iteration using a new map
row = make(map[string]interface{})
if !iter.MapScan(row) {
t.Fatal("select:", iter.Close())
}
assertEqual(t, "fullname", "Grace Hopper", row["fullname"])
assertEqual(t, "age", 31, row["age"])
assertEqual(t, "address", "10.0.0.1", row["address"])
}
func TestSliceMap(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.slice_map_table (
testuuid timeuuid PRIMARY KEY,
testtimestamp timestamp,
testvarchar varchar,
testbigint bigint,
testblob blob,
testbool boolean,
testfloat float,
testdouble double,
testint int,
testdecimal decimal,
testlist list<text>,
testset set<int>,
testmap map<varchar, varchar>,
testvarint varint,
testinet inet
)`); err != nil {
t.Fatal("create table:", err)
}
m := make(map[string]interface{})
bigInt := new(big.Int)
if _, ok := bigInt.SetString("830169365738487321165427203929228", 10); !ok {
t.Fatal("Failed setting bigint by string")
}
m["testuuid"] = TimeUUID()
m["testvarchar"] = "Test VarChar"
m["testbigint"] = time.Now().Unix()
m["testtimestamp"] = time.Now().Truncate(time.Millisecond).UTC()
m["testblob"] = []byte("test blob")
m["testbool"] = true
m["testfloat"] = float32(4.564)
m["testdouble"] = float64(4.815162342)
m["testint"] = 2343
m["testdecimal"] = inf.NewDec(100, 0)
m["testlist"] = []string{"quux", "foo", "bar", "baz", "quux"}
m["testset"] = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
m["testmap"] = map[string]string{"field1": "val1", "field2": "val2", "field3": "val3"}
m["testvarint"] = bigInt
m["testinet"] = "213.212.2.19"
sliceMap := []map[string]interface{}{m}
if err := session.Query(`INSERT INTO slice_map_table (testuuid, testtimestamp, testvarchar, testbigint, testblob, testbool, testfloat, testdouble, testint, testdecimal, testlist, testset, testmap, testvarint, testinet) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
m["testuuid"], m["testtimestamp"], m["testvarchar"], m["testbigint"], m["testblob"], m["testbool"], m["testfloat"], m["testdouble"], m["testint"], m["testdecimal"], m["testlist"], m["testset"], m["testmap"], m["testvarint"], m["testinet"]).Exec(); err != nil {
t.Fatal("insert:", err)
}
if returned, retErr := session.Query(`SELECT * FROM slice_map_table`).Iter().SliceMap(); retErr != nil {
t.Fatal("select:", retErr)
} else {
matchSliceMap(t, sliceMap, returned[0])
}
// Test for Iter.MapScan()
{
testMap := make(map[string]interface{})
if !session.Query(`SELECT * FROM slice_map_table`).Iter().MapScan(testMap) {
t.Fatal("MapScan failed to work with one row")
}
matchSliceMap(t, sliceMap, testMap)
}
// Test for Query.MapScan()
{
testMap := make(map[string]interface{})
if session.Query(`SELECT * FROM slice_map_table`).MapScan(testMap) != nil {
t.Fatal("MapScan failed to work with one row")
}
matchSliceMap(t, sliceMap, testMap)
}
}
func matchSliceMap(t *testing.T, sliceMap []map[string]interface{}, testMap map[string]interface{}) {
if sliceMap[0]["testuuid"] != testMap["testuuid"] {
t.Fatal("returned testuuid did not match")
}
if sliceMap[0]["testtimestamp"] != testMap["testtimestamp"] {
t.Fatal("returned testtimestamp did not match")
}
if sliceMap[0]["testvarchar"] != testMap["testvarchar"] {
t.Fatal("returned testvarchar did not match")
}
if sliceMap[0]["testbigint"] != testMap["testbigint"] {
t.Fatal("returned testbigint did not match")
}
if !reflect.DeepEqual(sliceMap[0]["testblob"], testMap["testblob"]) {
t.Fatal("returned testblob did not match")
}
if sliceMap[0]["testbool"] != testMap["testbool"] {
t.Fatal("returned testbool did not match")
}
if sliceMap[0]["testfloat"] != testMap["testfloat"] {
t.Fatal("returned testfloat did not match")
}
if sliceMap[0]["testdouble"] != testMap["testdouble"] {
t.Fatal("returned testdouble did not match")
}
if sliceMap[0]["testinet"] != testMap["testinet"] {
t.Fatal("returned testinet did not match")
}
expectedDecimal := sliceMap[0]["testdecimal"].(*inf.Dec)
returnedDecimal := testMap["testdecimal"].(*inf.Dec)
if expectedDecimal.Cmp(returnedDecimal) != 0 {
t.Fatal("returned testdecimal did not match")
}
if !reflect.DeepEqual(sliceMap[0]["testlist"], testMap["testlist"]) {
t.Fatal("returned testlist did not match")
}
if !reflect.DeepEqual(sliceMap[0]["testset"], testMap["testset"]) {
t.Fatal("returned testset did not match")
}
if !reflect.DeepEqual(sliceMap[0]["testmap"], testMap["testmap"]) {
t.Fatal("returned testmap did not match")
}
if sliceMap[0]["testint"] != testMap["testint"] {
t.Fatal("returned testint did not match")
}
}
func TestSmallInt(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion < protoVersion4 {
t.Skip("smallint is only supported in cassandra 2.2+")
}
if err := createTable(session, `CREATE TABLE gocql_test.smallint_table (
testsmallint smallint PRIMARY KEY,
)`); err != nil {
t.Fatal("create table:", err)
}
m := make(map[string]interface{})
m["testsmallint"] = int16(2)
sliceMap := []map[string]interface{}{m}
if err := session.Query(`INSERT INTO smallint_table (testsmallint) VALUES (?)`,
m["testsmallint"]).Exec(); err != nil {
t.Fatal("insert:", err)
}
if returned, retErr := session.Query(`SELECT * FROM smallint_table`).Iter().SliceMap(); retErr != nil {
t.Fatal("select:", retErr)
} else {
if sliceMap[0]["testsmallint"] != returned[0]["testsmallint"] {
t.Fatal("returned testsmallint did not match")
}
}
}
func TestScanWithNilArguments(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.scan_with_nil_arguments (
foo varchar,
bar int,
PRIMARY KEY (foo, bar)
)`); err != nil {
t.Fatal("create:", err)
}
for i := 1; i <= 20; i++ {
if err := session.Query("INSERT INTO scan_with_nil_arguments (foo, bar) VALUES (?, ?)",
"squares", i*i).Exec(); err != nil {
t.Fatal("insert:", err)
}
}
iter := session.Query("SELECT * FROM scan_with_nil_arguments WHERE foo = ?", "squares").Iter()
var n int
count := 0
for iter.Scan(nil, &n) {
count += n
}
if err := iter.Close(); err != nil {
t.Fatal("close:", err)
}
if count != 2870 {
t.Fatalf("expected %d, got %d", 2870, count)
}
}
func TestScanCASWithNilArguments(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, `CREATE TABLE gocql_test.scan_cas_with_nil_arguments (
foo varchar,
bar varchar,
PRIMARY KEY (foo, bar)
)`); err != nil {
t.Fatal("create:", err)
}
foo := "baz"
var cas string
if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
VALUES (?, ?) IF NOT EXISTS`,
foo, foo).ScanCAS(nil, nil); err != nil {
t.Fatal("insert:", err)
} else if !applied {
t.Fatal("insert should have been applied")
}
if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
VALUES (?, ?) IF NOT EXISTS`,
foo, foo).ScanCAS(&cas, nil); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatal("insert should not have been applied")
} else if foo != cas {
t.Fatalf("expected %v but got %v", foo, cas)
}
if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar)
VALUES (?, ?) IF NOT EXISTS`,
foo, foo).ScanCAS(nil, &cas); err != nil {
t.Fatal("insert:", err)
} else if applied {
t.Fatal("insert should not have been applied")
} else if foo != cas {
t.Fatalf("expected %v but got %v", foo, cas)
}
}
func TestRebindQueryInfo(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.rebind_query (id int, value text, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
if err := session.Query("INSERT INTO rebind_query (id, value) VALUES (?, ?)", 23, "quux").Exec(); err != nil {
t.Fatalf("insert into rebind_query failed, err '%v'", err)
}
if err := session.Query("INSERT INTO rebind_query (id, value) VALUES (?, ?)", 24, "w00t").Exec(); err != nil {
t.Fatalf("insert into rebind_query failed, err '%v'", err)
}
q := session.Query("SELECT value FROM rebind_query WHERE ID = ?")
q.Bind(23)
iter := q.Iter()
var value string
for iter.Scan(&value) {
}
if value != "quux" {
t.Fatalf("expected %v but got %v", "quux", value)
}
q.Bind(24)
iter = q.Iter()
for iter.Scan(&value) {
}
if value != "w00t" {
t.Fatalf("expected %v but got %v", "quux", value)
}
}
//TestStaticQueryInfo makes sure that the application can manually bind query parameters using the simplest possible static binding strategy
func TestStaticQueryInfo(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.static_query_info (id int, value text, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
if err := session.Query("INSERT INTO static_query_info (id, value) VALUES (?, ?)", 113, "foo").Exec(); err != nil {
t.Fatalf("insert into static_query_info failed, err '%v'", err)
}
autobinder := func(q *QueryInfo) ([]interface{}, error) {
values := make([]interface{}, 1)
values[0] = 113
return values, nil
}
qry := session.Bind("SELECT id, value FROM static_query_info WHERE id = ?", autobinder)
if err := qry.Exec(); err != nil {
t.Fatalf("expose query info failed, error '%v'", err)
}
iter := qry.Iter()
var id int
var value string
iter.Scan(&id, &value)
if err := iter.Close(); err != nil {
t.Fatalf("query with exposed info failed, err '%v'", err)
}
if value != "foo" {
t.Fatalf("Expected value %s, but got %s", "foo", value)
}
}
type ClusteredKeyValue struct {
Id int
Cluster int
Value string
}
func (kv *ClusteredKeyValue) Bind(q *QueryInfo) ([]interface{}, error) {
values := make([]interface{}, len(q.Args))
for i, info := range q.Args {
fieldName := upcaseInitial(info.Name)
value := reflect.ValueOf(kv)
field := reflect.Indirect(value).FieldByName(fieldName)
values[i] = field.Addr().Interface()
}
return values, nil
}
func upcaseInitial(str string) string {
for i, v := range str {
return string(unicode.ToUpper(v)) + str[i+1:]
}
return ""
}
//TestBoundQueryInfo makes sure that the application can manually bind query parameters using the query meta data supplied at runtime
func TestBoundQueryInfo(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.clustered_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
write := &ClusteredKeyValue{Id: 200, Cluster: 300, Value: "baz"}
insert := session.Bind("INSERT INTO clustered_query_info (id, cluster, value) VALUES (?, ?,?)", write.Bind)
if err := insert.Exec(); err != nil {
t.Fatalf("insert into clustered_query_info failed, err '%v'", err)
}
read := &ClusteredKeyValue{Id: 200, Cluster: 300}
qry := session.Bind("SELECT id, cluster, value FROM clustered_query_info WHERE id = ? and cluster = ?", read.Bind)
iter := qry.Iter()
var id, cluster int
var value string
iter.Scan(&id, &cluster, &value)
if err := iter.Close(); err != nil {
t.Fatalf("query with clustered_query_info info failed, err '%v'", err)
}
if value != "baz" {
t.Fatalf("Expected value %s, but got %s", "baz", value)
}
}
//TestBatchQueryInfo makes sure that the application can manually bind query parameters when executing in a batch
func TestBatchQueryInfo(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, "CREATE TABLE gocql_test.batch_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
write := func(q *QueryInfo) ([]interface{}, error) {
values := make([]interface{}, 3)
values[0] = 4000
values[1] = 5000
values[2] = "bar"
return values, nil
}
batch := session.NewBatch(LoggedBatch)
batch.Bind("INSERT INTO batch_query_info (id, cluster, value) VALUES (?, ?,?)", write)
if err := session.ExecuteBatch(batch); err != nil {
t.Fatalf("batch insert into batch_query_info failed, err '%v'", err)
}
read := func(q *QueryInfo) ([]interface{}, error) {
values := make([]interface{}, 2)
values[0] = 4000
values[1] = 5000
return values, nil
}
qry := session.Bind("SELECT id, cluster, value FROM batch_query_info WHERE id = ? and cluster = ?", read)
iter := qry.Iter()
var id, cluster int
var value string
iter.Scan(&id, &cluster, &value)
if err := iter.Close(); err != nil {
t.Fatalf("query with batch_query_info info failed, err '%v'", err)
}
if value != "bar" {
t.Fatalf("Expected value %s, but got %s", "bar", value)
}
}
func getRandomConn(t *testing.T, session *Session) *Conn {
conn := session.getConn()
if conn == nil {
t.Fatal("unable to get a connection")
}
return conn
}
func injectInvalidPreparedStatement(t *testing.T, session *Session, table string) (string, *Conn) {
if err := createTable(session, `CREATE TABLE gocql_test.`+table+` (
foo varchar,
bar int,
PRIMARY KEY (foo, bar)
)`); err != nil {
t.Fatal("create:", err)
}
stmt := "INSERT INTO " + table + " (foo, bar) VALUES (?, 7)"
conn := getRandomConn(t, session)
flight := new(inflightPrepare)
key := session.stmtsLRU.keyFor(conn.addr, "", stmt)
session.stmtsLRU.add(key, flight)
flight.preparedStatment = &preparedStatment{
id: []byte{'f', 'o', 'o', 'b', 'a', 'r'},
request: preparedMetadata{
resultMetadata: resultMetadata{
colCount: 1,
actualColCount: 1,
columns: []ColumnInfo{
{
Keyspace: "gocql_test",
Table: table,
Name: "foo",
TypeInfo: NativeType{
typ: TypeVarchar,
},
},
},
},
},
}
return stmt, conn
}
func TestPrepare_MissingSchemaPrepare(t *testing.T) {
s := createSession(t)
conn := getRandomConn(t, s)
defer s.Close()
insertQry := &Query{stmt: "INSERT INTO invalidschemaprep (val) VALUES (?)", values: []interface{}{5}, cons: s.cons,
session: s, pageSize: s.pageSize, trace: s.trace,
prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
if err := conn.executeQuery(insertQry).err; err == nil {
t.Fatal("expected error, but got nil.")
}
if err := createTable(s, "CREATE TABLE gocql_test.invalidschemaprep (val int, PRIMARY KEY (val))"); err != nil {
t.Fatal("create table:", err)
}
if err := conn.executeQuery(insertQry).err; err != nil {
t.Fatal(err) // unconfigured columnfamily
}
}
func TestPrepare_ReprepareStatement(t *testing.T) {
session := createSession(t)
defer session.Close()
stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement")
query := session.Query(stmt, "bar")
if err := conn.executeQuery(query).Close(); err != nil {
t.Fatalf("Failed to execute query for reprepare statement: %v", err)
}
}
func TestPrepare_ReprepareBatch(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement_batch")
batch := session.NewBatch(UnloggedBatch)
batch.Query(stmt, "bar")
if err := conn.executeBatch(batch).Close(); err != nil {
t.Fatalf("Failed to execute query for reprepare statement: %v", err)
}
}
func TestQueryInfo(t *testing.T) {
session := createSession(t)
defer session.Close()
conn := getRandomConn(t, session)
info, err := conn.prepareStatement(context.Background(), "SELECT release_version, host_id FROM system.local WHERE key = ?", nil)
if err != nil {
t.Fatalf("Failed to execute query for preparing statement: %v", err)
}
if x := len(info.request.columns); x != 1 {
t.Fatalf("Was not expecting meta data for %d query arguments, but got %d\n", 1, x)
}
if session.cfg.ProtoVersion > 1 {
if x := len(info.response.columns); x != 2 {
t.Fatalf("Was not expecting meta data for %d result columns, but got %d\n", 2, x)
}
}
}
//TestPreparedCacheEviction will make sure that the cache size is maintained
func TestPrepare_PreparedCacheEviction(t *testing.T) {
const maxPrepared = 4
host := clusterHosts[0]
cluster := createCluster()
cluster.MaxPreparedStmts = maxPrepared
cluster.Events.DisableSchemaEvents = true
cluster.Hosts = []string{host}
cluster.HostFilter = WhiteListHostFilter(host)
session := createSessionFromCluster(cluster, t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.prepcachetest (id int,mod int,PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
// clear the cache
session.stmtsLRU.clear()
//Fill the table
for i := 0; i < 2; i++ {
if err := session.Query("INSERT INTO prepcachetest (id,mod) VALUES (?, ?)", i, 10000%(i+1)).Exec(); err != nil {
t.Fatalf("insert into prepcachetest failed, err '%v'", err)
}
}
//Populate the prepared statement cache with select statements
var id, mod int
for i := 0; i < 2; i++ {
err := session.Query("SELECT id,mod FROM prepcachetest WHERE id = "+strconv.FormatInt(int64(i), 10)).Scan(&id, &mod)
if err != nil {
t.Fatalf("select from prepcachetest failed, error '%v'", err)
}
}
//generate an update statement to test they are prepared
err := session.Query("UPDATE prepcachetest SET mod = ? WHERE id = ?", 1, 11).Exec()
if err != nil {
t.Fatalf("update prepcachetest failed, error '%v'", err)
}
//generate a delete statement to test they are prepared
err = session.Query("DELETE FROM prepcachetest WHERE id = ?", 1).Exec()
if err != nil {
t.Fatalf("delete from prepcachetest failed, error '%v'", err)
}
//generate an insert statement to test they are prepared
err = session.Query("INSERT INTO prepcachetest (id,mod) VALUES (?, ?)", 3, 11).Exec()
if err != nil {
t.Fatalf("insert into prepcachetest failed, error '%v'", err)
}
session.stmtsLRU.mu.Lock()
defer session.stmtsLRU.mu.Unlock()
//Make sure the cache size is maintained
if session.stmtsLRU.lru.Len() != session.stmtsLRU.lru.MaxEntries {
t.Fatalf("expected cache size of %v, got %v", session.stmtsLRU.lru.MaxEntries, session.stmtsLRU.lru.Len())
}
// Walk through all the configured hosts and test cache retention and eviction
for _, host := range session.cfg.Hosts {
_, ok := session.stmtsLRU.lru.Get(session.stmtsLRU.keyFor(host+":9042", session.cfg.Keyspace, "SELECT id,mod FROM prepcachetest WHERE id = 0"))
if ok {
t.Errorf("expected first select to be purged but was in cache for host=%q", host)
}
_, ok = session.stmtsLRU.lru.Get(session.stmtsLRU.keyFor(host+":9042", session.cfg.Keyspace, "SELECT id,mod FROM prepcachetest WHERE id = 1"))
if !ok {
t.Errorf("exepected second select to be in cache for host=%q", host)
}
_, ok = session.stmtsLRU.lru.Get(session.stmtsLRU.keyFor(host+":9042", session.cfg.Keyspace, "INSERT INTO prepcachetest (id,mod) VALUES (?, ?)"))
if !ok {
t.Errorf("expected insert to be in cache for host=%q", host)
}
_, ok = session.stmtsLRU.lru.Get(session.stmtsLRU.keyFor(host+":9042", session.cfg.Keyspace, "UPDATE prepcachetest SET mod = ? WHERE id = ?"))
if !ok {
t.Errorf("expected update to be in cached for host=%q", host)
}
_, ok = session.stmtsLRU.lru.Get(session.stmtsLRU.keyFor(host+":9042", session.cfg.Keyspace, "DELETE FROM prepcachetest WHERE id = ?"))
if !ok {
t.Errorf("expected delete to be cached for host=%q", host)
}
}
}
func TestPrepare_PreparedCacheKey(t *testing.T) {
session := createSession(t)
defer session.Close()
// create a second keyspace
cluster2 := createCluster()
createKeyspace(t, cluster2, "gocql_test2")
cluster2.Keyspace = "gocql_test2"
session2, err := cluster2.CreateSession()
if err != nil {
t.Fatal("create session:", err)
}
defer session2.Close()
// both keyspaces have a table named "test_stmt_cache_key"
if err := createTable(session, "CREATE TABLE gocql_test.test_stmt_cache_key (id varchar primary key, field varchar)"); err != nil {
t.Fatal("create table:", err)
}
if err := createTable(session2, "CREATE TABLE gocql_test2.test_stmt_cache_key (id varchar primary key, field varchar)"); err != nil {
t.Fatal("create table:", err)
}
// both tables have a single row with the same partition key but different column value
if err = session.Query(`INSERT INTO test_stmt_cache_key (id, field) VALUES (?, ?)`, "key", "one").Exec(); err != nil {
t.Fatal("insert:", err)
}
if err = session2.Query(`INSERT INTO test_stmt_cache_key (id, field) VALUES (?, ?)`, "key", "two").Exec(); err != nil {
t.Fatal("insert:", err)
}
// should be able to see different values in each keyspace
var value string
if err = session.Query("SELECT field FROM test_stmt_cache_key WHERE id = ?", "key").Scan(&value); err != nil {
t.Fatal("select:", err)
}
if value != "one" {
t.Errorf("Expected one, got %s", value)
}
if err = session2.Query("SELECT field FROM test_stmt_cache_key WHERE id = ?", "key").Scan(&value); err != nil {
t.Fatal("select:", err)
}
if value != "two" {
t.Errorf("Expected two, got %s", value)
}
}
//TestMarshalFloat64Ptr tests to see that a pointer to a float64 is marshalled correctly.
func TestMarshalFloat64Ptr(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.float_test (id double, test double, primary key (id))"); err != nil {
t.Fatal("create table:", err)
}
testNum := float64(7500)
if err := session.Query(`INSERT INTO float_test (id,test) VALUES (?,?)`, float64(7500.00), &testNum).Exec(); err != nil {
t.Fatal("insert float64:", err)
}
}
//TestMarshalInet tests to see that a pointer to a float64 is marshalled correctly.
func TestMarshalInet(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.inet_test (ip inet, name text, primary key (ip))"); err != nil {
t.Fatal("create table:", err)
}
stringIp := "123.34.45.56"
if err := session.Query(`INSERT INTO inet_test (ip,name) VALUES (?,?)`, stringIp, "Test IP 1").Exec(); err != nil {
t.Fatal("insert string inet:", err)
}
var stringResult string
if err := session.Query("SELECT ip FROM inet_test").Scan(&stringResult); err != nil {
t.Fatalf("select for string from inet_test 1 failed: %v", err)
}
if stringResult != stringIp {
t.Errorf("Expected %s, was %s", stringIp, stringResult)
}
var ipResult net.IP
if err := session.Query("SELECT ip FROM inet_test").Scan(&ipResult); err != nil {
t.Fatalf("select for net.IP from inet_test 1 failed: %v", err)
}
if ipResult.String() != stringIp {
t.Errorf("Expected %s, was %s", stringIp, ipResult.String())
}
if err := session.Query(`DELETE FROM inet_test WHERE ip = ?`, stringIp).Exec(); err != nil {
t.Fatal("delete inet table:", err)
}
netIp := net.ParseIP("222.43.54.65")
if err := session.Query(`INSERT INTO inet_test (ip,name) VALUES (?,?)`, netIp, "Test IP 2").Exec(); err != nil {
t.Fatal("insert netIp inet:", err)
}
if err := session.Query("SELECT ip FROM inet_test").Scan(&stringResult); err != nil {
t.Fatalf("select for string from inet_test 2 failed: %v", err)
}
if stringResult != netIp.String() {
t.Errorf("Expected %s, was %s", netIp.String(), stringResult)
}
if err := session.Query("SELECT ip FROM inet_test").Scan(&ipResult); err != nil {
t.Fatalf("select for net.IP from inet_test 2 failed: %v", err)
}
if ipResult.String() != netIp.String() {
t.Errorf("Expected %s, was %s", netIp.String(), ipResult.String())
}
}
func TestVarint(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.varint_test (id varchar, test varint, test2 varint, primary key (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", 0).Exec(); err != nil {
t.Fatalf("insert varint: %v", err)
}
var result int
if err := session.Query("SELECT test FROM varint_test").Scan(&result); err != nil {
t.Fatalf("select from varint_test failed: %v", err)
}
if result != 0 {
t.Errorf("Expected 0, was %d", result)
}
if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", -1).Exec(); err != nil {
t.Fatalf("insert varint: %v", err)
}
if err := session.Query("SELECT test FROM varint_test").Scan(&result); err != nil {
t.Fatalf("select from varint_test failed: %v", err)
}
if result != -1 {
t.Errorf("Expected -1, was %d", result)
}
if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", nil).Exec(); err != nil {
t.Fatalf("insert varint: %v", err)
}
if err := session.Query("SELECT test FROM varint_test").Scan(&result); err != nil {
t.Fatalf("select from varint_test failed: %v", err)
}
if result != 0 {
t.Errorf("Expected 0, was %d", result)
}
var nullableResult *int
if err := session.Query("SELECT test FROM varint_test").Scan(&nullableResult); err != nil {
t.Fatalf("select from varint_test failed: %v", err)
}
if nullableResult != nil {
t.Errorf("Expected nil, was %d", nullableResult)
}
if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", int64(math.MaxInt32)+1).Exec(); err != nil {
t.Fatalf("insert varint: %v", err)
}
var result64 int64
if err := session.Query("SELECT test FROM varint_test").Scan(&result64); err != nil {
t.Fatalf("select from varint_test failed: %v", err)
}
if result64 != int64(math.MaxInt32)+1 {
t.Errorf("Expected %d, was %d", int64(math.MaxInt32)+1, result64)
}
biggie := new(big.Int)
biggie.SetString("36893488147419103232", 10) // > 2**64
if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", biggie).Exec(); err != nil {
t.Fatalf("insert varint: %v", err)
}
resultBig := new(big.Int)
if err := session.Query("SELECT test FROM varint_test").Scan(resultBig); err != nil {
t.Fatalf("select from varint_test failed: %v", err)
}
if resultBig.String() != biggie.String() {
t.Errorf("Expected %s, was %s", biggie.String(), resultBig.String())
}
err := session.Query("SELECT test FROM varint_test").Scan(&result64)
if err == nil || strings.Index(err.Error(), "out of range") == -1 {
t.Errorf("expected out of range error since value is too big for int64")
}
// value not set in cassandra, leave bind variable empty
resultBig = new(big.Int)
if err := session.Query("SELECT test2 FROM varint_test").Scan(resultBig); err != nil {
t.Fatalf("select from varint_test failed: %v", err)
}
if resultBig.Int64() != 0 {
t.Errorf("Expected %s, was %s", biggie.String(), resultBig.String())
}
// can use double pointer to explicitly detect value is not set in cassandra
if err := session.Query("SELECT test2 FROM varint_test").Scan(&resultBig); err != nil {
t.Fatalf("select from varint_test failed: %v", err)
}
if resultBig != nil {
t.Errorf("Expected %v, was %v", nil, *resultBig)
}
}
//TestQueryStats confirms that the stats are returning valid data. Accuracy may be questionable.
func TestQueryStats(t *testing.T) {
session := createSession(t)
defer session.Close()
qry := session.Query("SELECT * FROM system.peers")
if err := qry.Exec(); err != nil {
t.Fatalf("query failed. %v", err)
} else {
if qry.Attempts() < 1 {
t.Fatal("expected at least 1 attempt, but got 0")
}
if qry.Latency() <= 0 {
t.Fatalf("expected latency to be greater than 0, but got %v instead.", qry.Latency())
}
}
}
// TestIterHosts confirms that host is added to Iter when the query succeeds.
func TestIterHost(t *testing.T) {
session := createSession(t)
defer session.Close()
iter := session.Query("SELECT * FROM system.peers").Iter()
// check if Host method works
if iter.Host() == nil {
t.Error("No host in iter")
}
}
//TestBatchStats confirms that the stats are returning valid data. Accuracy may be questionable.
func TestBatchStats(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion == 1 {
t.Skip("atomic batches not supported. Please use Cassandra >= 2.0")
}
if err := createTable(session, "CREATE TABLE gocql_test.batchStats (id int, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
b := session.NewBatch(LoggedBatch)
b.Query("INSERT INTO batchStats (id) VALUES (?)", 1)
b.Query("INSERT INTO batchStats (id) VALUES (?)", 2)
if err := session.ExecuteBatch(b); err != nil {
t.Fatalf("query failed. %v", err)
} else {
if b.Attempts() < 1 {
t.Fatal("expected at least 1 attempt, but got 0")
}
if b.Latency() <= 0 {
t.Fatalf("expected latency to be greater than 0, but got %v instead.", b.Latency())
}
}
}
//TestNilInQuery tests to see that a nil value passed to a query is handled by Cassandra
//TODO validate the nil value by reading back the nil. Need to fix Unmarshalling.
func TestNilInQuery(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.testNilInsert (id int, count int, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
if err := session.Query("INSERT INTO testNilInsert (id,count) VALUES (?,?)", 1, nil).Exec(); err != nil {
t.Fatalf("failed to insert with err: %v", err)
}
var id int
if err := session.Query("SELECT id FROM testNilInsert").Scan(&id); err != nil {
t.Fatalf("failed to select with err: %v", err)
} else if id != 1 {
t.Fatalf("expected id to be 1, got %v", id)
}
}
// Don't initialize time.Time bind variable if cassandra timestamp column is empty
func TestEmptyTimestamp(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.test_empty_timestamp (id int, time timestamp, num int, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
if err := session.Query("INSERT INTO test_empty_timestamp (id, num) VALUES (?,?)", 1, 561).Exec(); err != nil {
t.Fatalf("failed to insert with err: %v", err)
}
var timeVal time.Time
if err := session.Query("SELECT time FROM test_empty_timestamp where id = ?", 1).Scan(&timeVal); err != nil {
t.Fatalf("failed to select with err: %v", err)
}
if !timeVal.IsZero() {
t.Errorf("time.Time bind variable should still be empty (was %s)", timeVal)
}
}
// Integration test of just querying for data from the system.schema_keyspace table where the keyspace DOES exist.
func TestGetKeyspaceMetadata(t *testing.T) {
session := createSession(t)
defer session.Close()
keyspaceMetadata, err := getKeyspaceMetadata(session, "gocql_test")
if err != nil {
t.Fatalf("failed to query the keyspace metadata with err: %v", err)
}
if keyspaceMetadata == nil {
t.Fatal("failed to query the keyspace metadata, nil returned")
}
if keyspaceMetadata.Name != "gocql_test" {
t.Errorf("Expected keyspace name to be 'gocql' but was '%s'", keyspaceMetadata.Name)
}
if keyspaceMetadata.StrategyClass != "org.apache.cassandra.locator.SimpleStrategy" {
t.Errorf("Expected replication strategy class to be 'org.apache.cassandra.locator.SimpleStrategy' but was '%s'", keyspaceMetadata.StrategyClass)
}
if keyspaceMetadata.StrategyOptions == nil {
t.Error("Expected replication strategy options map but was nil")
}
rfStr, ok := keyspaceMetadata.StrategyOptions["replication_factor"]
if !ok {
t.Fatalf("Expected strategy option 'replication_factor' but was not found in %v", keyspaceMetadata.StrategyOptions)
}
rfInt, err := strconv.Atoi(rfStr.(string))
if err != nil {
t.Fatalf("Error converting string to int with err: %v", err)
}
if rfInt != *flagRF {
t.Errorf("Expected replication factor to be %d but was %d", *flagRF, rfInt)
}
}
// Integration test of just querying for data from the system.schema_keyspace table where the keyspace DOES NOT exist.
func TestGetKeyspaceMetadataFails(t *testing.T) {
session := createSession(t)
defer session.Close()
_, err := getKeyspaceMetadata(session, "gocql_keyspace_does_not_exist")
if err != ErrKeyspaceDoesNotExist || err == nil {
t.Fatalf("Expected error of type ErrKeySpaceDoesNotExist. Instead, error was %v", err)
}
}
// Integration test of just querying for data from the system.schema_columnfamilies table
func TestGetTableMetadata(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.test_table_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
tables, err := getTableMetadata(session, "gocql_test")
if err != nil {
t.Fatalf("failed to query the table metadata with err: %v", err)
}
if tables == nil {
t.Fatal("failed to query the table metadata, nil returned")
}
var testTable *TableMetadata
// verify all tables have minimum expected data
for i := range tables {
table := &tables[i]
if table.Name == "" {
t.Errorf("Expected table name to be set, but it was empty: index=%d metadata=%+v", i, table)
}
if table.Keyspace != "gocql_test" {
t.Errorf("Expected keyspace for '%s' table metadata to be 'gocql_test' but was '%s'", table.Name, table.Keyspace)
}
if session.cfg.ProtoVersion < 4 {
// TODO(zariel): there has to be a better way to detect what metadata version
// we are in, and a better way to structure the code so that it is abstracted away
// from us here
if table.KeyValidator == "" {
t.Errorf("Expected key validator to be set for table %s", table.Name)
}
if table.Comparator == "" {
t.Errorf("Expected comparator to be set for table %s", table.Name)
}
if table.DefaultValidator == "" {
t.Errorf("Expected default validator to be set for table %s", table.Name)
}
}
// these fields are not set until the metadata is compiled
if table.PartitionKey != nil {
t.Errorf("Did not expect partition key for table %s", table.Name)
}
if table.ClusteringColumns != nil {
t.Errorf("Did not expect clustering columns for table %s", table.Name)
}
if table.Columns != nil {
t.Errorf("Did not expect columns for table %s", table.Name)
}
// for the next part of the test after this loop, find the metadata for the test table
if table.Name == "test_table_metadata" {
testTable = table
}
}
// verify actual values on the test tables
if testTable == nil {
t.Fatal("Expected table metadata for name 'test_table_metadata'")
}
if session.cfg.ProtoVersion == protoVersion1 {
if testTable.KeyValidator != "org.apache.cassandra.db.marshal.Int32Type" {
t.Errorf("Expected test_table_metadata key validator to be 'org.apache.cassandra.db.marshal.Int32Type' but was '%s'", testTable.KeyValidator)
}
if testTable.Comparator != "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type)" {
t.Errorf("Expected test_table_metadata key validator to be 'org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type)' but was '%s'", testTable.Comparator)
}
if testTable.DefaultValidator != "org.apache.cassandra.db.marshal.BytesType" {
t.Errorf("Expected test_table_metadata key validator to be 'org.apache.cassandra.db.marshal.BytesType' but was '%s'", testTable.DefaultValidator)
}
expectedKeyAliases := []string{"first_id"}
if !reflect.DeepEqual(testTable.KeyAliases, expectedKeyAliases) {
t.Errorf("Expected key aliases %v but was %v", expectedKeyAliases, testTable.KeyAliases)
}
expectedColumnAliases := []string{"second_id"}
if !reflect.DeepEqual(testTable.ColumnAliases, expectedColumnAliases) {
t.Errorf("Expected key aliases %v but was %v", expectedColumnAliases, testTable.ColumnAliases)
}
}
if testTable.ValueAlias != "" {
t.Errorf("Expected value alias '' but was '%s'", testTable.ValueAlias)
}
}
// Integration test of just querying for data from the system.schema_columns table
func TestGetColumnMetadata(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.test_column_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
if err := session.Query("CREATE INDEX index_column_metadata ON test_column_metadata ( third_id )").Exec(); err != nil {
t.Fatalf("failed to create index with err: %v", err)
}
columns, err := getColumnMetadata(session, "gocql_test")
if err != nil {
t.Fatalf("failed to query column metadata with err: %v", err)
}
if columns == nil {
t.Fatal("failed to query column metadata, nil returned")
}
testColumns := map[string]*ColumnMetadata{}
// verify actual values on the test columns
for i := range columns {
column := &columns[i]
if column.Name == "" {
t.Errorf("Expected column name to be set, but it was empty: index=%d metadata=%+v", i, column)
}
if column.Table == "" {
t.Errorf("Expected column %s table name to be set, but it was empty", column.Name)
}
if column.Keyspace != "gocql_test" {
t.Errorf("Expected column %s keyspace name to be 'gocql_test', but it was '%s'", column.Name, column.Keyspace)
}
if column.Kind == ColumnUnkownKind {
t.Errorf("Expected column %s kind to be set, but it was empty", column.Name)
}
if session.cfg.ProtoVersion == 1 && column.Kind != ColumnRegular {
t.Errorf("Expected column %s kind to be set to 'regular' for proto V1 but it was '%s'", column.Name, column.Kind)
}
if column.Validator == "" {
t.Errorf("Expected column %s validator to be set, but it was empty", column.Name)
}
// find the test table columns for the next step after this loop
if column.Table == "test_column_metadata" {
testColumns[column.Name] = column
}
}
if session.cfg.ProtoVersion == 1 {
// V1 proto only returns "regular columns"
if len(testColumns) != 1 {
t.Errorf("Expected 1 test columns but there were %d", len(testColumns))
}
thirdID, found := testColumns["third_id"]
if !found {
t.Fatalf("Expected to find column 'third_id' metadata but there was only %v", testColumns)
}
if thirdID.Kind != ColumnRegular {
t.Errorf("Expected %s column kind to be '%s' but it was '%s'", thirdID.Name, ColumnRegular, thirdID.Kind)
}
if thirdID.Index.Name != "index_column_metadata" {
t.Errorf("Expected %s column index name to be 'index_column_metadata' but it was '%s'", thirdID.Name, thirdID.Index.Name)
}
} else {
if len(testColumns) != 3 {
t.Errorf("Expected 3 test columns but there were %d", len(testColumns))
}
firstID, found := testColumns["first_id"]
if !found {
t.Fatalf("Expected to find column 'first_id' metadata but there was only %v", testColumns)
}
secondID, found := testColumns["second_id"]
if !found {
t.Fatalf("Expected to find column 'second_id' metadata but there was only %v", testColumns)
}
thirdID, found := testColumns["third_id"]
if !found {
t.Fatalf("Expected to find column 'third_id' metadata but there was only %v", testColumns)
}
if firstID.Kind != ColumnPartitionKey {
t.Errorf("Expected %s column kind to be '%s' but it was '%s'", firstID.Name, ColumnPartitionKey, firstID.Kind)
}
if secondID.Kind != ColumnClusteringKey {
t.Errorf("Expected %s column kind to be '%s' but it was '%s'", secondID.Name, ColumnClusteringKey, secondID.Kind)
}
if thirdID.Kind != ColumnRegular {
t.Errorf("Expected %s column kind to be '%s' but it was '%s'", thirdID.Name, ColumnRegular, thirdID.Kind)
}
if !session.useSystemSchema && thirdID.Index.Name != "index_column_metadata" {
// TODO(zariel): update metadata to scan index from system_schema
t.Errorf("Expected %s column index name to be 'index_column_metadata' but it was '%s'", thirdID.Name, thirdID.Index.Name)
}
}
}
// Integration test of querying and composition the keyspace metadata
func TestKeyspaceMetadata(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.test_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
if err := session.Query("CREATE INDEX index_metadata ON test_metadata ( third_id )").Exec(); err != nil {
t.Fatalf("failed to create index with err: %v", err)
}
keyspaceMetadata, err := session.KeyspaceMetadata("gocql_test")
if err != nil {
t.Fatalf("failed to query keyspace metadata with err: %v", err)
}
if keyspaceMetadata == nil {
t.Fatal("expected the keyspace metadata to not be nil, but it was nil")
}
if keyspaceMetadata.Name != session.cfg.Keyspace {
t.Fatalf("Expected the keyspace name to be %s but was %s", session.cfg.Keyspace, keyspaceMetadata.Name)
}
if len(keyspaceMetadata.Tables) == 0 {
t.Errorf("Expected tables but there were none")
}
tableMetadata, found := keyspaceMetadata.Tables["test_metadata"]
if !found {
t.Fatalf("failed to find the test_metadata table metadata")
}
if len(tableMetadata.PartitionKey) != 1 {
t.Errorf("expected partition key length of 1, but was %d", len(tableMetadata.PartitionKey))
}
for i, column := range tableMetadata.PartitionKey {
if column == nil {
t.Errorf("partition key column metadata at index %d was nil", i)
}
}
if tableMetadata.PartitionKey[0].Name != "first_id" {
t.Errorf("Expected the first partition key column to be 'first_id' but was '%s'", tableMetadata.PartitionKey[0].Name)
}
if len(tableMetadata.ClusteringColumns) != 1 {
t.Fatalf("expected clustering columns length of 1, but was %d", len(tableMetadata.ClusteringColumns))
}
for i, column := range tableMetadata.ClusteringColumns {
if column == nil {
t.Fatalf("clustering column metadata at index %d was nil", i)
}
}
if tableMetadata.ClusteringColumns[0].Name != "second_id" {
t.Errorf("Expected the first clustering column to be 'second_id' but was '%s'", tableMetadata.ClusteringColumns[0].Name)
}
thirdColumn, found := tableMetadata.Columns["third_id"]
if !found {
t.Fatalf("Expected a column definition for 'third_id'")
}
if !session.useSystemSchema && thirdColumn.Index.Name != "index_metadata" {
// TODO(zariel): scan index info from system_schema
t.Errorf("Expected column index named 'index_metadata' but was '%s'", thirdColumn.Index.Name)
}
}
// Integration test of the routing key calculation
func TestRoutingKey(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.test_single_routing_key (first_id int, second_id int, PRIMARY KEY (first_id, second_id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
if err := createTable(session, "CREATE TABLE gocql_test.test_composite_routing_key (first_id int, second_id int, PRIMARY KEY ((first_id, second_id)))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
routingKeyInfo, err := session.routingKeyInfo(context.Background(), "SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?")
if err != nil {
t.Fatalf("failed to get routing key info due to error: %v", err)
}
if routingKeyInfo == nil {
t.Fatal("Expected routing key info, but was nil")
}
if len(routingKeyInfo.indexes) != 1 {
t.Fatalf("Expected routing key indexes length to be 1 but was %d", len(routingKeyInfo.indexes))
}
if routingKeyInfo.indexes[0] != 1 {
t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0])
}
if len(routingKeyInfo.types) != 1 {
t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types))
}
if routingKeyInfo.types[0] == nil {
t.Fatal("Expected routing key types[0] to be non-nil")
}
if routingKeyInfo.types[0].Type() != TypeInt {
t.Fatalf("Expected routing key types[0].Type to be %v but was %v", TypeInt, routingKeyInfo.types[0].Type())
}
// verify the cache is working
routingKeyInfo, err = session.routingKeyInfo(context.Background(), "SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?")
if err != nil {
t.Fatalf("failed to get routing key info due to error: %v", err)
}
if len(routingKeyInfo.indexes) != 1 {
t.Fatalf("Expected routing key indexes length to be 1 but was %d", len(routingKeyInfo.indexes))
}
if routingKeyInfo.indexes[0] != 1 {
t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0])
}
if len(routingKeyInfo.types) != 1 {
t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types))
}
if routingKeyInfo.types[0] == nil {
t.Fatal("Expected routing key types[0] to be non-nil")
}
if routingKeyInfo.types[0].Type() != TypeInt {
t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[0].Type())
}
cacheSize := session.routingKeyInfoCache.lru.Len()
if cacheSize != 1 {
t.Errorf("Expected cache size to be 1 but was %d", cacheSize)
}
query := session.Query("SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?", 1, 2)
routingKey, err := query.GetRoutingKey()
if err != nil {
t.Fatalf("Failed to get routing key due to error: %v", err)
}
expectedRoutingKey := []byte{0, 0, 0, 2}
if !reflect.DeepEqual(expectedRoutingKey, routingKey) {
t.Errorf("Expected routing key %v but was %v", expectedRoutingKey, routingKey)
}
routingKeyInfo, err = session.routingKeyInfo(context.Background(), "SELECT * FROM test_composite_routing_key WHERE second_id=? AND first_id=?")
if err != nil {
t.Fatalf("failed to get routing key info due to error: %v", err)
}
if routingKeyInfo == nil {
t.Fatal("Expected routing key info, but was nil")
}
if len(routingKeyInfo.indexes) != 2 {
t.Fatalf("Expected routing key indexes length to be 2 but was %d", len(routingKeyInfo.indexes))
}
if routingKeyInfo.indexes[0] != 1 {
t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0])
}
if routingKeyInfo.indexes[1] != 0 {
t.Errorf("Expected routing key index[1] to be 0 but was %d", routingKeyInfo.indexes[1])
}
if len(routingKeyInfo.types) != 2 {
t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types))
}
if routingKeyInfo.types[0] == nil {
t.Fatal("Expected routing key types[0] to be non-nil")
}
if routingKeyInfo.types[0].Type() != TypeInt {
t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[0].Type())
}
if routingKeyInfo.types[1] == nil {
t.Fatal("Expected routing key types[1] to be non-nil")
}
if routingKeyInfo.types[1].Type() != TypeInt {
t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[1].Type())
}
query = session.Query("SELECT * FROM test_composite_routing_key WHERE second_id=? AND first_id=?", 1, 2)
routingKey, err = query.GetRoutingKey()
if err != nil {
t.Fatalf("Failed to get routing key due to error: %v", err)
}
expectedRoutingKey = []byte{0, 4, 0, 0, 0, 2, 0, 0, 4, 0, 0, 0, 1, 0}
if !reflect.DeepEqual(expectedRoutingKey, routingKey) {
t.Errorf("Expected routing key %v but was %v", expectedRoutingKey, routingKey)
}
// verify the cache is working
cacheSize = session.routingKeyInfoCache.lru.Len()
if cacheSize != 2 {
t.Errorf("Expected cache size to be 2 but was %d", cacheSize)
}
}
// Integration test of the token-aware policy-based connection pool
func TestTokenAwareConnPool(t *testing.T) {
cluster := createCluster()
cluster.PoolConfig.HostSelectionPolicy = TokenAwareHostPolicy(RoundRobinHostPolicy())
// force metadata query to page
cluster.PageSize = 1
session := createSessionFromCluster(cluster, t)
defer session.Close()
expectedPoolSize := cluster.NumConns * len(session.ring.allHosts())
// wait for pool to fill
for i := 0; i < 10; i++ {
if session.pool.Size() == expectedPoolSize {
break
}
time.Sleep(100 * time.Millisecond)
}
if expectedPoolSize != session.pool.Size() {
t.Errorf("Expected pool size %d but was %d", expectedPoolSize, session.pool.Size())
}
// add another cf so there are two pages when fetching table metadata from our keyspace
if err := createTable(session, "CREATE TABLE gocql_test.test_token_aware_other_cf (id int, data text, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create test_token_aware table with err: %v", err)
}
if err := createTable(session, "CREATE TABLE gocql_test.test_token_aware (id int, data text, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create test_token_aware table with err: %v", err)
}
query := session.Query("INSERT INTO test_token_aware (id, data) VALUES (?,?)", 42, "8 * 6 =")
if err := query.Exec(); err != nil {
t.Fatalf("failed to insert with err: %v", err)
}
query = session.Query("SELECT data FROM test_token_aware where id = ?", 42).Consistency(One)
var data string
if err := query.Scan(&data); err != nil {
t.Error(err)
}
// TODO add verification that the query went to the correct host
}
func TestNegativeStream(t *testing.T) {
session := createSession(t)
defer session.Close()
conn := getRandomConn(t, session)
const stream = -50
writer := frameWriterFunc(func(f *framer, streamID int) error {
f.writeHeader(0, opOptions, stream)
return f.finishWrite()
})
frame, err := conn.exec(context.Background(), writer, nil)
if err == nil {
t.Fatalf("expected to get an error on stream %d", stream)
} else if frame != nil {
t.Fatalf("expected to get nil frame got %+v", frame)
}
}
func TestManualQueryPaging(t *testing.T) {
const rowsToInsert = 5
session := createSession(t)
defer session.Close()
if err := createTable(session, "CREATE TABLE gocql_test.testManualPaging (id int, count int, PRIMARY KEY (id))"); err != nil {
t.Fatal(err)
}
for i := 0; i < rowsToInsert; i++ {
err := session.Query("INSERT INTO testManualPaging(id, count) VALUES(?, ?)", i, i*i).Exec()
if err != nil {
t.Fatal(err)
}
}
// disable auto paging, 1 page per iteration
query := session.Query("SELECT id, count FROM testManualPaging").PageState(nil).PageSize(2)
var id, count, fetched int
iter := query.Iter()
// NOTE: this isnt very indicative of how it should be used, the idea is that
// the page state is returned to some client who will send it back to manually
// page through the results.
for {
for iter.Scan(&id, &count) {
if count != (id * id) {
t.Fatalf("got wrong value from iteration: got %d expected %d", count, id*id)
}
fetched++
}
if len(iter.PageState()) > 0 {
// more pages
iter = query.PageState(iter.PageState()).Iter()
} else {
break
}
}
if err := iter.Close(); err != nil {
t.Fatal(err)
}
if fetched != rowsToInsert {
t.Fatalf("expected to fetch %d rows got %d", rowsToInsert, fetched)
}
}
func TestLexicalUUIDType(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.test_lexical_uuid (
key varchar,
column1 'org.apache.cassandra.db.marshal.LexicalUUIDType',
value int,
PRIMARY KEY (key, column1)
)`); err != nil {
t.Fatal("create:", err)
}
key := TimeUUID().String()
column1 := TimeUUID()
err := session.Query("INSERT INTO test_lexical_uuid(key, column1, value) VALUES(?, ?, ?)", key, column1, 55).Exec()
if err != nil {
t.Fatal(err)
}
var gotUUID UUID
if err := session.Query("SELECT column1 from test_lexical_uuid where key = ? AND column1 = ?", key, column1).Scan(&gotUUID); err != nil {
t.Fatal(err)
}
if gotUUID != column1 {
t.Errorf("got %s, expected %s", gotUUID, column1)
}
}
// Issue 475
func TestSessionBindRoutingKey(t *testing.T) {
cluster := createCluster()
cluster.PoolConfig.HostSelectionPolicy = TokenAwareHostPolicy(RoundRobinHostPolicy())
session := createSessionFromCluster(cluster, t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.test_bind_routing_key (
key varchar,
value int,
PRIMARY KEY (key)
)`); err != nil {
t.Fatal(err)
}
const (
key = "routing-key"
value = 5
)
fn := func(info *QueryInfo) ([]interface{}, error) {
return []interface{}{key, value}, nil
}
q := session.Bind("INSERT INTO test_bind_routing_key(key, value) VALUES(?, ?)", fn)
if err := q.Exec(); err != nil {
t.Fatal(err)
}
}
func TestJSONSupport(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion < 4 {
t.Skip("skipping JSON support on proto < 4")
}
if err := createTable(session, `CREATE TABLE gocql_test.test_json (
id text PRIMARY KEY,
age int,
state text
)`); err != nil {
t.Fatal(err)
}
err := session.Query("INSERT INTO test_json JSON ?", `{"id": "user123", "age": 42, "state": "TX"}`).Exec()
if err != nil {
t.Fatal(err)
}
var (
id string
age int
state string
)
err = session.Query("SELECT id, age, state FROM test_json WHERE id = ?", "user123").Scan(&id, &age, &state)
if err != nil {
t.Fatal(err)
}
if id != "user123" {
t.Errorf("got id %q expected %q", id, "user123")
}
if age != 42 {
t.Errorf("got age %d expected %d", age, 42)
}
if state != "TX" {
t.Errorf("got state %q expected %q", state, "TX")
}
}
func TestUDF(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion < 4 {
t.Skip("skipping UDF support on proto < 4")
}
const query = `CREATE OR REPLACE FUNCTION uniq(state set<text>, val text)
CALLED ON NULL INPUT RETURNS set<text> LANGUAGE java
AS 'state.add(val); return state;'`
err := session.Query(query).Exec()
if err != nil {
t.Fatal(err)
}
}
func TestDiscoverViaProxy(t *testing.T) {
// This (complicated) test tests that when the driver is given an initial host
// that is infact a proxy it discovers the rest of the ring behind the proxy
// and does not store the proxies address as a host in its connection pool.
// See https://github.com/gocql/gocql/issues/481
proxy, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("unable to create proxy listener: %v", err)
}
var (
wg sync.WaitGroup
mu sync.Mutex
proxyConns []net.Conn
closed bool
)
go func(wg *sync.WaitGroup) {
cassandraAddr := JoinHostPort(clusterHosts[0], 9042)
cassandra := func() (net.Conn, error) {
return net.Dial("tcp", cassandraAddr)
}
proxyFn := func(wg *sync.WaitGroup, from, to net.Conn) {
defer wg.Done()
_, err := io.Copy(to, from)
if err != nil {
mu.Lock()
if !closed {
t.Error(err)
}
mu.Unlock()
}
}
// handle dials cassandra and then proxies requests and reponsess. It waits
// for both the read and write side of the TCP connection to close before
// returning.
handle := func(conn net.Conn) error {
defer conn.Close()
cass, err := cassandra()
if err != nil {
return err
}
mu.Lock()
proxyConns = append(proxyConns, cass)
mu.Unlock()
defer cass.Close()
var wg sync.WaitGroup
wg.Add(1)
go proxyFn(&wg, conn, cass)
wg.Add(1)
go proxyFn(&wg, cass, conn)
wg.Wait()
return nil
}
for {
// proxy just accepts connections and then proxies them to cassandra,
// it runs until it is closed.
conn, err := proxy.Accept()
if err != nil {
mu.Lock()
if !closed {
t.Error(err)
}
mu.Unlock()
return
}
mu.Lock()
proxyConns = append(proxyConns, conn)
mu.Unlock()
wg.Add(1)
go func(conn net.Conn) {
defer wg.Done()
if err := handle(conn); err != nil {
t.Error(err)
return
}
}(conn)
}
}(&wg)
defer wg.Wait()
proxyAddr := proxy.Addr().String()
cluster := createCluster()
cluster.NumConns = 1
// initial host is the proxy address
cluster.Hosts = []string{proxyAddr}
session := createSessionFromCluster(cluster, t)
defer session.Close()
if session.hostSource.localHost.BroadcastAddress() == nil {
t.Skip("Target cluster does not have broadcast_address in system.local.")
goto close
}
// we shouldnt need this but to be safe
time.Sleep(1 * time.Second)
session.pool.mu.RLock()
for _, host := range clusterHosts {
if _, ok := session.pool.hostConnPools[host]; !ok {
t.Errorf("missing host in pool after discovery: %q", host)
}
}
session.pool.mu.RUnlock()
close:
mu.Lock()
closed = true
if err := proxy.Close(); err != nil {
t.Log(err)
}
for _, conn := range proxyConns {
if err := conn.Close(); err != nil {
t.Log(err)
}
}
mu.Unlock()
}
func TestUnmarshallNestedTypes(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion < protoVersion3 {
t.Skip("can not have frozen types in cassandra < 2.1.3")
}
if err := createTable(session, `CREATE TABLE gocql_test.test_557 (
id text PRIMARY KEY,
val list<frozen<map<text, text> > >
)`); err != nil {
t.Fatal(err)
}
m := []map[string]string{
{"key1": "val1"},
{"key2": "val2"},
}
const id = "key"
err := session.Query("INSERT INTO test_557(id, val) VALUES(?, ?)", id, m).Exec()
if err != nil {
t.Fatal(err)
}
var data []map[string]string
if err := session.Query("SELECT val FROM test_557 WHERE id = ?", id).Scan(&data); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(data, m) {
t.Fatalf("%+#v != %+#v", data, m)
}
}
func TestSchemaReset(t *testing.T) {
if flagCassVersion.Major == 0 || (flagCassVersion.Before(2, 1, 3)) {
t.Skipf("skipping TestSchemaReset due to CASSANDRA-7910 in Cassandra <2.1.3 version=%v", flagCassVersion)
}
cluster := createCluster()
cluster.NumConns = 1
session := createSessionFromCluster(cluster, t)
defer session.Close()
if err := createTable(session, `CREATE TABLE gocql_test.test_schema_reset (
id text PRIMARY KEY)`); err != nil {
t.Fatal(err)
}
const key = "test"
err := session.Query("INSERT INTO test_schema_reset(id) VALUES(?)", key).Exec()
if err != nil {
t.Fatal(err)
}
var id string
err = session.Query("SELECT * FROM test_schema_reset WHERE id=?", key).Scan(&id)
if err != nil {
t.Fatal(err)
} else if id != key {
t.Fatalf("expected to get id=%q got=%q", key, id)
}
if err := createTable(session, `ALTER TABLE gocql_test.test_schema_reset ADD val text`); err != nil {
t.Fatal(err)
}
const expVal = "test-val"
err = session.Query("INSERT INTO test_schema_reset(id, val) VALUES(?, ?)", key, expVal).Exec()
if err != nil {
t.Fatal(err)
}
var val string
err = session.Query("SELECT * FROM test_schema_reset WHERE id=?", key).Scan(&id, &val)
if err != nil {
t.Fatal(err)
}
if id != key {
t.Errorf("expected to get id=%q got=%q", key, id)
}
if val != expVal {
t.Errorf("expected to get val=%q got=%q", expVal, val)
}
}
func TestCreateSession_DontSwallowError(t *testing.T) {
t.Skip("This test is bad, and the resultant error from cassandra changes between versions")
cluster := createCluster()
cluster.ProtoVersion = 0x100
session, err := cluster.CreateSession()
if err == nil {
session.Close()
t.Fatal("expected to get an error for unsupported protocol")
}
if flagCassVersion.Major < 3 {
// TODO: we should get a distinct error type here which include the underlying
// cassandra error about the protocol version, for now check this here.
if !strings.Contains(err.Error(), "Invalid or unsupported protocol version") {
t.Fatalf(`expcted to get error "unsupported protocol version" got: %q`, err)
}
} else {
if !strings.Contains(err.Error(), "unsupported response version") {
t.Fatalf(`expcted to get error "unsupported response version" got: %q`, err)
}
}
}
func TestControl_DiscoverProtocol(t *testing.T) {
cluster := createCluster()
cluster.ProtoVersion = 0
session, err := cluster.CreateSession()
if err != nil {
t.Fatal(err)
}
defer session.Close()
if session.cfg.ProtoVersion == 0 {
t.Fatal("did not discovery protocol")
}
}
// TestUnsetCol verify unset column will not replace an existing column
func TestUnsetCol(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion < 4 {
t.Skip("Unset Values are not supported in protocol < 4")
}
if err := createTable(session, "CREATE TABLE gocql_test.testUnsetInsert (id int, my_int int, my_text text, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
if err := session.Query("INSERT INTO testUnSetInsert (id,my_int,my_text) VALUES (?,?,?)", 1, 2, "3").Exec(); err != nil {
t.Fatalf("failed to insert with err: %v", err)
}
if err := session.Query("INSERT INTO testUnSetInsert (id,my_int,my_text) VALUES (?,?,?)", 1, UnsetValue, UnsetValue).Exec(); err != nil {
t.Fatalf("failed to insert with err: %v", err)
}
var id, mInt int
var mText string
if err := session.Query("SELECT id, my_int ,my_text FROM testUnsetInsert").Scan(&id, &mInt, &mText); err != nil {
t.Fatalf("failed to select with err: %v", err)
} else if id != 1 || mInt != 2 || mText != "3" {
t.Fatalf("Expected results: 1, 2, \"3\", got %v, %v, %v", id, mInt, mText)
}
}
// TestUnsetColBatch verify unset column will not replace a column in batch
func TestUnsetColBatch(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion < 4 {
t.Skip("Unset Values are not supported in protocol < 4")
}
if err := createTable(session, "CREATE TABLE gocql_test.batchUnsetInsert (id int, my_int int, my_text text, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}
b := session.NewBatch(LoggedBatch)
b.Query("INSERT INTO gocql_test.batchUnsetInsert(id, my_int, my_text) VALUES (?,?,?)", 1, 1, UnsetValue)
b.Query("INSERT INTO gocql_test.batchUnsetInsert(id, my_int, my_text) VALUES (?,?,?)", 1, UnsetValue, "")
b.Query("INSERT INTO gocql_test.batchUnsetInsert(id, my_int, my_text) VALUES (?,?,?)", 2, 2, UnsetValue)
if err := session.ExecuteBatch(b); err != nil {
t.Fatalf("query failed. %v", err)
} else {
if b.Attempts() < 1 {
t.Fatal("expected at least 1 attempt, but got 0")
}
if b.Latency() <= 0 {
t.Fatalf("expected latency to be greater than 0, but got %v instead.", b.Latency())
}
}
var id, mInt, count int
var mText string
if err := session.Query("SELECT count(*) FROM gocql_test.batchUnsetInsert;").Scan(&count); err != nil {
t.Fatalf("Failed to select with err: %v", err)
} else if count != 2 {
t.Fatalf("Expected Batch Insert count 2, got %v", count)
}
if err := session.Query("SELECT id, my_int ,my_text FROM gocql_test.batchUnsetInsert where id=1;").Scan(&id, &mInt, &mText); err != nil {
t.Fatalf("failed to select with err: %v", err)
} else if id != mInt {
t.Fatalf("expected id, my_int to be 1, got %v and %v", id, mInt)
}
}
func TestQuery_NamedValues(t *testing.T) {
session := createSession(t)
defer session.Close()
if session.cfg.ProtoVersion < 3 {
t.Skip("named Values are not supported in protocol < 3")
}
if err := createTable(session, "CREATE TABLE gocql_test.named_query(id int, value text, PRIMARY KEY (id))"); err != nil {
t.Fatal(err)
}
err := session.Query("INSERT INTO gocql_test.named_query(id, value) VALUES(:id, :value)", NamedValue("id", 1), NamedValue("value", "i am a value")).Exec()
if err != nil {
t.Fatal(err)
}
var value string
if err := session.Query("SELECT VALUE from gocql_test.named_query WHERE id = :id", NamedValue("id", 1)).Scan(&value); err != nil {
t.Fatal(err)
}
}
|