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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use std::{iter, mem};
use byteorder::{ByteOrder, NetworkEndian};
use futures::future::{pending, BoxFuture, FutureExt};
use itertools::izip;
use mz_adapter::client::RecordFirstRowStream;
use mz_adapter::session::{
EndTransactionAction, InProgressRows, Portal, PortalState, SessionConfig, TransactionStatus,
};
use mz_adapter::statement_logging::{StatementEndedExecutionReason, StatementExecutionStrategy};
use mz_adapter::{
verify_datum_desc, AdapterError, AdapterNotice, ExecuteContextExtra, ExecuteResponse,
PeekResponseUnary, RowsFuture,
};
use mz_frontegg_auth::Authenticator as FronteggAuthentication;
use mz_ore::cast::CastFrom;
use mz_ore::netio::AsyncReady;
use mz_ore::str::StrExt;
use mz_ore::{assert_none, assert_ok, instrument};
use mz_pgcopy::{CopyCsvFormatParams, CopyFormatParams, CopyTextFormatParams};
use mz_pgwire_common::{ErrorResponse, Format, FrontendMessage, Severity, VERSIONS, VERSION_3};
use mz_repr::{
CatalogItemId, Datum, RelationDesc, RelationType, RowArena, RowIterator, RowRef, ScalarType,
};
use mz_server_core::TlsMode;
use mz_sql::ast::display::AstDisplay;
use mz_sql::ast::{CopyDirection, CopyStatement, FetchDirection, Ident, Raw, Statement};
use mz_sql::parse::StatementParseResult;
use mz_sql::plan::{CopyFormat, ExecuteTimeout, StatementDesc};
use mz_sql::session::metadata::SessionMetadata;
use mz_sql::session::user::INTERNAL_USER_NAMES;
use mz_sql::session::vars::{ConnectionCounter, DropConnection, Var, VarInput, MAX_COPY_FROM_SIZE};
use postgres::error::SqlState;
use tokio::io::{self, AsyncRead, AsyncWrite};
use tokio::select;
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::time::{self};
use tokio_stream::wrappers::UnboundedReceiverStream;
use tracing::{debug, debug_span, warn, Instrument};
use uuid::Uuid;
use crate::codec::FramedConn;
use crate::message::{self, BackendMessage};
/// Reports whether the given stream begins with a pgwire handshake.
///
/// To avoid false negatives, there must be at least eight bytes in `buf`.
pub fn match_handshake(buf: &[u8]) -> bool {
// The pgwire StartupMessage looks like this:
//
// i32 - Length of entire message.
// i32 - Protocol version number.
// [String] - Arbitrary key-value parameters of any length.
//
// Since arbitrary parameters can be included in the StartupMessage, the
// first Int32 is worthless, since the message could have any length.
// Instead, we sniff the protocol version number.
if buf.len() < 8 {
return false;
}
let version = NetworkEndian::read_i32(&buf[4..8]);
VERSIONS.contains(&version)
}
/// Parameters for the [`run`] function.
pub struct RunParams<'a, A> {
/// The TLS mode of the pgwire server.
pub tls_mode: Option<TlsMode>,
/// A client for the adapter.
pub adapter_client: mz_adapter::Client,
/// The connection to the client.
pub conn: &'a mut FramedConn<A>,
/// The universally unique identifier for the connection.
pub conn_uuid: Uuid,
/// The protocol version that the client provided in the startup message.
pub version: i32,
/// The parameters that the client provided in the startup message.
pub params: BTreeMap<String, String>,
/// Frontegg authentication.
pub frontegg: Option<&'a FronteggAuthentication>,
/// Whether this is an internal server that permits access to restricted
/// system resources.
pub internal: bool,
/// Global connection limit and count
pub active_connection_count: Arc<Mutex<ConnectionCounter>>,
/// Helm chart version
pub helm_chart_version: Option<String>,
}
/// Runs a pgwire connection to completion.
///
/// This involves responding to `FrontendMessage::StartupMessage` and all future
/// requests until the client terminates the connection or a fatal error occurs.
///
/// Note that this function returns successfully even upon delivering a fatal
/// error to the client. It only returns `Err` if an unexpected I/O error occurs
/// while communicating with the client, e.g., if the connection is severed in
/// the middle of a request.
#[mz_ore::instrument(level = "debug")]
pub async fn run<'a, A>(
RunParams {
tls_mode,
adapter_client,
conn,
conn_uuid,
version,
mut params,
frontegg,
internal,
active_connection_count,
helm_chart_version,
}: RunParams<'a, A>,
) -> Result<(), io::Error>
where
A: AsyncRead + AsyncWrite + AsyncReady + Send + Sync + Unpin,
{
if version != VERSION_3 {
return conn
.send(ErrorResponse::fatal(
SqlState::SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION,
"server does not support the client's requested protocol version",
))
.await;
}
let user = params.remove("user").unwrap_or_else(String::new);
if internal {
// The internal server can only be used to connect to the internal users.
if !INTERNAL_USER_NAMES.contains(&user) {
let msg = format!("unauthorized login to user '{user}'");
return conn
.send(ErrorResponse::fatal(SqlState::INSUFFICIENT_PRIVILEGE, msg))
.await;
}
} else {
// The external server cannot be used to connect to any system users.
if mz_adapter::catalog::is_reserved_role_name(user.as_str()) {
let msg = format!("unauthorized login to user '{user}'");
return conn
.send(ErrorResponse::fatal(SqlState::INSUFFICIENT_PRIVILEGE, msg))
.await;
}
}
if let Err(err) = conn.inner().ensure_tls_compatibility(&tls_mode) {
return conn.send(err).await;
}
let (mut session, expired) = if let Some(frontegg) = frontegg {
conn.send(BackendMessage::AuthenticationCleartextPassword)
.await?;
conn.flush().await?;
let password = match conn.recv().await? {
Some(FrontendMessage::Password { password }) => password,
_ => {
return conn
.send(ErrorResponse::fatal(
SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
"expected Password message",
))
.await
}
};
let auth_response = frontegg.authenticate(&user, &password).await;
match auth_response {
Ok(mut auth_session) => {
// Create a session based on the auth session.
//
// In particular, it's important that the username come from the
// auth session, as Frontegg may return an email address with
// different casing than the user supplied via the pgwire
// username field. We want to use the Frontegg casing as
// canonical.
let session = adapter_client.new_session(SessionConfig {
conn_id: conn.conn_id().clone(),
uuid: conn_uuid,
user: auth_session.user().into(),
client_ip: conn.peer_addr().clone(),
external_metadata_rx: Some(auth_session.external_metadata_rx()),
helm_chart_version,
});
let expired = async move { auth_session.expired().await };
(session, expired.left_future())
}
Err(err) => {
warn!(?err, "pgwire connection failed authentication");
return conn
.send(ErrorResponse::fatal(
SqlState::INVALID_PASSWORD,
"invalid password",
))
.await;
}
}
} else {
let session = adapter_client.new_session(SessionConfig {
conn_id: conn.conn_id().clone(),
uuid: conn_uuid,
user,
client_ip: conn.peer_addr().clone(),
external_metadata_rx: None,
helm_chart_version,
});
// No frontegg check, so auth session lasts indefinitely.
let auth_session = pending().right_future();
(session, auth_session)
};
for (name, value) in params {
let settings = match name.as_str() {
"options" => match parse_options(&value) {
Ok(opts) => opts,
Err(()) => {
session.add_notice(AdapterNotice::BadStartupSetting {
name,
reason: "could not parse".into(),
});
continue;
}
},
_ => vec![(name, value)],
};
for (key, val) in settings {
const LOCAL: bool = false;
// TODO: Issuing an error here is better than what we did before
// (silently ignore errors on set), but erroring the connection
// might be the better behavior. We maybe need to support more
// options sent by psql and drivers before we can safely do this.
if let Err(err) = session
.vars_mut()
.set(None, &key, VarInput::Flat(&val), LOCAL)
{
session.add_notice(AdapterNotice::BadStartupSetting {
name: key,
reason: err.to_string(),
});
}
}
}
session
.vars_mut()
.end_transaction(EndTransactionAction::Commit);
let _guard = match DropConnection::new_connection(session.user(), active_connection_count) {
Ok(drop_connection) => drop_connection,
Err(e) => {
let e: AdapterError = e.into();
return conn.send(e.into_response(Severity::Fatal)).await;
}
};
// Register session with adapter.
let mut adapter_client = match adapter_client.startup(session).await {
Ok(adapter_client) => adapter_client,
Err(e) => return conn.send(e.into_response(Severity::Fatal)).await,
};
let mut buf = vec![BackendMessage::AuthenticationOk];
for var in adapter_client.session().vars().notify_set() {
buf.push(BackendMessage::ParameterStatus(var.name(), var.value()));
}
buf.push(BackendMessage::BackendKeyData {
conn_id: adapter_client.session().conn_id().unhandled(),
secret_key: adapter_client.session().secret_key(),
});
buf.extend(
adapter_client
.session()
.drain_notices()
.into_iter()
.map(|notice| BackendMessage::ErrorResponse(notice.into_response())),
);
buf.push(BackendMessage::ReadyForQuery(
adapter_client.session().transaction().into(),
));
conn.send_all(buf).await?;
conn.flush().await?;
let machine = StateMachine {
conn,
adapter_client,
txn_needs_commit: false,
};
select! {
r = machine.run() => {
// Errors produced internally (like MAX_REQUEST_SIZE being exceeded) should send an
// error to the client informing them why the connection was closed. We still want to
// return the original error up the stack, though, so we skip error checking during conn
// operations.
if let Err(err) = &r {
let _ = conn
.send(ErrorResponse::fatal(
SqlState::CONNECTION_FAILURE,
err.to_string(),
))
.await;
let _ = conn.flush().await;
}
r
},
_ = expired => {
conn
.send(ErrorResponse::fatal(SqlState::INVALID_AUTHORIZATION_SPECIFICATION, "authentication expired"))
.await?;
conn.flush().await
}
}
}
/// Returns (name, value) session settings pairs from an options value.
///
/// From Postgres, see pg_split_opts in postinit.c and process_postgres_switches
/// in postgres.c.
fn parse_options(value: &str) -> Result<Vec<(String, String)>, ()> {
let opts = split_options(value);
let mut pairs = Vec::with_capacity(opts.len());
let mut seen_prefix = false;
for opt in opts {
if !seen_prefix {
if opt == "-c" {
seen_prefix = true;
} else {
let (key, val) = parse_option(&opt)?;
pairs.push((key.to_owned(), val.to_owned()));
}
} else {
let (key, val) = opt.split_once('=').ok_or(())?;
pairs.push((key.to_owned(), val.to_owned()));
seen_prefix = false;
}
}
Ok(pairs)
}
/// Returns the parsed key and value from option of the form `--key=value`, `-c
/// key=value`, or `-ckey=value`. Keys replace `-` with `_`. Returns an error if
/// there was some other prefix.
fn parse_option(option: &str) -> Result<(&str, &str), ()> {
let (key, value) = option.split_once('=').ok_or(())?;
for prefix in &["-c", "--"] {
if let Some(key) = key.strip_prefix(prefix) {
return Ok((key, value));
}
}
Err(())
}
/// Splits value by any number of spaces except those preceded by `\`.
fn split_options(value: &str) -> Vec<String> {
let mut strs = Vec::new();
// Need to build a string because of the escaping, so we can't simply
// subslice into value, and this isn't called enough to need to make it
// smart so it only builds a string if needed.
let mut current = String::new();
let mut was_slash = false;
for c in value.chars() {
was_slash = match c {
' ' => {
if was_slash {
current.push(' ');
} else if !current.is_empty() {
// To ignore multiple spaces in a row, only push if current
// is not empty.
strs.push(std::mem::take(&mut current));
}
false
}
'\\' => {
if was_slash {
// Two slashes in a row will add a slash and not escape the
// next char.
current.push('\\');
false
} else {
true
}
}
_ => {
current.push(c);
false
}
};
}
// A `\` at the end will be ignored.
if !current.is_empty() {
strs.push(current);
}
strs
}
#[derive(Debug)]
enum State {
Ready,
Drain,
Done,
}
struct StateMachine<'a, A> {
conn: &'a mut FramedConn<A>,
adapter_client: mz_adapter::SessionClient,
txn_needs_commit: bool,
}
enum SendRowsEndedReason {
Success { rows_returned: u64 },
Errored { error: String },
Canceled,
}
const ABORTED_TXN_MSG: &str =
"current transaction is aborted, commands ignored until end of transaction block";
impl<'a, A> StateMachine<'a, A>
where
A: AsyncRead + AsyncWrite + AsyncReady + Send + Sync + Unpin + 'a,
{
// Manually desugar this (don't use `async fn run`) here because a much better
// error message is produced if there are problems with Send or other traits
// somewhere within the Future.
#[allow(clippy::manual_async_fn)]
#[mz_ore::instrument(level = "debug")]
fn run(mut self) -> impl Future<Output = Result<(), io::Error>> + Send + 'a {
async move {
let mut state = State::Ready;
loop {
self.send_pending_notices().await?;
state = match state {
State::Ready => self.advance_ready().await?,
State::Drain => self.advance_drain().await?,
State::Done => return Ok(()),
};
self.adapter_client
.add_idle_in_transaction_session_timeout();
}
}
}
#[instrument(level = "debug")]
async fn advance_ready(&mut self) -> Result<State, io::Error> {
// Handle timeouts first so we don't execute any statements when there's a pending timeout.
let message = select! {
biased;
// `recv_timeout()` is cancel-safe as per it's docs.
Some(timeout) = self.adapter_client.recv_timeout() => {
let err: AdapterError = timeout.into();
let conn_id = self.adapter_client.session().conn_id();
tracing::warn!("session timed out, conn_id {}", conn_id);
// Process the error, doing any state cleanup.
let error_response = err.into_response(Severity::Fatal);
let error_state = self.error(error_response).await;
// Terminate __after__ we do any cleanup.
self.adapter_client.terminate().await;
// We must wait for the client to send a request before we can send the error response.
// Due to the PG wire protocol, we can't send an ErrorResponse unless it is in response
// to a client message.
let _ = self.conn.recv().await?;
return error_state;
},
// `recv()` is cancel-safe as per it's docs.
message = self.conn.recv() => message?,
};
self.adapter_client
.remove_idle_in_transaction_session_timeout();
// NOTE(guswynn): we could consider adding spans to all message types. Currently
// only a few message types seem useful.
let message_name = message.as_ref().map(|m| m.name()).unwrap_or_default();
let next_state = match message {
Some(FrontendMessage::Query { sql }) => {
let query_root_span =
tracing::info_span!(parent: None, "advance_ready", otel.name = message_name);
query_root_span.follows_from(tracing::Span::current());
self.query(sql).instrument(query_root_span).await?
}
Some(FrontendMessage::Parse {
name,
sql,
param_types,
}) => self.parse(name, sql, param_types).await?,
Some(FrontendMessage::Bind {
portal_name,
statement_name,
param_formats,
raw_params,
result_formats,
}) => {
self.bind(
portal_name,
statement_name,
param_formats,
raw_params,
result_formats,
)
.await?
}
Some(FrontendMessage::Execute {
portal_name,
max_rows,
}) => {
let max_rows = match usize::try_from(max_rows) {
Ok(0) | Err(_) => ExecuteCount::All, // If `max_rows < 0`, no limit.
Ok(n) => ExecuteCount::Count(n),
};
let execute_root_span =
tracing::info_span!(parent: None, "advance_ready", otel.name = message_name);
execute_root_span.follows_from(tracing::Span::current());
let state = self
.execute(
portal_name,
max_rows,
portal_exec_message,
None,
ExecuteTimeout::None,
None,
)
.instrument(execute_root_span)
.await?;
// In PostgreSQL, when using the extended query protocol, some statements may
// trigger an eager commit of the current implicit transaction,
// see: <https://git.postgresql.org/gitweb/?p=postgresql.git&a=commitdiff&h=f92944137>.
//
// In Materialize, however, we eagerly commit every statement outside of an explicit
// transaction when using the extended query protocol. This allows us to eliminate
// the possibility of a multiple statement implicit transaction, which in turn
// allows us to apply single-statement optimizations to queries issued in implicit
// transactions in the extended query protocol.
//
// We don't immediately commit here to allow users to page through the portal if
// necessary. Committing the transaction would destroy the portal before the next
// Execute command has a chance to resume it. So we instead mark the transaction
// for commit the next time that `ensure_transaction` is called.
if self.adapter_client.session().transaction().is_implicit() {
self.txn_needs_commit = true;
}
state
}
Some(FrontendMessage::DescribeStatement { name }) => {
self.describe_statement(&name).await?
}
Some(FrontendMessage::DescribePortal { name }) => self.describe_portal(&name).await?,
Some(FrontendMessage::CloseStatement { name }) => self.close_statement(name).await?,
Some(FrontendMessage::ClosePortal { name }) => self.close_portal(name).await?,
Some(FrontendMessage::Flush) => self.flush().await?,
Some(FrontendMessage::Sync) => self.sync().await?,
Some(FrontendMessage::Terminate) => State::Done,
Some(FrontendMessage::CopyData(_))
| Some(FrontendMessage::CopyDone)
| Some(FrontendMessage::CopyFail(_))
| Some(FrontendMessage::Password { .. }) => State::Drain,
None => State::Done,
};
Ok(next_state)
}
async fn advance_drain(&mut self) -> Result<State, io::Error> {
let message = self.conn.recv().await?;
if message.is_some() {
self.adapter_client
.remove_idle_in_transaction_session_timeout();
}
match message {
Some(FrontendMessage::Sync) => self.sync().await,
None => Ok(State::Done),
_ => Ok(State::Drain),
}
}
#[instrument(level = "debug")]
async fn one_query(&mut self, stmt: Statement<Raw>, sql: String) -> Result<State, io::Error> {
// Bind the portal. Note that this does not set the empty string prepared
// statement.
const EMPTY_PORTAL: &str = "";
if let Err(e) = self
.adapter_client
.declare(EMPTY_PORTAL.to_string(), stmt, sql)
.await
{
return self.error(e.into_response(Severity::Error)).await;
}
let stmt_desc = self
.adapter_client
.session()
.get_portal_unverified(EMPTY_PORTAL)
.map(|portal| portal.desc.clone())
.expect("unnamed portal should be present");
if !stmt_desc.param_types.is_empty() {
return self
.error(ErrorResponse::error(
SqlState::UNDEFINED_PARAMETER,
"there is no parameter $1",
))
.await;
}
// Maybe send row description.
if let Some(relation_desc) = &stmt_desc.relation_desc {
if !stmt_desc.is_copy {
let formats = vec![Format::Text; stmt_desc.arity()];
self.send(BackendMessage::RowDescription(
message::encode_row_description(relation_desc, &formats),
))
.await?;
}
}
let result = match self
.adapter_client
.execute(EMPTY_PORTAL.to_string(), self.conn.wait_closed(), None)
.await
{
Ok((response, execute_started)) => {
self.send_pending_notices().await?;
self.send_execute_response(
response,
stmt_desc.relation_desc,
EMPTY_PORTAL.to_string(),
ExecuteCount::All,
portal_exec_message,
None,
ExecuteTimeout::None,
execute_started,
)
.await
}
Err(e) => {
self.send_pending_notices().await?;
self.error(e.into_response(Severity::Error)).await
}
};
// Destroy the portal.
self.adapter_client.session().remove_portal(EMPTY_PORTAL);
result
}
async fn ensure_transaction(&mut self, num_stmts: usize) -> Result<(), io::Error> {
if self.txn_needs_commit {
self.commit_transaction().await?;
}
// start_transaction can't error (but assert that just in case it changes in
// the future.
let res = self.adapter_client.start_transaction(Some(num_stmts));
assert_ok!(res);
Ok(())
}
fn parse_sql<'b>(&self, sql: &'b str) -> Result<Vec<StatementParseResult<'b>>, ErrorResponse> {
match self.adapter_client.parse(sql) {
Ok(result) => result.map_err(|e| {
// Convert our 0-based byte position to pgwire's 1-based character
// position.
let pos = sql[..e.error.pos].chars().count() + 1;
ErrorResponse::error(SqlState::SYNTAX_ERROR, e.error.message).with_position(pos)
}),
Err(msg) => Err(ErrorResponse::error(SqlState::PROGRAM_LIMIT_EXCEEDED, msg)),
}
}
// See "Multiple Statements in a Simple Query" which documents how implicit
// transactions are handled.
// From https://www.postgresql.org/docs/current/protocol-flow.html
#[instrument(level = "debug")]
async fn query(&mut self, sql: String) -> Result<State, io::Error> {
// Parse first before doing any transaction checking.
let stmts = match self.parse_sql(&sql) {
Ok(stmts) => stmts,
Err(err) => {
self.error(err).await?;
return self.ready().await;
}
};
let num_stmts = stmts.len();
// Compare with postgres' backend/tcop/postgres.c exec_simple_query.
for StatementParseResult { ast: stmt, sql } in stmts {
// In an aborted transaction, reject all commands except COMMIT/ROLLBACK.
if self.is_aborted_txn() && !is_txn_exit_stmt(Some(&stmt)) {
self.aborted_txn_error().await?;
break;
}
// Start an implicit transaction if we aren't in any transaction and there's
// more than one statement. This mirrors the `use_implicit_block` variable in
// postgres.
//
// This needs to be done in the loop instead of once at the top because
// a COMMIT/ROLLBACK statement needs to start a new transaction on next
// statement.
self.ensure_transaction(num_stmts).await?;
match self.one_query(stmt, sql.to_string()).await? {
State::Ready => (),
State::Drain => break,
State::Done => return Ok(State::Done),
}
}
// Implicit transactions are closed at the end of a Query message.
{
if self.adapter_client.session().transaction().is_implicit() {
self.commit_transaction().await?;
}
}
if num_stmts == 0 {
self.send(BackendMessage::EmptyQueryResponse).await?;
}
self.ready().await
}
#[instrument(level = "debug")]
async fn parse(
&mut self,
name: String,
sql: String,
param_oids: Vec<u32>,
) -> Result<State, io::Error> {
// Start a transaction if we aren't in one.
self.ensure_transaction(1).await?;
let mut param_types = vec![];
for oid in param_oids {
match mz_pgrepr::Type::from_oid(oid) {
Ok(ty) => match ScalarType::try_from(&ty) {
Ok(ty) => param_types.push(Some(ty)),
Err(err) => {
return self
.error(ErrorResponse::error(
SqlState::INVALID_PARAMETER_VALUE,
err.to_string(),
))
.await
}
},
Err(_) if oid == 0 => param_types.push(None),
Err(e) => {
return self
.error(ErrorResponse::error(
SqlState::PROTOCOL_VIOLATION,
e.to_string(),
))
.await;
}
}
}
let stmts = match self.parse_sql(&sql) {
Ok(stmts) => stmts,
Err(err) => {
return self.error(err).await;
}
};
if stmts.len() > 1 {
return self
.error(ErrorResponse::error(
SqlState::INTERNAL_ERROR,
"cannot insert multiple commands into a prepared statement",
))
.await;
}
let (maybe_stmt, sql) = match stmts.into_iter().next() {
None => (None, ""),
Some(StatementParseResult { ast, sql }) => (Some(ast), sql),
};
if self.is_aborted_txn() && !is_txn_exit_stmt(maybe_stmt.as_ref()) {
return self.aborted_txn_error().await;
}
match self
.adapter_client
.prepare(name, maybe_stmt, sql.to_string(), param_types)
.await
{
Ok(()) => {
self.send(BackendMessage::ParseComplete).await?;
Ok(State::Ready)
}
Err(e) => self.error(e.into_response(Severity::Error)).await,
}
}
/// Commits and clears the current transaction.
#[instrument(level = "debug")]
async fn commit_transaction(&mut self) -> Result<(), io::Error> {
self.end_transaction(EndTransactionAction::Commit).await
}
/// Rollback and clears the current transaction.
#[instrument(level = "debug")]
async fn rollback_transaction(&mut self) -> Result<(), io::Error> {
self.end_transaction(EndTransactionAction::Rollback).await
}
/// End a transaction and report to the user if an error occurred.
#[instrument(level = "debug")]
async fn end_transaction(&mut self, action: EndTransactionAction) -> Result<(), io::Error> {
self.txn_needs_commit = false;
let resp = self.adapter_client.end_transaction(action).await;
if let Err(err) = resp {
self.send(BackendMessage::ErrorResponse(
err.into_response(Severity::Error),
))
.await?;
}
Ok(())
}
#[instrument(level = "debug")]
async fn bind(
&mut self,
portal_name: String,
statement_name: String,
param_formats: Vec<Format>,
raw_params: Vec<Option<Vec<u8>>>,
result_formats: Vec<Format>,
) -> Result<State, io::Error> {
// Start a transaction if we aren't in one.
self.ensure_transaction(1).await?;
let aborted_txn = self.is_aborted_txn();
let stmt = match self
.adapter_client
.get_prepared_statement(&statement_name)
.await
{
Ok(stmt) => stmt,
Err(err) => return self.error(err.into_response(Severity::Error)).await,
};
let param_types = &stmt.desc().param_types;
if param_types.len() != raw_params.len() {
let message = format!(
"bind message supplies {actual} parameters, \
but prepared statement \"{name}\" requires {expected}",
name = statement_name,
actual = raw_params.len(),
expected = param_types.len()
);
return self
.error(ErrorResponse::error(SqlState::PROTOCOL_VIOLATION, message))
.await;
}
let param_formats = match pad_formats(param_formats, raw_params.len()) {
Ok(param_formats) => param_formats,
Err(msg) => {
return self
.error(ErrorResponse::error(SqlState::PROTOCOL_VIOLATION, msg))
.await
}
};
if aborted_txn && !is_txn_exit_stmt(stmt.stmt()) {
return self.aborted_txn_error().await;
}
let buf = RowArena::new();
let mut params = vec![];
for (raw_param, mz_typ, format) in izip!(raw_params, param_types, param_formats) {
let pg_typ = mz_pgrepr::Type::from(mz_typ);
let datum = match raw_param {
None => Datum::Null,
Some(bytes) => match mz_pgrepr::Value::decode(format, &pg_typ, &bytes) {
Ok(param) => param.into_datum(&buf, &pg_typ),
Err(err) => {
let msg = format!("unable to decode parameter: {}", err);
return self
.error(ErrorResponse::error(SqlState::INVALID_PARAMETER_VALUE, msg))
.await;
}
},
};
params.push((datum, mz_typ.clone()))
}
let result_formats = match pad_formats(
result_formats,
stmt.desc()
.relation_desc
.clone()
.map(|desc| desc.typ().column_types.len())
.unwrap_or(0),
) {
Ok(result_formats) => result_formats,
Err(msg) => {
return self
.error(ErrorResponse::error(SqlState::PROTOCOL_VIOLATION, msg))
.await
}
};
// Binary encodings are disabled for list, map, and aclitem types, but this doesn't
// apply to COPY TO statements.
if !stmt.stmt().map_or(false, |stmt| {
matches!(
stmt,
Statement::Copy(CopyStatement {
direction: CopyDirection::To,
..
})
)
}) {
if let Some(desc) = stmt.desc().relation_desc.clone() {
for (format, ty) in result_formats.iter().zip(desc.iter_types()) {
match (format, &ty.scalar_type) {
(Format::Binary, mz_repr::ScalarType::List { .. }) => {
return self
.error(ErrorResponse::error(
SqlState::PROTOCOL_VIOLATION,
"binary encoding of list types is not implemented",
))
.await;
}
(Format::Binary, mz_repr::ScalarType::Map { .. }) => {
return self
.error(ErrorResponse::error(
SqlState::PROTOCOL_VIOLATION,
"binary encoding of map types is not implemented",
))
.await;
}
(Format::Binary, mz_repr::ScalarType::AclItem) => {
return self
.error(ErrorResponse::error(
SqlState::PROTOCOL_VIOLATION,
"binary encoding of aclitem types does not exist",
))
.await;
}
_ => (),
}
}
}
}
let desc = stmt.desc().clone();
let revision = stmt.catalog_revision;
let logging = Arc::clone(stmt.logging());
let stmt = stmt.stmt().cloned();
if let Err(err) = self.adapter_client.session().set_portal(
portal_name,
desc,
stmt,
logging,
params,
result_formats,
revision,
) {
return self.error(err.into_response(Severity::Error)).await;
}
self.send(BackendMessage::BindComplete).await?;
Ok(State::Ready)
}
fn execute(
&mut self,
portal_name: String,
max_rows: ExecuteCount,
get_response: GetResponse,
fetch_portal_name: Option<String>,
timeout: ExecuteTimeout,
outer_ctx_extra: Option<ExecuteContextExtra>,
) -> BoxFuture<'_, Result<State, io::Error>> {
async move {
let aborted_txn = self.is_aborted_txn();
// Check if the portal has been started and can be continued.
let portal = match self
.adapter_client
.session()
.get_portal_unverified_mut(&portal_name)
{
Some(portal) => portal,
None => {
let msg = format!("portal {} does not exist", portal_name.quoted());
if let Some(outer_ctx_extra) = outer_ctx_extra {
self.adapter_client.retire_execute(
outer_ctx_extra,
StatementEndedExecutionReason::Errored { error: msg.clone() },
);
}
return self
.error(ErrorResponse::error(SqlState::INVALID_CURSOR_NAME, msg))
.await;
}
};
// In an aborted transaction, reject all commands except COMMIT/ROLLBACK.
let txn_exit_stmt = is_txn_exit_stmt(portal.stmt.as_deref());
if aborted_txn && !txn_exit_stmt {
if let Some(outer_ctx_extra) = outer_ctx_extra {
self.adapter_client.retire_execute(
outer_ctx_extra,
StatementEndedExecutionReason::Errored {
error: ABORTED_TXN_MSG.to_string(),
},
);
}
return self.aborted_txn_error().await;
}
let row_desc = portal.desc.relation_desc.clone();
match &mut portal.state {
PortalState::NotStarted => {
// Start a transaction if we aren't in one.
self.ensure_transaction(1).await?;
match self
.adapter_client
.execute(
portal_name.clone(),
self.conn.wait_closed(),
outer_ctx_extra,
)
.await
{
Ok((response, execute_started)) => {
self.send_pending_notices().await?;
self.send_execute_response(
response,
row_desc,
portal_name,
max_rows,
get_response,
fetch_portal_name,
timeout,
execute_started,
)
.await
}
Err(e) => {
self.send_pending_notices().await?;
self.error(e.into_response(Severity::Error)).await
}
}
}
PortalState::InProgress(rows) => {
let rows = rows.take().expect("InProgress rows must be populated");
let (result, statement_ended_execution_reason) = match self
.send_rows(
row_desc.expect("portal missing row desc on resumption"),
portal_name,
rows,
max_rows,
get_response,
fetch_portal_name,
timeout,
)
.await
{
Err(e) => {
// This is an error communicating with the connection.
// We consider that to be a cancelation, rather than a query error.
(Err(e), StatementEndedExecutionReason::Canceled)
}
Ok((ok, SendRowsEndedReason::Canceled)) => {
(Ok(ok), StatementEndedExecutionReason::Canceled)
}
// NOTE: For now the `rows_returned` in
// fetches is a bit confusing. We record
// `Some(n)` for the first fetch, where `n` is
// the number of rows returned by the inner
// execute (regardless of how many rows the
// fetch fetched) , and `None` for subsequent fetches.
//
// This arguably makes sense since the rows
// returned measures how much work the compute
// layer had to do to satisfy the query, but
// we should revisit it if/when we start
// logging the inner execute separately.
Ok((ok, SendRowsEndedReason::Success { rows_returned: _ })) => (
Ok(ok),
StatementEndedExecutionReason::Success {
rows_returned: None,
execution_strategy: None,
},
),
Ok((ok, SendRowsEndedReason::Errored { error })) => {
(Ok(ok), StatementEndedExecutionReason::Errored { error })
}
};
if let Some(outer_ctx_extra) = outer_ctx_extra {
self.adapter_client
.retire_execute(outer_ctx_extra, statement_ended_execution_reason);
}
result
}
// FETCH is an awkward command for our current architecture. In Postgres it
// will extract <count> rows from the target portal, cache them, and return
// them to the user as requested. Its command tag is always FETCH <num rows
// extracted>. In Materialize, since we have chosen to not fully support FETCH,
// we must remember the number of rows that were returned. Use this tag to
// remember that information and return it.
PortalState::Completed(Some(tag)) => {
let tag = tag.to_string();
if let Some(outer_ctx_extra) = outer_ctx_extra {
self.adapter_client.retire_execute(
outer_ctx_extra,
StatementEndedExecutionReason::Success {
rows_returned: None,
execution_strategy: None,
},
);
}
self.send(BackendMessage::CommandComplete { tag }).await?;
Ok(State::Ready)
}
PortalState::Completed(None) => {
let error = format!(
"portal {} cannot be run",
Ident::new_unchecked(portal_name).to_ast_string_stable()
);
if let Some(outer_ctx_extra) = outer_ctx_extra {
self.adapter_client.retire_execute(
outer_ctx_extra,
StatementEndedExecutionReason::Errored {
error: error.clone(),
},
);
}
self.error(ErrorResponse::error(
SqlState::OBJECT_NOT_IN_PREREQUISITE_STATE,
error,
))
.await
}
}
}
.instrument(debug_span!("execute"))
.boxed()
}
#[instrument(level = "debug")]
async fn describe_statement(&mut self, name: &str) -> Result<State, io::Error> {
// Start a transaction if we aren't in one.
self.ensure_transaction(1).await?;
let stmt = match self.adapter_client.get_prepared_statement(name).await {
Ok(stmt) => stmt,
Err(err) => return self.error(err.into_response(Severity::Error)).await,
};
// Cloning to avoid a mutable borrow issue because `send` also uses `adapter_client`
let parameter_desc = BackendMessage::ParameterDescription(
stmt.desc()
.param_types
.iter()
.map(mz_pgrepr::Type::from)
.collect(),
);
// Claim that all results will be output in text format, even
// though the true result formats are not yet known. A bit
// weird, but this is the behavior that PostgreSQL specifies.
let formats = vec![Format::Text; stmt.desc().arity()];
let row_desc = describe_rows(stmt.desc(), &formats);
self.send_all([parameter_desc, row_desc]).await?;
Ok(State::Ready)
}
#[instrument(level = "debug")]
async fn describe_portal(&mut self, name: &str) -> Result<State, io::Error> {
// Start a transaction if we aren't in one.
self.ensure_transaction(1).await?;
let session = self.adapter_client.session();
let row_desc = session
.get_portal_unverified(name)
.map(|portal| describe_rows(&portal.desc, &portal.result_formats));
match row_desc {
Some(row_desc) => {
self.send(row_desc).await?;
Ok(State::Ready)
}
None => {
self.error(ErrorResponse::error(
SqlState::INVALID_CURSOR_NAME,
format!("portal {} does not exist", name.quoted()),
))
.await
}
}
}
#[instrument(level = "debug")]
async fn close_statement(&mut self, name: String) -> Result<State, io::Error> {
self.adapter_client
.session()
.remove_prepared_statement(&name);
self.send(BackendMessage::CloseComplete).await?;
Ok(State::Ready)
}
#[instrument(level = "debug")]
async fn close_portal(&mut self, name: String) -> Result<State, io::Error> {
self.adapter_client.session().remove_portal(&name);
self.send(BackendMessage::CloseComplete).await?;
Ok(State::Ready)
}
fn complete_portal(&mut self, name: &str) {
let portal = self
.adapter_client
.session()
.get_portal_unverified_mut(name)
.expect("portal should exist");
portal.state = PortalState::Completed(None);
}
async fn fetch(
&mut self,
name: String,
count: Option<FetchDirection>,
max_rows: ExecuteCount,
fetch_portal_name: Option<String>,
timeout: ExecuteTimeout,
ctx_extra: ExecuteContextExtra,
) -> Result<State, io::Error> {
// Unlike Execute, no count specified in FETCH returns 1 row, and 0 means 0
// instead of All.
let count = count.unwrap_or(FetchDirection::ForwardCount(1));
// Figure out how many rows we should send back by looking at the various
// combinations of the execute and fetch.
//
// In Postgres, Fetch will cache <count> rows from the target portal and
// return those as requested (if, say, an Execute message was sent with a
// max_rows < the Fetch's count). We expect that case to be incredibly rare and
// so have chosen to not support it until users request it. This eases
// implementation difficulty since we don't have to be able to "send" rows to
// a buffer.
//
// TODO(mjibson): Test this somehow? Need to divide up the pgtest files in
// order to have some that are not Postgres compatible.
let count = match (max_rows, count) {
(ExecuteCount::Count(max_rows), FetchDirection::ForwardCount(count)) => {
let count = usize::cast_from(count);
if max_rows < count {
let msg = "Execute with max_rows < a FETCH's count is not supported";
self.adapter_client.retire_execute(
ctx_extra,
StatementEndedExecutionReason::Errored {
error: msg.to_string(),
},
);
return self
.error(ErrorResponse::error(SqlState::FEATURE_NOT_SUPPORTED, msg))
.await;
}
ExecuteCount::Count(count)
}
(ExecuteCount::Count(_), FetchDirection::ForwardAll) => {
let msg = "Execute with max_rows of a FETCH ALL is not supported";
self.adapter_client.retire_execute(
ctx_extra,
StatementEndedExecutionReason::Errored {
error: msg.to_string(),
},
);
return self
.error(ErrorResponse::error(SqlState::FEATURE_NOT_SUPPORTED, msg))
.await;
}
(ExecuteCount::All, FetchDirection::ForwardAll) => ExecuteCount::All,
(ExecuteCount::All, FetchDirection::ForwardCount(count)) => {
ExecuteCount::Count(usize::cast_from(count))
}
};
let cursor_name = name.to_string();
self.execute(
cursor_name,
count,
fetch_message,
fetch_portal_name,
timeout,
Some(ctx_extra),
)
.await
}
async fn flush(&mut self) -> Result<State, io::Error> {
self.conn.flush().await?;
Ok(State::Ready)
}
/// Sends a backend message to the client, after applying a severity filter.
///
/// The message is only sent if its severity is above the severity set
/// in the session, with the default value being NOTICE.
#[instrument(level = "debug")]
async fn send<M>(&mut self, message: M) -> Result<(), io::Error>
where
M: Into<BackendMessage>,
{
let message: BackendMessage = message.into();
let is_error =
matches!(&message, BackendMessage::ErrorResponse(e) if e.severity.is_error());
self.conn.send(message).await?;
// Flush immediately after sending an error response, as some clients
// expect to be able to read the error response before sending a Sync
// message. This is arguably in violation of the protocol specification,
// but the specification is somewhat ambiguous, and easier to match
// PostgreSQL here than to fix all the clients that have this
// expectation.
if is_error {
self.conn.flush().await?;
}
Ok(())
}
#[instrument(level = "debug")]
pub async fn send_all(
&mut self,
messages: impl IntoIterator<Item = BackendMessage>,
) -> Result<(), io::Error> {
for m in messages {
self.send(m).await?;
}
Ok(())
}
#[instrument(level = "debug")]
async fn sync(&mut self) -> Result<State, io::Error> {
// Close the current transaction if we are in an implicit transaction.
if self.adapter_client.session().transaction().is_implicit() {
self.commit_transaction().await?;
}
self.ready().await
}
#[instrument(level = "debug")]
async fn ready(&mut self) -> Result<State, io::Error> {
let txn_state = self.adapter_client.session().transaction().into();
self.send(BackendMessage::ReadyForQuery(txn_state)).await?;
self.flush().await
}
// Converts a RowsFuture to a stream while also checking for connection close.
#[instrument(level = "debug")]
async fn row_future_to_stream<'s, 'p>(
&'s mut self,
parent: &'p tracing::Span,
mut rows: RowsFuture,
) -> Result<UnboundedReceiver<PeekResponseUnary>, io::Error>
where
'p: 's,
{
// select is safe to use because if close finishes, rows is canceled,
// which is the intended behavior.
let span = tracing::debug_span!(parent: parent, "row_future_to_stream");
async move {
loop {
tokio::select! {
err = self.conn.wait_closed() => return Err(err),
rows = &mut rows => {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
tx.send(rows).expect("send must succeed");
return Ok(rx);
}
notice = self.adapter_client.session().recv_notice() => {
self.send(notice.into_response())
.await?;
self.conn.flush().await?;
}
}
}
}
.instrument(span)
.await
}
#[allow(clippy::too_many_arguments)]
#[instrument(level = "debug")]
async fn send_execute_response(
&mut self,
response: ExecuteResponse,
row_desc: Option<RelationDesc>,
portal_name: String,
max_rows: ExecuteCount,
get_response: GetResponse,
fetch_portal_name: Option<String>,
timeout: ExecuteTimeout,
execute_started: Instant,
) -> Result<State, io::Error> {
let mut tag = response.tag();
macro_rules! command_complete {
() => {{
self.send(BackendMessage::CommandComplete {
tag: tag
.take()
.expect("command_complete only called on tag-generating results"),
})
.await?;
Ok(State::Ready)
}};
}
let r = match response {
ExecuteResponse::ClosedCursor => {
self.complete_portal(&portal_name);
command_complete!()
}
ExecuteResponse::DeclaredCursor => {
self.complete_portal(&portal_name);
command_complete!()
}
ExecuteResponse::EmptyQuery => {
self.send(BackendMessage::EmptyQueryResponse).await?;
Ok(State::Ready)
}
ExecuteResponse::Fetch {
name,
count,
timeout,
ctx_extra,
} => {
self.fetch(
name,
count,
max_rows,
Some(portal_name.to_string()),
timeout,
ctx_extra,
)
.await
}
ExecuteResponse::SendingRows {
future: rx,
instance_id,
strategy,
} => {
let row_desc =
row_desc.expect("missing row description for ExecuteResponse::SendingRows");
let span = tracing::debug_span!("sending_rows");
let rows = self.row_future_to_stream(&span, rx).await?;
self.send_rows(
row_desc,
portal_name,
InProgressRows::new(RecordFirstRowStream::new(
Box::new(UnboundedReceiverStream::new(rows)),
execute_started,
&self.adapter_client,
Some(instance_id),
Some(strategy),
)),
max_rows,
get_response,
fetch_portal_name,
timeout,
)
.instrument(span)
.await
.map(|(state, _)| state)
}
ExecuteResponse::SendingRowsImmediate { rows } => {
let row_desc = row_desc
.expect("missing row description for ExecuteResponse::SendingRowsImmediate");
let span = tracing::debug_span!("sending_rows_immediate");
let stream =
futures::stream::once(futures::future::ready(PeekResponseUnary::Rows(rows)));
self.send_rows(
row_desc,
portal_name,
InProgressRows::new(RecordFirstRowStream::new(
Box::new(stream),
execute_started,
&self.adapter_client,
None,
Some(StatementExecutionStrategy::Constant),
)),
max_rows,
get_response,
fetch_portal_name,
timeout,
)
.instrument(span)
.await
.map(|(state, _)| state)
}
ExecuteResponse::SetVariable { name, .. } => {
// This code is somewhat awkwardly structured because we
// can't hold `var` across an await point.
let qn = name.to_string();
let msg = if let Some(var) = self
.adapter_client
.session()
.vars_mut()
.notify_set()
.find(|v| v.name() == qn)
{
Some(BackendMessage::ParameterStatus(var.name(), var.value()))
} else {
None
};
if let Some(msg) = msg {
self.send(msg).await?;
}
command_complete!()
}
ExecuteResponse::Subscribing {
rx,
ctx_extra,
instance_id,
} => {
if fetch_portal_name.is_none() {
let mut msg = ErrorResponse::notice(
SqlState::WARNING,
"streaming SUBSCRIBE rows directly requires a client that does not buffer output",
);
if self.adapter_client.session().vars().application_name() == "psql" {
msg.hint = Some(
"Wrap your SUBSCRIBE statement in `COPY (SUBSCRIBE ...) TO STDOUT`."
.into(),
)
}
self.send(msg).await?;
self.conn.flush().await?;
}
let row_desc =
row_desc.expect("missing row description for ExecuteResponse::Subscribing");
let (result, statement_ended_execution_reason) = match self
.send_rows(
row_desc,
portal_name,
InProgressRows::new(RecordFirstRowStream::new(
Box::new(UnboundedReceiverStream::new(rx)),
execute_started,
&self.adapter_client,
Some(instance_id),
None,
)),
max_rows,
get_response,
fetch_portal_name,
timeout,
)
.await
{
Err(e) => {
// This is an error communicating with the connection.
// We consider that to be a cancelation, rather than a query error.
(Err(e), StatementEndedExecutionReason::Canceled)
}
Ok((ok, SendRowsEndedReason::Canceled)) => {
(Ok(ok), StatementEndedExecutionReason::Canceled)
}
Ok((ok, SendRowsEndedReason::Success { rows_returned })) => (
Ok(ok),
StatementEndedExecutionReason::Success {
rows_returned: Some(rows_returned),
execution_strategy: None,
},
),
Ok((ok, SendRowsEndedReason::Errored { error })) => {
(Ok(ok), StatementEndedExecutionReason::Errored { error })
}
};
self.adapter_client
.retire_execute(ctx_extra, statement_ended_execution_reason);
return result;
}
ExecuteResponse::CopyTo { format, resp } => {
let row_desc =
row_desc.expect("missing row description for ExecuteResponse::CopyTo");
match *resp {
ExecuteResponse::Subscribing {
rx,
ctx_extra,
instance_id,
} => {
let (result, statement_ended_execution_reason) = match self
.copy_rows(
format,
row_desc,
RecordFirstRowStream::new(
Box::new(UnboundedReceiverStream::new(rx)),
execute_started,
&self.adapter_client,
Some(instance_id),
None,
),
)
.await
{
Err(e) => {
// This is an error communicating with the connection.
// We consider that to be a cancelation, rather than a query error.
(Err(e), StatementEndedExecutionReason::Canceled)
}
Ok((state, SendRowsEndedReason::Success { rows_returned })) => (
Ok(state),
StatementEndedExecutionReason::Success {
rows_returned: Some(rows_returned),
execution_strategy: None,
},
),
Ok((state, SendRowsEndedReason::Errored { error })) => {
(Ok(state), StatementEndedExecutionReason::Errored { error })
}
Ok((state, SendRowsEndedReason::Canceled)) => {
(Ok(state), StatementEndedExecutionReason::Canceled)
}
};
self.adapter_client
.retire_execute(ctx_extra, statement_ended_execution_reason);
return result;
}
ExecuteResponse::SendingRows {
future: rows_rx,
instance_id,
strategy,
} => {
let span = tracing::debug_span!("sending_rows");
let rows = self.row_future_to_stream(&span, rows_rx).await?;
// We don't need to finalize execution here;
// it was already done in the
// coordinator. Just extract the state and
// return that.
return self
.copy_rows(
format,
row_desc,
RecordFirstRowStream::new(
Box::new(UnboundedReceiverStream::new(rows)),
execute_started,
&self.adapter_client,
Some(instance_id),
Some(strategy),
),
)
.await
.map(|(state, _)| state);
}
ExecuteResponse::SendingRowsImmediate { rows } => {
let span = tracing::debug_span!("sending_rows_immediate");
let rows = futures::stream::once(futures::future::ready(
PeekResponseUnary::Rows(rows),
));
// We don't need to finalize execution here;
// it was already done in the
// coordinator. Just extract the state and
// return that.
return self
.copy_rows(
format,
row_desc,
RecordFirstRowStream::new(
Box::new(rows),
execute_started,
&self.adapter_client,
None,
Some(StatementExecutionStrategy::Constant),
),
)
.instrument(span)
.await
.map(|(state, _)| state);
}
_ => {
return self
.error(ErrorResponse::error(
SqlState::INTERNAL_ERROR,
"unsupported COPY response type".to_string(),
))
.await;
}
};
}
ExecuteResponse::CopyFrom {
id,
columns,
params,
ctx_extra,
} => {
let row_desc =
row_desc.expect("missing row description for ExecuteResponse::CopyFrom");
self.copy_from(id, columns, params, row_desc, ctx_extra)
.await
}
ExecuteResponse::TransactionCommitted { params }
| ExecuteResponse::TransactionRolledBack { params } => {
let notify_set: mz_ore::collections::HashSet<String> = self
.adapter_client
.session()
.vars()
.notify_set()
.map(|v| v.name().to_string())
.collect();
// Only report on parameters that are in the notify set.
for (name, value) in params
.into_iter()
.filter(|(name, _v)| notify_set.contains(*name))
{
let msg = BackendMessage::ParameterStatus(name, value);
self.send(msg).await?;
}
command_complete!()
}
ExecuteResponse::AlteredDefaultPrivileges
| ExecuteResponse::AlteredObject(..)
| ExecuteResponse::AlteredRole
| ExecuteResponse::AlteredSystemConfiguration
| ExecuteResponse::CreatedCluster { .. }
| ExecuteResponse::CreatedClusterReplica { .. }
| ExecuteResponse::CreatedConnection { .. }
| ExecuteResponse::CreatedDatabase { .. }
| ExecuteResponse::CreatedIndex { .. }
| ExecuteResponse::CreatedIntrospectionSubscribe
| ExecuteResponse::CreatedMaterializedView { .. }
| ExecuteResponse::CreatedContinualTask { .. }
| ExecuteResponse::CreatedRole
| ExecuteResponse::CreatedSchema { .. }
| ExecuteResponse::CreatedSecret { .. }
| ExecuteResponse::CreatedSink { .. }
| ExecuteResponse::CreatedSource { .. }
| ExecuteResponse::CreatedTable { .. }
| ExecuteResponse::CreatedType
| ExecuteResponse::CreatedView { .. }
| ExecuteResponse::CreatedViews { .. }
| ExecuteResponse::CreatedNetworkPolicy
| ExecuteResponse::Comment
| ExecuteResponse::Deallocate { .. }
| ExecuteResponse::Deleted(..)
| ExecuteResponse::DiscardedAll
| ExecuteResponse::DiscardedTemp
| ExecuteResponse::DroppedObject(_)
| ExecuteResponse::DroppedOwned
| ExecuteResponse::GrantedPrivilege
| ExecuteResponse::GrantedRole
| ExecuteResponse::Inserted(..)
| ExecuteResponse::Copied(..)
| ExecuteResponse::Prepare
| ExecuteResponse::Raised
| ExecuteResponse::ReassignOwned
| ExecuteResponse::RevokedPrivilege
| ExecuteResponse::RevokedRole
| ExecuteResponse::StartedTransaction { .. }
| ExecuteResponse::Updated(..)
| ExecuteResponse::ValidatedConnection => {
command_complete!()
}
};
assert_none!(tag, "tag created but not consumed: {:?}", tag);
r
}
#[allow(clippy::too_many_arguments)]
// TODO(guswynn): figure out how to get it to compile without skip_all
#[mz_ore::instrument(level = "debug")]
async fn send_rows(
&mut self,
row_desc: RelationDesc,
portal_name: String,
mut rows: InProgressRows,
max_rows: ExecuteCount,
get_response: GetResponse,
fetch_portal_name: Option<String>,
timeout: ExecuteTimeout,
) -> Result<(State, SendRowsEndedReason), io::Error> {
// If this portal is being executed from a FETCH then we need to use the result
// format type of the outer portal.
let result_format_portal_name: &str = if let Some(ref name) = fetch_portal_name {
name
} else {
&portal_name
};
let result_formats = self
.adapter_client
.session()
.get_portal_unverified(result_format_portal_name)
.expect("valid fetch portal name for send rows")
.result_formats
.clone();
let (mut wait_once, mut deadline) = match timeout {
ExecuteTimeout::None => (false, None),
ExecuteTimeout::Seconds(t) => (
false,
Some(tokio::time::Instant::now() + tokio::time::Duration::from_secs_f64(t)),
),
ExecuteTimeout::WaitOnce => (true, None),
};
self.conn.set_encode_state(
row_desc
.typ()
.column_types
.iter()
.map(|ty| mz_pgrepr::Type::from(&ty.scalar_type))
.zip(result_formats)
.collect(),
);
let mut total_sent_rows = 0;
// want_rows is the maximum number of rows the client wants.
let mut want_rows = match max_rows {
ExecuteCount::All => usize::MAX,
ExecuteCount::Count(count) => count,
};
// Send rows while the client still wants them and there are still rows to send.
loop {
// Fetch next batch of rows, waiting for a possible requested
// timeout or notice.
let batch = if rows.current.is_some() {
FetchResult::Rows(rows.current.take())
} else if want_rows == 0 {
FetchResult::Rows(None)
} else {
let notice_fut = self.adapter_client.session().recv_notice();
tokio::select! {
err = self.conn.wait_closed() => return Err(err),
_ = time::sleep_until(deadline.unwrap_or_else(tokio::time::Instant::now)), if deadline.is_some() => FetchResult::Rows(None),
notice = notice_fut => {
FetchResult::Notice(notice)
}
batch = rows.remaining.recv() => match batch {
None => FetchResult::Rows(None),
Some(PeekResponseUnary::Rows(rows)) => FetchResult::Rows(Some(rows)),
Some(PeekResponseUnary::Error(err)) => FetchResult::Error(err),
Some(PeekResponseUnary::Canceled) => FetchResult::Canceled,
},
}
};
match batch {
FetchResult::Rows(None) => break,
FetchResult::Rows(Some(mut batch_rows)) => {
if let Err(err) = verify_datum_desc(&row_desc, &mut batch_rows) {
let msg = err.to_string();
return self
.error(err.into_response(Severity::Error))
.await
.map(|state| (state, SendRowsEndedReason::Errored { error: msg }));
}
// If wait_once is true: the first time this fn is called it blocks (same as
// deadline == None). The second time this fn is called it should behave the
// same a 0s timeout.
if wait_once && batch_rows.peek().is_some() {
deadline = Some(tokio::time::Instant::now());
wait_once = false;
}
// Send a portion of the rows.
let mut sent_rows = 0;
let messages = (&mut batch_rows)
.map(|row| {
let values = mz_pgrepr::values_from_row(row, row_desc.typ());
BackendMessage::DataRow(values)
})
.inspect(|_| sent_rows += 1)
.take(want_rows);
self.send_all(messages).await?;
total_sent_rows += sent_rows;
want_rows -= sent_rows;
// If we have sent the number of requested rows, put the remainder of the batch
// (if any) back and stop sending.
if want_rows == 0 {
if batch_rows.peek().is_some() {
rows.current = Some(batch_rows);
}
break;
}
self.conn.flush().await?;
}
FetchResult::Notice(notice) => {
self.send(notice.into_response()).await?;
self.conn.flush().await?;
}
FetchResult::Error(text) => {
return self
.error(ErrorResponse::error(SqlState::INTERNAL_ERROR, text.clone()))
.await
.map(|state| (state, SendRowsEndedReason::Errored { error: text }));
}
FetchResult::Canceled => {
return self
.error(ErrorResponse::error(
SqlState::QUERY_CANCELED,
"canceling statement due to user request",
))
.await
.map(|state| (state, SendRowsEndedReason::Canceled));
}
}
}
let portal = self
.adapter_client
.session()
.get_portal_unverified_mut(&portal_name)
.expect("valid portal name for send rows");
// Always return rows back, even if it's empty. This prevents an unclosed
// portal from re-executing after it has been emptied.
portal.state = PortalState::InProgress(Some(rows));
let fetch_portal = fetch_portal_name.map(|name| {
self.adapter_client
.session()
.get_portal_unverified_mut(&name)
.expect("valid fetch portal")
});
let response_message = get_response(max_rows, total_sent_rows, fetch_portal);
self.send(response_message).await?;
Ok((
State::Ready,
SendRowsEndedReason::Success {
rows_returned: u64::cast_from(total_sent_rows),
},
))
}
#[mz_ore::instrument(level = "debug")]
async fn copy_rows(
&mut self,
format: CopyFormat,
row_desc: RelationDesc,
mut stream: RecordFirstRowStream,
) -> Result<(State, SendRowsEndedReason), io::Error> {
let (row_format, encode_format) = match format {
CopyFormat::Text => (
CopyFormatParams::Text(CopyTextFormatParams::default()),
Format::Text,
),
CopyFormat::Binary => (CopyFormatParams::Binary, Format::Binary),
CopyFormat::Csv => (
CopyFormatParams::Csv(CopyCsvFormatParams::default()),
Format::Text,
),
CopyFormat::Parquet => {
let text = "Parquet format is not supported".to_string();
return self
.error(ErrorResponse::error(SqlState::INTERNAL_ERROR, text.clone()))
.await
.map(|state| (state, SendRowsEndedReason::Errored { error: text }));
}
};
let encode_fn = |row: &RowRef, typ: &RelationType, out: &mut Vec<u8>| {
mz_pgcopy::encode_copy_format(&row_format, row, typ, out)
};
let typ = row_desc.typ();
let column_formats = iter::repeat(encode_format)
.take(typ.column_types.len())
.collect();
self.send(BackendMessage::CopyOutResponse {
overall_format: encode_format,
column_formats,
})
.await?;
// In Postgres, binary copy has a header that is followed (in the same
// CopyData) by the first row. In order to replicate their behavior, use a
// common vec that we can extend one time now and then fill up with the encode
// functions.
let mut out = Vec::new();
if let CopyFormat::Binary = format {
// 11-byte signature.
out.extend(b"PGCOPY\n\xFF\r\n\0");
// 32-bit flags field.
out.extend([0, 0, 0, 0]);
// 32-bit header extension length field.
out.extend([0, 0, 0, 0]);
}
let mut count = 0;
loop {
tokio::select! {
e = self.conn.wait_closed() => return Err(e),
batch = stream.recv() => match batch {
None => break,
Some(PeekResponseUnary::Error(text)) => {
return self
.error(ErrorResponse::error(SqlState::INTERNAL_ERROR, text.clone()))
.await
.map(|state| (state, SendRowsEndedReason::Errored { error: text }));
}
Some(PeekResponseUnary::Canceled) => {
return self.error(ErrorResponse::error(
SqlState::QUERY_CANCELED,
"canceling statement due to user request",
))
.await.map(|state| (state, SendRowsEndedReason::Canceled));
}
Some(PeekResponseUnary::Rows(mut rows)) => {
count += rows.count();
while let Some(row) = rows.next() {
encode_fn(row, typ, &mut out)?;
self.send(BackendMessage::CopyData(mem::take(&mut out)))
.await?;
}
}
},
notice = self.adapter_client.session().recv_notice() => {
self.send(notice.into_response())
.await?;
self.conn.flush().await?;
}
}
self.conn.flush().await?;
}
// Send required trailers.
if let CopyFormat::Binary = format {
let trailer: i16 = -1;
out.extend(trailer.to_be_bytes());
self.send(BackendMessage::CopyData(mem::take(&mut out)))
.await?;
}
let tag = format!("COPY {}", count);
self.send(BackendMessage::CopyDone).await?;
self.send(BackendMessage::CommandComplete { tag }).await?;
Ok((
State::Ready,
SendRowsEndedReason::Success {
rows_returned: u64::cast_from(count),
},
))
}
/// Handles the copy-in mode of the postgres protocol from transferring
/// data to the server.
#[instrument(level = "debug")]
async fn copy_from(
&mut self,
id: CatalogItemId,
columns: Vec<usize>,
params: CopyFormatParams<'_>,
row_desc: RelationDesc,
mut ctx_extra: ExecuteContextExtra,
) -> Result<State, io::Error> {
let res = self
.copy_from_inner(id, columns, params, row_desc, &mut ctx_extra)
.await;
match &res {
Ok(State::Done) => {
// The connection closed gracefully without sending us a `CopyDone`,
// causing us to just drop the copy request.
// For the purposes of statement logging, we count this as a cancellation.
self.adapter_client
.retire_execute(ctx_extra, StatementEndedExecutionReason::Canceled);
}
Err(e) => {
self.adapter_client.retire_execute(
ctx_extra,
StatementEndedExecutionReason::Errored {
error: format!("{e}"),
},
);
}
other => {
tracing::warn!(?other, "aborting COPY FROM");
self.adapter_client
.retire_execute(ctx_extra, StatementEndedExecutionReason::Aborted);
}
}
res
}
async fn copy_from_inner(
&mut self,
id: CatalogItemId,
columns: Vec<usize>,
params: CopyFormatParams<'_>,
row_desc: RelationDesc,
ctx_extra: &mut ExecuteContextExtra,
) -> Result<State, io::Error> {
let typ = row_desc.typ();
let column_formats = vec![Format::Text; typ.column_types.len()];
self.send(BackendMessage::CopyInResponse {
overall_format: Format::Text,
column_formats,
})
.await?;
self.conn.flush().await?;
let system_vars = self.adapter_client.get_system_vars().await.ok();
let max_size = system_vars
.as_ref()
.map(|resp| resp.get(MAX_COPY_FROM_SIZE.name()))
.flatten()
.map(|max_size| max_size.parse().ok())
.flatten()
.unwrap_or(usize::MAX);
tracing::debug!("COPY FROM max buffer size: {max_size} bytes");
let mut data = Vec::new();
loop {
let message = self.conn.recv().await?;
match message {
Some(FrontendMessage::CopyData(buf)) => {
// Bail before we OOM.
if (data.len() + buf.len()) > max_size {
return self
.error(ErrorResponse::error(
SqlState::INSUFFICIENT_RESOURCES,
"COPY FROM STDIN too large",
))
.await;
}
data.extend(buf)
}
Some(FrontendMessage::CopyDone) => break,
Some(FrontendMessage::CopyFail(err)) => {
self.adapter_client.retire_execute(
std::mem::take(ctx_extra),
StatementEndedExecutionReason::Canceled,
);
return self
.error(ErrorResponse::error(
SqlState::QUERY_CANCELED,
format!("COPY from stdin failed: {}", err),
))
.await;
}
Some(FrontendMessage::Flush) | Some(FrontendMessage::Sync) => {}
Some(_) => {
let msg = "unexpected message type during COPY from stdin";
self.adapter_client.retire_execute(
std::mem::take(ctx_extra),
StatementEndedExecutionReason::Errored {
error: msg.to_string(),
},
);
return self
.error(ErrorResponse::error(SqlState::PROTOCOL_VIOLATION, msg))
.await;
}
None => {
return Ok(State::Done);
}
}
}
let column_types = typ
.column_types
.iter()
.map(|x| &x.scalar_type)
.map(mz_pgrepr::Type::from)
.collect::<Vec<mz_pgrepr::Type>>();
let rows = match mz_pgcopy::decode_copy_format(&data, &column_types, params) {
Ok(rows) => rows,
Err(e) => {
self.adapter_client.retire_execute(
std::mem::take(ctx_extra),
StatementEndedExecutionReason::Errored {
error: e.to_string(),
},
);
return self
.error(ErrorResponse::error(
SqlState::BAD_COPY_FILE_FORMAT,
format!("{}", e),
))
.await;
}
};
let count = rows.len();
if let Err(e) = self
.adapter_client
.insert_rows(id, columns, rows, std::mem::take(ctx_extra))
.await
{
self.adapter_client.retire_execute(
std::mem::take(ctx_extra),
StatementEndedExecutionReason::Errored {
error: e.to_string(),
},
);
return self.error(e.into_response(Severity::Error)).await;
}
let tag = format!("COPY {}", count);
self.send(BackendMessage::CommandComplete { tag }).await?;
Ok(State::Ready)
}
#[instrument(level = "debug")]
async fn send_pending_notices(&mut self) -> Result<(), io::Error> {
let notices = self
.adapter_client
.session()
.drain_notices()
.into_iter()
.map(|notice| BackendMessage::ErrorResponse(notice.into_response()));
self.send_all(notices).await?;
Ok(())
}
#[instrument(level = "debug")]
async fn error(&mut self, err: ErrorResponse) -> Result<State, io::Error> {
assert!(err.severity.is_error());
debug!(
"cid={} error code={}",
self.adapter_client.session().conn_id(),
err.code.code()
);
let is_fatal = err.severity.is_fatal();
self.send(BackendMessage::ErrorResponse(err)).await?;
let txn = self.adapter_client.session().transaction();
match txn {
// Error can be called from describe and parse and so might not be in an active
// transaction.
TransactionStatus::Default | TransactionStatus::Failed(_) => {}
// In Started (i.e., a single statement), cleanup ourselves.
TransactionStatus::Started(_) => {
self.rollback_transaction().await?;
}
// Implicit transactions also clear themselves.
TransactionStatus::InTransactionImplicit(_) => {
self.rollback_transaction().await?;
}
// Explicit transactions move to failed.
TransactionStatus::InTransaction(_) => {
self.adapter_client.fail_transaction();
}
};
if is_fatal {
Ok(State::Done)
} else {
Ok(State::Drain)
}
}
#[instrument(level = "debug")]
async fn aborted_txn_error(&mut self) -> Result<State, io::Error> {
self.send(BackendMessage::ErrorResponse(ErrorResponse::error(
SqlState::IN_FAILED_SQL_TRANSACTION,
ABORTED_TXN_MSG,
)))
.await?;
Ok(State::Drain)
}
fn is_aborted_txn(&mut self) -> bool {
matches!(
self.adapter_client.session().transaction(),
TransactionStatus::Failed(_)
)
}
}
fn pad_formats(formats: Vec<Format>, n: usize) -> Result<Vec<Format>, String> {
match (formats.len(), n) {
(0, e) => Ok(vec![Format::Text; e]),
(1, e) => Ok(iter::repeat(formats[0]).take(e).collect()),
(a, e) if a == e => Ok(formats),
(a, e) => Err(format!(
"expected {} field format specifiers, but got {}",
e, a
)),
}
}
fn describe_rows(stmt_desc: &StatementDesc, formats: &[Format]) -> BackendMessage {
match &stmt_desc.relation_desc {
Some(desc) if !stmt_desc.is_copy => {
BackendMessage::RowDescription(message::encode_row_description(desc, formats))
}
_ => BackendMessage::NoData,
}
}
type GetResponse = fn(
max_rows: ExecuteCount,
total_sent_rows: usize,
fetch_portal: Option<&mut Portal>,
) -> BackendMessage;
// A GetResponse used by send_rows during execute messages on portals or for
// simple query messages.
fn portal_exec_message(
max_rows: ExecuteCount,
total_sent_rows: usize,
_fetch_portal: Option<&mut Portal>,
) -> BackendMessage {
// If max_rows is not specified, we will always send back a CommandComplete. If
// max_rows is specified, we only send CommandComplete if there were more rows
// requested than were remaining. That is, if max_rows == number of rows that
// were remaining before sending (not that are remaining after sending), then
// we still send a PortalSuspended. The number of remaining rows after the rows
// have been sent doesn't matter. This matches postgres.
match max_rows {
ExecuteCount::Count(max_rows) if max_rows <= total_sent_rows => {
BackendMessage::PortalSuspended
}
_ => BackendMessage::CommandComplete {
tag: format!("SELECT {}", total_sent_rows),
},
}
}
// A GetResponse used by send_rows during FETCH queries.
fn fetch_message(
_max_rows: ExecuteCount,
total_sent_rows: usize,
fetch_portal: Option<&mut Portal>,
) -> BackendMessage {
let tag = format!("FETCH {}", total_sent_rows);
if let Some(portal) = fetch_portal {
portal.state = PortalState::Completed(Some(tag.clone()));
}
BackendMessage::CommandComplete { tag }
}
#[derive(Debug, Copy, Clone)]
enum ExecuteCount {
All,
Count(usize),
}
// See postgres' backend/tcop/postgres.c IsTransactionExitStmt.
fn is_txn_exit_stmt(stmt: Option<&Statement<Raw>>) -> bool {
match stmt {
// Add PREPARE to this if we ever support it.
Some(stmt) => matches!(stmt, Statement::Commit(_) | Statement::Rollback(_)),
None => false,
}
}
#[derive(Debug)]
enum FetchResult {
Rows(Option<Box<dyn RowIterator + Send + Sync>>),
Canceled,
Error(String),
Notice(AdapterNotice),
}
#[cfg(test)]
mod test {
use super::*;
#[mz_ore::test]
fn test_parse_options() {
struct TestCase {
input: &'static str,
expect: Result<Vec<(&'static str, &'static str)>, ()>,
}
let tests = vec![
TestCase {
input: "",
expect: Ok(vec![]),
},
TestCase {
input: "--key",
expect: Err(()),
},
TestCase {
input: "--key=val",
expect: Ok(vec![("key", "val")]),
},
TestCase {
input: r#"--key=val -ckey2=val2 -c key3=val3 -c key4=val4 -ckey5=val5"#,
expect: Ok(vec![
("key", "val"),
("key2", "val2"),
("key3", "val3"),
("key4", "val4"),
("key5", "val5"),
]),
},
TestCase {
input: r#"-c\ key=val"#,
expect: Ok(vec![(" key", "val")]),
},
TestCase {
input: "--key=val -ckey2 val2",
expect: Err(()),
},
// Unclear what this should do.
TestCase {
input: "--key=",
expect: Ok(vec![("key", "")]),
},
];
for test in tests {
let got = parse_options(test.input);
let expect = test.expect.map(|r| {
r.into_iter()
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect()
});
assert_eq!(got, expect, "input: {}", test.input);
}
}
#[mz_ore::test]
fn test_parse_option() {
struct TestCase {
input: &'static str,
expect: Result<(&'static str, &'static str), ()>,
}
let tests = vec![
TestCase {
input: "",
expect: Err(()),
},
TestCase {
input: "--",
expect: Err(()),
},
TestCase {
input: "--c",
expect: Err(()),
},
TestCase {
input: "a=b",
expect: Err(()),
},
TestCase {
input: "--a=b",
expect: Ok(("a", "b")),
},
TestCase {
input: "--ca=b",
expect: Ok(("ca", "b")),
},
TestCase {
input: "-ca=b",
expect: Ok(("a", "b")),
},
// Unclear what this should error, but at least test it.
TestCase {
input: "--=",
expect: Ok(("", "")),
},
];
for test in tests {
let got = parse_option(test.input);
assert_eq!(got, test.expect, "input: {}", test.input);
}
}
#[mz_ore::test]
fn test_split_options() {
struct TestCase {
input: &'static str,
expect: Vec<&'static str>,
}
let tests = vec![
TestCase {
input: "",
expect: vec![],
},
TestCase {
input: " ",
expect: vec![],
},
TestCase {
input: " a ",
expect: vec!["a"],
},
TestCase {
input: " ab cd ",
expect: vec!["ab", "cd"],
},
TestCase {
input: r#" ab\ cd "#,
expect: vec!["ab ", "cd"],
},
TestCase {
input: r#" ab\\ cd "#,
expect: vec![r#"ab\"#, "cd"],
},
TestCase {
input: r#" ab\\\ cd "#,
expect: vec![r#"ab\ "#, "cd"],
},
TestCase {
input: r#" ab\\\ cd "#,
expect: vec![r#"ab\ cd"#],
},
TestCase {
input: r#" ab\\\cd "#,
expect: vec![r#"ab\cd"#],
},
TestCase {
input: r#"a\"#,
expect: vec!["a"],
},
TestCase {
input: r#"a\ "#,
expect: vec!["a "],
},
TestCase {
input: r#"\"#,
expect: vec![],
},
TestCase {
input: r#"\ "#,
expect: vec![r#" "#],
},
TestCase {
input: r#" \ "#,
expect: vec![r#" "#],
},
TestCase {
input: r#"\ "#,
expect: vec![r#" "#],
},
];
for test in tests {
let got = split_options(test.input);
assert_eq!(got, test.expect, "input: {}", test.input);
}
}
}