From 563fcba54eb4612970453d189480430f9ae5f0ce Mon Sep 17 00:00:00 2001 From: Rafia Sabih Date: Sat, 28 Nov 2026 08:56:49 +0100 Subject: [PATCH v19] postgres_fdw: Add streaming_fetch option for cursor-free fetching MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit postgres_fdw fetches remote rows through a cursor, which keeps the remote server from using parallel query. The new boolean option streaming_fetch (server and table level, default false) runs the scan in libpq’s chunked-rows mode instead, with fetch_size as the chunk size. Asynchronous execution is disabled in this mode, and scans that lock rows (FOR UPDATE/SHARE, or feeding a non-direct UPDATE or DELETE) still use a cursor, since a streamed query would lock every row up front. A connection carries only one such result at a time, so before anything else is sent on it, the rest of the active scan’s result is saved in the scan’s spool: whole PGresults up to work_mem, then rows in a temporary file. Rows are saved as received and converted only when the scan returns them, so no user-defined code runs on behalf of an unrelated statement. The connection refers to the spool only by ID; spools are deleted when their scan’s subtransaction aborts or portal fails, and any result whose spool is gone is discarded. A drain interrupted by an error makes the scan fail rather than return short results. A scan that stops early must still read the rest of the remote result, so streaming_fetch can be slower than a cursor when only a few rows are needed. Suggested-by: Bernd Helmle and Robert Haas Reviewed-by: Robert Haas, Alexander Pyhalov, Yilin Zhang and Kenan Yilmaz Tested-by: Jelte Fennema-Nio and Kenan Yilmaz --- contrib/postgres_fdw/connection.c | 94 +- .../postgres_fdw/expected/postgres_fdw.out | 826 +++++++++++++ .../postgres_fdw/expected/query_cancel.out | 21 + contrib/postgres_fdw/option.c | 4 + contrib/postgres_fdw/postgres_fdw.c | 1081 +++++++++++++++-- contrib/postgres_fdw/postgres_fdw.h | 12 + contrib/postgres_fdw/sql/postgres_fdw.sql | 423 +++++++ contrib/postgres_fdw/sql/query_cancel.sql | 11 + doc/src/sgml/postgres-fdw.sgml | 51 + src/tools/pgindent/typedefs.list | 1 + 10 files changed, 2423 insertions(+), 101 deletions(-) diff --git a/contrib/postgres_fdw/connection.c b/contrib/postgres_fdw/connection.c index 17f8c1e8f31..b951a4f1c32 100644 --- a/contrib/postgres_fdw/connection.c +++ b/contrib/postgres_fdw/connection.c @@ -177,11 +177,10 @@ static void pgfdw_inval_callback(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue); static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry); static void pgfdw_reset_xact_state(ConnCacheEntry *entry, bool toplevel); -static bool pgfdw_cancel_query(PGconn *conn); static bool pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime); static bool pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, - bool consume_input); + bool consume_input, PgFdwConnState *state); static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors); static bool pgfdw_exec_cleanup_query_begin(PGconn *conn, const char *query); @@ -313,6 +312,9 @@ GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state) /* Process a pending asynchronous request if any. */ if (entry->state.pendingAreq) process_pending_request(entry->state.pendingAreq); + + /* Likewise, finish any streaming_fetch scan using the connection. */ + drain_active_scan(&entry->state); /* Start a new transaction or subtransaction if needed. */ begin_remote_xact(entry); } @@ -445,6 +447,7 @@ make_new_connection(ConnCacheEntry *entry, UserMapping *user) /* Now try to make the connection */ entry->conn = connect_pg_server(server, user); + entry->state.conn = entry->conn; elog(DEBUG3, "new postgres_fdw connection %p for server \"%s\" (user mapping oid %u, userid %u)", entry->conn, server->servername, user->umid, user->userid); @@ -710,6 +713,7 @@ disconnect_pg_server(ConnCacheEntry *entry) { libpqsrv_disconnect(entry->conn); entry->conn = NULL; + entry->state.conn = NULL; } } @@ -1083,14 +1087,21 @@ GetPrepStmtNumber(PGconn *conn) * ignore that for now. * * Caller is responsible for the error handling on the result. + * + * state must not be NULL, since any streaming_fetch scan still using the + * connection has to be drained first. */ PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state) { /* First, process a pending asynchronous request, if any. */ - if (state && state->pendingAreq) + if (state->pendingAreq) process_pending_request(state->pendingAreq); + /* Likewise, finish any streaming_fetch scan using the connection. */ + Assert(state->conn == conn); + drain_active_scan(state); + if (!PQsendQuery(conn, query)) return NULL; return pgfdw_get_result(conn); @@ -1107,6 +1118,18 @@ pgfdw_get_result(PGconn *conn) return libpqsrv_get_result_last(conn, pgfdw_we_get_result); } +/* + * Wrap libpqsrv_get_result(), adding wait event. Used to read a + * streaming_fetch result one chunk at a time. + * + * Caller is responsible for the error handling on the result. + */ +PGresult * +pgfdw_get_next_result(PGconn *conn) +{ + return libpqsrv_get_result(conn, pgfdw_we_get_result); +} + /* * Report an error we got from the remote server. * @@ -1194,6 +1217,13 @@ pgfdw_xact_callback(XactEvent event, void *arg) List *pending_entries = NIL; List *cancel_requested = NIL; + /* streaming_fetch spools don't outlive the transaction */ + if (event == XACT_EVENT_PRE_COMMIT || + event == XACT_EVENT_PARALLEL_PRE_COMMIT || + event == XACT_EVENT_ABORT || + event == XACT_EVENT_PARALLEL_ABORT) + pgfdw_spools_at_xact_end(); + /* Quick exit if no connections were touched in this transaction. */ if (!xact_got_connection) return; @@ -1248,6 +1278,12 @@ pgfdw_xact_callback(XactEvent event, void *arg) */ pgfdw_reject_incomplete_xact_state_change(entry); + /* + * Open cursors are closed by now, but a failed one may + * have left its streaming_fetch result behind. + */ + drain_active_scan(&entry->state); + /* Commit all remote transactions during pre-commit */ CONSTRUCT_COMMIT_COMMAND(sql, entry); entry->changing_xact_state = true; @@ -1280,7 +1316,7 @@ pgfdw_xact_callback(XactEvent event, void *arg) if (entry->have_prep_stmt && entry->have_error) { res = pgfdw_exec_query(entry->conn, "DEALLOCATE ALL", - NULL); + &entry->state); PQclear(res); } entry->have_prep_stmt = false; @@ -1372,6 +1408,11 @@ pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid, List *pending_entries = NIL; List *cancel_requested = NIL; + /* Keep streaming_fetch spools in step with the subtransaction */ + if (event == SUBXACT_EVENT_COMMIT_SUB || event == SUBXACT_EVENT_ABORT_SUB) + pgfdw_spools_at_subxact_end(event == SUBXACT_EVENT_COMMIT_SUB, + mySubid, parentSubid); + /* Nothing to do at subxact start, nor after commit. */ if (!(event == SUBXACT_EVENT_PRE_COMMIT_SUB || event == SUBXACT_EVENT_ABORT_SUB)) @@ -1410,6 +1451,14 @@ pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid, */ pgfdw_reject_incomplete_xact_state_change(entry); + /* + * A cursor that outlives this subtransaction may still be + * streaming; drain it before RELEASE SAVEPOINT. Do this before + * setting changing_xact_state, so an error only aborts the + * subtransaction. + */ + drain_active_scan(&entry->state); + /* Commit all remote subtransactions during pre-commit */ snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel); entry->changing_xact_state = true; @@ -1606,9 +1655,11 @@ pgfdw_reset_xact_state(ConnCacheEntry *entry, bool toplevel) * XXX: if the query was one sent by fetch_more_data_begin(), we could get the * query text from the pendingAreq saved in the per-connection state, then * report the query using it. + * + * On success, pgfdw_cancel_query_end() also clears state->active_spool_id. */ -static bool -pgfdw_cancel_query(PGconn *conn) +bool +pgfdw_cancel_query(PGconn *conn, PgFdwConnState *state) { TimestampTz now = GetCurrentTimestamp(); TimestampTz endtime; @@ -1628,7 +1679,7 @@ pgfdw_cancel_query(PGconn *conn) if (!pgfdw_cancel_query_begin(conn, endtime)) return false; - return pgfdw_cancel_query_end(conn, endtime, retrycanceltime, false); + return pgfdw_cancel_query_end(conn, endtime, retrycanceltime, false, state); } /* @@ -1655,7 +1706,8 @@ pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime) static bool pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime, - TimestampTz retrycanceltime, bool consume_input) + TimestampTz retrycanceltime, bool consume_input, + PgFdwConnState *state) { PGresult *result; bool timed_out; @@ -1692,6 +1744,9 @@ pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime, } PQclear(result); + /* The canceled query's result is consumed; nothing is streaming now. */ + state->active_spool_id = 0; + return true; } @@ -1943,7 +1998,7 @@ pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel) * remote server, and if so, request cancellation of the command. */ if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE && - !pgfdw_cancel_query(entry->conn)) + !pgfdw_cancel_query(entry->conn, &entry->state)) return; /* Unable to cancel running query */ CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel); @@ -1966,10 +2021,11 @@ pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel) * If pendingAreq of the per-connection state is not NULL, it means that * an asynchronous fetch begun by fetch_more_data_begin() was not done * successfully and thus the per-connection state was not reset in - * fetch_more_data(); in that case reset the per-connection state here. + * fetch_more_data(). Reset it. A streaming_fetch result still being + * read was consumed by the cancel above, which cleared active_spool_id. */ - if (entry->state.pendingAreq) - memset(&entry->state, 0, sizeof(entry->state)); + entry->state.pendingAreq = NULL; + Assert(entry->state.active_spool_id == 0); /* Disarm changing_xact_state if it all worked */ entry->changing_xact_state = false; @@ -2193,7 +2249,7 @@ pgfdw_finish_abort_cleanup(List *pending_entries, List *cancel_requested, RETRY_CANCEL_TIMEOUT); if (!pgfdw_cancel_query_end(entry->conn, endtime, - retrycanceltime, true)) + retrycanceltime, true, &entry->state)) { /* Unable to cancel running query */ pgfdw_reset_xact_state(entry, toplevel); @@ -2263,9 +2319,9 @@ pgfdw_finish_abort_cleanup(List *pending_entries, List *cancel_requested, entry->have_error = false; } - /* Reset the per-connection state if needed */ - if (entry->state.pendingAreq) - memset(&entry->state, 0, sizeof(entry->state)); + /* Reset the async request; the cancel consumed any streaming result */ + entry->state.pendingAreq = NULL; + Assert(entry->state.active_spool_id == 0); /* We're done with this entry; unset the changing_xact_state flag */ entry->changing_xact_state = false; @@ -2308,9 +2364,9 @@ pgfdw_finish_abort_cleanup(List *pending_entries, List *cancel_requested, entry->have_prep_stmt = false; entry->have_error = false; - /* Reset the per-connection state if needed */ - if (entry->state.pendingAreq) - memset(&entry->state, 0, sizeof(entry->state)); + /* Reset the async request; the cancel consumed any streaming result */ + entry->state.pendingAreq = NULL; + Assert(entry->state.active_spool_id == 0); /* We're done with this entry; unset the changing_xact_state flag */ entry->changing_xact_state = false; diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index 115ebc7925f..8edce32b2f2 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -255,6 +255,49 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again ANALYZE ft1; ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true'); -- =================================================================== +-- test streaming_fetch option +-- =================================================================== +CREATE SERVER fetch_stream_srv FOREIGN DATA WRAPPER postgres_fdw + OPTIONS (streaming_fetch 'true'); +CREATE USER MAPPING FOR CURRENT_USER SERVER fetch_stream_srv; +CREATE FOREIGN TABLE ft_stream (c1 int) SERVER fetch_stream_srv; +-- Set on the server; EXPLAIN VERBOSE shows "Streaming Fetch: true". +EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_stream; + QUERY PLAN +----------------------------------------------- + Foreign Scan on public.ft_stream + Output: c1 + Remote SQL: SELECT c1 FROM public.ft_stream + Streaming Fetch: true +(4 rows) + +-- A table-level setting overrides the server's, in either direction. +ALTER FOREIGN TABLE ft_stream OPTIONS (ADD streaming_fetch 'false'); +EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_stream; + QUERY PLAN +----------------------------------------------- + Foreign Scan on public.ft_stream + Output: c1 + Remote SQL: SELECT c1 FROM public.ft_stream +(3 rows) + +ALTER SERVER fetch_stream_srv OPTIONS (SET streaming_fetch 'false'); +ALTER FOREIGN TABLE ft_stream OPTIONS (SET streaming_fetch 'true'); +EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_stream; + QUERY PLAN +----------------------------------------------- + Foreign Scan on public.ft_stream + Output: c1 + Remote SQL: SELECT c1 FROM public.ft_stream + Streaming Fetch: true +(4 rows) + +ALTER FOREIGN TABLE ft_stream OPTIONS (SET streaming_fetch 'yes'); -- ERROR +ERROR: streaming_fetch requires a Boolean value +DROP FOREIGN TABLE ft_stream; +DROP USER MAPPING FOR CURRENT_USER SERVER fetch_stream_srv; +DROP SERVER fetch_stream_srv; +-- =================================================================== -- test subscription -- =================================================================== CREATE SUBSCRIPTION regress_pgfdw_subscription SERVER testserver1 @@ -892,6 +935,713 @@ WHERE a.c2 = 6 AND b.c1 = a.c1 AND a.c8 = 'foo' AND b.c7 = upper(a.c7); 996 | 6 | 00996 | Tue Apr 07 00:00:00 1970 PST | Tue Apr 07 00:00:00 1970 | 6 | 6 | foo | 996 | 6 | 00996 | Tue Apr 07 00:00:00 1970 PST | Tue Apr 07 00:00:00 1970 | 6 | 6 | foo (100 rows) +-- =================================================================== +-- streaming_fetch scans sharing a connection +-- =================================================================== +-- ft1_s and ft2_s stream the same remote table as ft1 and ft2, and all four +-- share the loopback connection. ft2_s gets its rows in chunks of 5. +CREATE FOREIGN TABLE ft1_s ( + c1 int NOT NULL, + c2 int NOT NULL, + c3 text, + c4 timestamptz, + c5 timestamp, + c6 varchar(10), + c7 char(10) default 'ft1', + c8 user_enum +) SERVER loopback OPTIONS (schema_name 'S 1', table_name 'T 1', + streaming_fetch 'true'); +ALTER FOREIGN TABLE ft1_s ALTER COLUMN c1 OPTIONS (column_name 'C 1'); +CREATE FOREIGN TABLE ft2_s ( + c1 int NOT NULL, + c2 int NOT NULL, + c3 text, + c4 timestamptz, + c5 timestamp, + c6 varchar(10), + c7 char(10) default 'ft2', + c8 user_enum +) SERVER loopback OPTIONS (schema_name 'S 1', table_name 'T 1', + streaming_fetch 'true', fetch_size '5', + use_remote_estimate 'true'); +ALTER FOREIGN TABLE ft2_s ALTER COLUMN c1 OPTIONS (column_name 'C 1'); +-- Nested loops: each time the inner scan starts, the rest of the outer +-- scan's result is saved locally, and later read back in fetch_size batches. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM ft2_s a, ft2_s b +WHERE a.c2 = 6 AND b.c1 = a.c1 AND a.c8 = 'foo' AND b.c7 = upper(a.c7); + QUERY PLAN +------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: a.c1, a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8, b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8 + -> Foreign Scan on public.ft2_s a + Output: a.c1, a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8 + Filter: (a.c8 = 'foo'::user_enum) + Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE ((c2 = 6)) + Streaming Fetch: true + -> Foreign Scan on public.ft2_s b + Output: b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8 + Filter: ((b.c7)::text = upper((a.c7)::text)) + Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (($1::integer = "C 1")) + Streaming Fetch: true +(12 rows) + +SELECT count(*), sum(b.c1) FROM ft2_s a, ft2_s b +WHERE a.c2 = 6 AND b.c1 = a.c1 AND a.c8 = 'foo' AND b.c7 = upper(a.c7); + count | sum +-------+------- + 100 | 50100 +(1 row) + +-- An EXISTS subquery stops its streaming scan at the first match, leaving +-- the rest of its result unread. The connection must still work for the +-- outer cursor's later FETCHes (ft1 needs several with fetch_size 5), for a +-- per-row UPDATE, and for a pushed-down UPDATE on ft4. +CREATE FUNCTION direct_modify_ft4(id int) RETURNS void AS $$ + UPDATE ft4 SET c3 = c3 WHERE c1 = id; +$$ LANGUAGE sql; +ALTER FOREIGN TABLE ft1 OPTIONS (ADD fetch_size '5'); +SET enable_hashagg = off; +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_material = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT a.c1, a.c2 FROM ft1 a +WHERE a.c1 < 20 AND a.c8 = 'foo' AND EXISTS (SELECT 1 FROM ft2_s b WHERE b.c2 = a.c2) +ORDER BY a.c1; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------- + Nested Loop Semi Join + Output: a.c1, a.c2 + -> Foreign Scan on public.ft1 a + Output: a.c1, a.c2 + Filter: (a.c8 = 'foo'::user_enum) + Remote SQL: SELECT "C 1", c2, c8 FROM "S 1"."T 1" WHERE (("C 1" < 20)) ORDER BY "C 1" ASC NULLS LAST + -> Foreign Scan on public.ft2_s b + Output: b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8 + Remote SQL: SELECT c2 FROM "S 1"."T 1" WHERE ((c2 = $1::integer)) + Streaming Fetch: true +(10 rows) + +SELECT a.c1, a.c2 FROM ft1 a +WHERE a.c1 < 20 AND a.c8 = 'foo' AND EXISTS (SELECT 1 FROM ft2_s b WHERE b.c2 = a.c2) +ORDER BY a.c1; + c1 | c2 +----+---- + 1 | 1 + 2 | 2 + 3 | 3 + 4 | 4 + 5 | 5 + 6 | 6 + 7 | 7 + 8 | 8 + 9 | 9 + 10 | 0 + 11 | 1 + 12 | 2 + 13 | 3 + 14 | 4 + 15 | 5 + 16 | 6 + 17 | 7 + 18 | 8 + 19 | 9 +(19 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE ft1 SET c3 = c3 +WHERE c1 < 20 AND c8 = 'foo' AND EXISTS (SELECT 1 FROM ft2_s b WHERE b.c2 = ft1.c2); + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------- + Update on public.ft1 + Remote SQL: UPDATE "S 1"."T 1" SET c3 = $2 WHERE ctid = $1 + -> Nested Loop Semi Join + Output: ft1.c3, ft1.ctid, ft1.*, b.* + -> Foreign Scan on public.ft1 + Output: ft1.c3, ft1.ctid, ft1.*, ft1.c2 + Filter: (ft1.c8 = 'foo'::user_enum) + Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8, ctid FROM "S 1"."T 1" WHERE (("C 1" < 20)) FOR UPDATE + -> Foreign Scan on public.ft2_s b + Output: b.*, b.c2 + Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE ((c2 = $1::integer)) + Streaming Fetch: true +(12 rows) + +EXPLAIN (VERBOSE, COSTS OFF) UPDATE ft4 SET c3 = c3 WHERE c1 = 1; + QUERY PLAN +--------------------------------------------------------------------- + Update on public.ft4 + -> Foreign Update on public.ft4 + Remote SQL: UPDATE "S 1"."T 3" SET c3 = c3 WHERE ((c1 = 1)) +(3 rows) + +BEGIN; +WITH u AS (UPDATE ft1 SET c3 = c3 + WHERE c1 < 20 AND c8 = 'foo' AND EXISTS (SELECT 1 FROM ft2_s b WHERE b.c2 = ft1.c2) + RETURNING c1) +SELECT count(*) FROM u; + count +------- + 19 +(1 row) + +SELECT count(*) FROM (SELECT direct_modify_ft4(a.c1) FROM ft1 a + WHERE a.c1 < 20 AND a.c8 = 'foo' AND EXISTS (SELECT 1 FROM ft2_s b WHERE b.c2 = a.c2) + OFFSET 0) s; + count +------- + 19 +(1 row) + +ROLLBACK; +-- A rescan of a scan that gets no new parameters (here, the outer row is +-- only used above it) replays the chunk it has in memory; but once one of +-- the outer cursor's FETCHes has saved the rest of its result, it is re-run. +SET enable_memoize = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT a.c1, s.c1 FROM ft1 a, + LATERAL (SELECT b.c1 FROM (SELECT c1, c2 FROM ft2_s OFFSET 0) b + WHERE b.c2 = a.c2 LIMIT 1) s +WHERE a.c1 < 20; + QUERY PLAN +---------------------------------------------------------------------------- + Nested Loop + Output: a.c1, b.c1 + -> Foreign Scan on public.ft1 a + Output: a.c1, a.c2 + Remote SQL: SELECT "C 1", c2 FROM "S 1"."T 1" WHERE (("C 1" < 20)) + -> Limit + Output: b.c1 + -> Subquery Scan on b + Output: b.c1 + Filter: (b.c2 = a.c2) + -> Foreign Scan on public.ft2_s + Output: ft2_s.c1, ft2_s.c2 + Remote SQL: SELECT "C 1", c2 FROM "S 1"."T 1" + Streaming Fetch: true +(14 rows) + +SELECT count(*) FROM ft1 a, + LATERAL (SELECT b.c1 FROM (SELECT c1, c2 FROM ft2_s OFFSET 0) b + WHERE b.c2 = a.c2 LIMIT 1) s +WHERE a.c1 < 20; + count +------- + 19 +(1 row) + +RESET enable_memoize; +RESET enable_hashagg; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_material; +ALTER FOREIGN TABLE ft1 OPTIONS (DROP fetch_size); +DROP FUNCTION direct_modify_ft4(int); +-- Scans that lock rows, including those under a non-direct UPDATE or DELETE, +-- use a cursor (no "Streaming Fetch"). +EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft2_s WHERE c1 = 1 FOR UPDATE; + QUERY PLAN +-------------------------------------------------------------------------------------------------------- + Foreign Scan on public.ft2_s + Output: c1, c2, c3, c4, c5, c6, c7, c8, ft2_s.* + Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 1)) FOR UPDATE +(3 rows) + +EXPLAIN (VERBOSE, COSTS OFF) DELETE FROM ft2_s WHERE c1 = 1 AND random() >= 0; + QUERY PLAN +--------------------------------------------------------------------------------- + Delete on public.ft2_s + Remote SQL: DELETE FROM "S 1"."T 1" WHERE ctid = $1 + -> Foreign Scan on public.ft2_s + Output: ctid + Filter: (random() >= '0'::double precision) + Remote SQL: SELECT ctid FROM "S 1"."T 1" WHERE (("C 1" = 1)) FOR UPDATE +(6 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE ft2_s f1 SET c3 = f2.c3 FROM ft1_s f2 +WHERE f1.c1 = f2.c1 AND f1.c1 = 3 AND random() >= 0; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.ft2_s f1 + Remote SQL: UPDATE "S 1"."T 1" SET c3 = $2 WHERE ctid = $1 + -> Foreign Scan + Output: f2.c3, f1.ctid, f1.*, f2.* + Filter: (random() >= '0'::double precision) + Relations: (public.ft2_s f1) INNER JOIN (public.ft1_s f2) + Remote SQL: SELECT r2.c3, r1.ctid, CASE WHEN (r1.*)::text IS NOT NULL THEN ROW(r1."C 1", r1.c2, r1.c3, r1.c4, r1.c5, r1.c6, r1.c7, r1.c8) END, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2."C 1", r2.c2, r2.c3, r2.c4, r2.c5, r2.c6, r2.c7, r2.c8) END FROM ("S 1"."T 1" r1 INNER JOIN "S 1"."T 1" r2 ON (((r2."C 1" = 3)) AND ((r1."C 1" = 3)))) FOR UPDATE OF r1 + -> Nested Loop + Output: f2.c3, f1.ctid, f1.*, f2.* + -> Foreign Scan on public.ft2_s f1 + Output: f1.ctid, f1.*, f1.c1 + Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8, ctid FROM "S 1"."T 1" WHERE (("C 1" = 3)) FOR UPDATE + -> Foreign Scan on public.ft1_s f2 + Output: f2.c3, f2.*, f2.c1 + Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 3)) + Streaming Fetch: true +(16 rows) + +-- A scan that fetches ctid without locking rows streams, and the ctid of +-- rows saved by a drain (6 to 12) is kept. +EXPLAIN (VERBOSE, COSTS OFF) SELECT c1, ctid FROM ft2_s WHERE c1 <= 12; + QUERY PLAN +------------------------------------------------------------------------- + Foreign Scan on public.ft2_s + Output: c1, ctid + Remote SQL: SELECT "C 1", ctid FROM "S 1"."T 1" WHERE (("C 1" <= 12)) + Streaming Fetch: true +(4 rows) + +BEGIN; +DECLARE c CURSOR FOR SELECT c1, ctid FROM ft2_s WHERE c1 <= 12 ORDER BY c1; +FETCH 1 FROM c; + c1 | ctid +----+------- + 1 | (0,1) +(1 row) + +SELECT count(*) FROM ft1; -- saves rows 6 to 12 + count +------- + 1000 +(1 row) + +FETCH ALL FROM c; + c1 | ctid +----+-------- + 2 | (0,2) + 3 | (0,3) + 4 | (0,4) + 5 | (0,5) + 6 | (0,6) + 7 | (0,7) + 8 | (0,8) + 9 | (0,9) + 10 | (0,10) + 11 | (0,11) + 12 | (0,12) +(11 rows) + +COMMIT; +-- A cursor whose last chunk was full can't tell it is at EOF. If a drain +-- then finds only the end of its stream, the next FETCH must return nothing. +BEGIN; +DECLARE c CURSOR FOR SELECT c1 FROM ft2_s WHERE c1 <= 10 ORDER BY c1; +MOVE 10 IN c; -- two full chunks +SELECT count(*) FROM ft1; -- reads the end of c's stream + count +------- + 1000 +(1 row) + +FETCH ALL FROM c; + c1 +---- +(0 rows) + +COMMIT; +DROP FOREIGN TABLE ft1_s, ft2_s; +-- Failures while a streaming scan's rows are read. Row 6's x can't be +-- converted to an int. +CREATE TABLE loct_lost (id int, x text); +INSERT INTO loct_lost SELECT g, g::text FROM generate_series(1, 5) g; +INSERT INTO loct_lost VALUES (6, 'not_an_int'), (7, '7'), (8, '8'); +CREATE FOREIGN TABLE ft_lost (id int, x int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_lost', + streaming_fetch 'true', fetch_size '2'); +CREATE FOREIGN TABLE ft_lost_other (id int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_lost'); +\set VERBOSITY terse +-- If the remote query itself fails while its rows are being saved, inside a +-- subtransaction, the scan must fail at the outer level rather than return +-- short results. The view fails at row 3000, after the rows saved before +-- the error have spilled to a temporary file. +CREATE VIEW loct_lost_big AS + SELECT g AS id, repeat('x', 100) AS pad, 1 / (g - 3000) AS x + FROM generate_series(1, 5000) g; +CREATE FOREIGN TABLE ft_lost_big (id int, pad text, x int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_lost_big', + streaming_fetch 'true', fetch_size '100'); +BEGIN; +SET LOCAL work_mem = '64kB'; +DECLARE c_lost CURSOR FOR SELECT id, length(pad), x FROM ft_lost_big; +FETCH 1 FROM c_lost; + id | length | x +----+--------+--- + 1 | 100 | 0 +(1 row) + +SAVEPOINT sp; +SELECT count(*) FROM ft_lost_other; -- ERROR at row 3000 +ERROR: division by zero +ROLLBACK TO SAVEPOINT sp; +FETCH ALL FROM c_lost; -- ERROR +ERROR: could not obtain all rows from remote server +COMMIT; +SELECT count(*) FROM ft_lost_other; -- connection still works + count +------- + 8 +(1 row) + +-- A cursor that fails while being read in a subtransaction is abandoned, +-- with its remote query still sending rows. The rest of that result must be +-- discarded before the connection is next used: by a query while the failed +-- cursor is still open, by one after it is closed, or by COMMIT. The last +-- two fail in lost_boom(), at row 3, in a cursor whose remote query only +-- starts inside the subtransaction. +CREATE FUNCTION lost_boom(id int) RETURNS int LANGUAGE plpgsql AS $$ +BEGIN + IF id = 3 THEN RAISE 'boom'; END IF; + RETURN id; +END $$; +BEGIN; +DECLARE c_lost CURSOR FOR SELECT id, x FROM ft_lost ORDER BY id; +FETCH 1 FROM c_lost; + id | x +----+--- + 1 | 1 +(1 row) + +SAVEPOINT sp; +FETCH 6 FROM c_lost; -- ERROR at row 6 +ERROR: invalid input syntax for type integer: "not_an_int" +ROLLBACK TO SAVEPOINT sp; +SELECT count(*) FROM ft_lost_other; + count +------- + 8 +(1 row) + +COMMIT; +BEGIN; +DECLARE c_lost CURSOR FOR SELECT lost_boom(id) FROM ft_lost ORDER BY id; +SAVEPOINT sp; +FETCH 5 FROM c_lost; -- ERROR at row 3 +ERROR: boom +ROLLBACK TO SAVEPOINT sp; +CLOSE c_lost; +SELECT count(*) FROM ft_lost_other; + count +------- + 8 +(1 row) + +COMMIT; +BEGIN; +DECLARE c_lost CURSOR FOR SELECT lost_boom(id) FROM ft_lost ORDER BY id; +SAVEPOINT sp; +FETCH 5 FROM c_lost; -- ERROR at row 3 +ERROR: boom +ROLLBACK TO SAVEPOINT sp; +COMMIT; +\set VERBOSITY default +-- A domain's input checks can run arbitrary code, so they must run only +-- while the scan itself is reading: these NOTICEs come from the FETCHes, not +-- from the query that saves the rest of the cursor's rows. +CREATE FUNCTION lost_note(x int) RETURNS bool LANGUAGE plpgsql AS $$ +BEGIN + RAISE NOTICE 'checking %', x; + RETURN true; +END $$; +CREATE DOMAIN lost_note_int AS int CHECK (lost_note(VALUE)); +CREATE FOREIGN TABLE ft_lost_note (id int, x lost_note_int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_lost', + streaming_fetch 'true', fetch_size '2'); +BEGIN; +DECLARE c_lost CURSOR FOR + SELECT id, x FROM ft_lost_note WHERE id <= 4 ORDER BY id; +FETCH 1 FROM c_lost; +NOTICE: checking 1 +NOTICE: checking 2 + id | x +----+--- + 1 | 1 +(1 row) + +SELECT count(*) FROM ft_lost_other; -- saves rows 3 and 4 + count +------- + 8 +(1 row) + +FETCH ALL FROM c_lost; +NOTICE: checking 3 +NOTICE: checking 4 + id | x +----+--- + 2 | 2 + 3 | 3 + 4 | 4 +(3 rows) + +COMMIT; +-- Such code can also use the connection the scan is reading from, in the +-- middle of converting the scan's own rows, which saves the rest of the +-- scan's result. +CREATE FUNCTION lost_query(x int) RETURNS bool LANGUAGE plpgsql AS $$ +BEGIN + IF x = current_setting('test.lost_query_at')::int THEN + PERFORM count(*) FROM ft_lost_other; + END IF; + RETURN true; +END $$; +CREATE DOMAIN lost_query_int AS int CHECK (lost_query(VALUE)); +CREATE FOREIGN TABLE ft_lost_query (id int, x lost_query_int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_lost', + streaming_fetch 'true', fetch_size '2'); +SET test.lost_query_at = 1; +SELECT id, x FROM ft_lost_query WHERE id <= 4 ORDER BY id; + id | x +----+--- + 1 | 1 + 2 | 2 + 3 | 3 + 4 | 4 +(4 rows) + +RESET test.lost_query_at; +DROP FOREIGN TABLE ft_lost_note, ft_lost_query; +DROP DOMAIN lost_note_int, lost_query_int; +DROP FUNCTION lost_boom(int), lost_note(int), lost_query(int); +DROP FOREIGN TABLE ft_lost, ft_lost_other, ft_lost_big; +DROP VIEW loct_lost_big; +DROP TABLE loct_lost; +-- Transaction control with a cursor whose remote query is still streaming +-- when postgres_fdw sends RELEASE SAVEPOINT, ROLLBACK TO SAVEPOINT or +-- COMMIT. Each case must return every row or fail cleanly, and leave the +-- connection usable. +CREATE TABLE loct_xact (id int, x text); +INSERT INTO loct_xact SELECT g, g::text FROM generate_series(1, 10) g; +CREATE FOREIGN TABLE ft_xact (id int, x int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_xact', + streaming_fetch 'true', fetch_size '2'); +CREATE FOREIGN TABLE ft_xact_other (id int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_xact'); +-- Nested savepoints, released one at a time; parallel_commit sends each +-- RELEASE SAVEPOINT asynchronously. +ALTER SERVER loopback OPTIONS (ADD parallel_commit 'true'); +BEGIN; +SAVEPOINT s1; +SAVEPOINT s2; +DECLARE c CURSOR FOR SELECT id FROM ft_xact ORDER BY id; +FETCH 3 FROM c; + id +---- + 1 + 2 + 3 +(3 rows) + +RELEASE SAVEPOINT s2; +FETCH 2 FROM c; + id +---- + 4 + 5 +(2 rows) + +RELEASE SAVEPOINT s1; +FETCH ALL FROM c; + id +---- + 6 + 7 + 8 + 9 + 10 +(5 rows) + +COMMIT; +ALTER SERVER loopback OPTIONS (DROP parallel_commit); +-- Rolling back the subtransaction in which the cursor was first read +-- cancels the remote query, so the cursor must report an error. +BEGIN; +DECLARE c CURSOR FOR SELECT id FROM ft_xact ORDER BY id; +SAVEPOINT s; +SELECT count(*) FROM ft_xact_other; + count +------- + 10 +(1 row) + +FETCH 3 FROM c; + id +---- + 1 + 2 + 3 +(3 rows) + +ROLLBACK TO SAVEPOINT s; +FETCH ALL FROM c; -- ERROR +ERROR: could not obtain remaining rows from remote server +DETAIL: The remote query was canceled when a subtransaction was rolled back. +COMMIT; +SELECT count(*) FROM ft_xact_other; -- connection still works + count +------- + 10 +(1 row) + +-- Cursor opened in a subtransaction that is rolled back goes away with it. +BEGIN; +SAVEPOINT s; +DECLARE c CURSOR FOR SELECT id FROM ft_xact ORDER BY id; +FETCH 3 FROM c; + id +---- + 1 + 2 + 3 +(3 rows) + +ROLLBACK TO SAVEPOINT s; +SELECT count(*) FROM ft_xact_other; + count +------- + 10 +(1 row) + +COMMIT; +-- Rows saved at RELEASE SAVEPOINT are converted later, so a bad one is +-- reported by the FETCH that reaches it. +INSERT INTO loct_xact VALUES (11, 'not_an_int'); +\set VERBOSITY terse +BEGIN; +SAVEPOINT s; +DECLARE c CURSOR FOR SELECT id, x FROM ft_xact ORDER BY id; +FETCH 3 FROM c; + id | x +----+--- + 1 | 1 + 2 | 2 + 3 | 3 +(3 rows) + +RELEASE SAVEPOINT s; +FETCH ALL FROM c; -- ERROR at row 11 +ERROR: invalid input syntax for type integer: "not_an_int" +ROLLBACK; +\set VERBOSITY default +SELECT count(*) FROM ft_xact_other; -- connection still works + count +------- + 11 +(1 row) + +DELETE FROM loct_xact WHERE id = 11; +-- A holdable cursor is read to the end at COMMIT and keeps all its rows. +BEGIN; +DECLARE c CURSOR WITH HOLD FOR SELECT id FROM ft_xact ORDER BY id; +FETCH 3 FROM c; + id +---- + 1 + 2 + 3 +(3 rows) + +COMMIT; +FETCH ALL FROM c; + id +---- + 4 + 5 + 6 + 7 + 8 + 9 + 10 +(7 rows) + +CLOSE c; +DROP FOREIGN TABLE ft_xact, ft_xact_other; +DROP TABLE loct_xact; +-- Rows saved locally on behalf of a cursor may spill to a temp file. That +-- file belongs to the cursor, so it must survive the rollback of the +-- subtransaction in which it was written. Every other row has a NULL. +CREATE TABLE loct_spill (id int, pad text); +INSERT INTO loct_spill + SELECT g, CASE WHEN g % 2 = 0 THEN repeat('x', 100) END + FROM generate_series(1, 5000) g; +CREATE FOREIGN TABLE ft_spill (id int, pad text) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_spill', + streaming_fetch 'true', fetch_size '10'); +CREATE FOREIGN TABLE ft_spill_other (id int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_spill'); +BEGIN; +SET LOCAL work_mem = '64kB'; +DECLARE c CURSOR FOR SELECT id, length(pad) FROM ft_spill ORDER BY id; +FETCH 1 FROM c; + id | length +----+-------- + 1 | +(1 row) + +SAVEPOINT s; +SELECT count(*) FROM ft_spill_other; -- saves c's rows, spilling to disk + count +------- + 5000 +(1 row) + +ROLLBACK TO SAVEPOINT s; +MOVE 4995 FROM c; +FETCH ALL FROM c; + id | length +------+-------- + 4997 | + 4998 | 100 + 4999 | + 5000 | 100 +(4 rows) + +COMMIT; +-- Rows still in a temp file are released when a rescan starts the scan over, +-- and when a cursor holding them fails. spill_fn() uses the connection at +-- row 1, which saves the rest of the scan's own result, spilling to disk. +CREATE FUNCTION spill_fn(id int) RETURNS int LANGUAGE plpgsql AS $$ +BEGIN + IF id = 1 THEN + PERFORM count(*) FROM ft_spill_other; + ELSIF id = 4000 THEN + RAISE 'boom'; + END IF; + RETURN id; +END $$; +BEGIN; +SET LOCAL work_mem = '64kB'; +SET LOCAL enable_material = off; +SET LOCAL enable_memoize = off; +SELECT v.x, s.id FROM (VALUES (1), (2)) v(x), + LATERAL (SELECT id FROM ft_spill WHERE spill_fn(id) > 0 AND v.x > 0 + ORDER BY id LIMIT 1) s; + x | id +---+---- + 1 | 1 + 2 | 1 +(2 rows) + +COMMIT; +\set VERBOSITY terse +BEGIN; +SET LOCAL work_mem = '64kB'; +DECLARE c CURSOR FOR SELECT spill_fn(id) FROM ft_spill ORDER BY id; +FETCH 1 FROM c; + spill_fn +---------- + 1 +(1 row) + +MOVE ALL IN c; -- ERROR at row 4000 +ERROR: boom +ROLLBACK; +\set VERBOSITY default +DROP FUNCTION spill_fn(int); +DROP FOREIGN TABLE ft_spill, ft_spill_other; +DROP TABLE loct_spill; -- bug before 9.3.5 due to sloppy handling of remote-estimate parameters SELECT * FROM ft1 WHERE c1 = ANY (ARRAY(SELECT c1 FROM ft2 WHERE c1 < 5)); c1 | c2 | c3 | c4 | c5 | c6 | c7 | c8 @@ -11587,6 +12337,43 @@ SELECT 1 FROM ft1 LIMIT 1; -- should fail ERROR: 08006 \set VERBOSITY default COMMIT; +-- =================================================================== +-- streaming_fetch: reconnecting after the remote backend terminates +-- =================================================================== +ALTER FOREIGN TABLE ft1 OPTIONS (ADD streaming_fetch 'true'); +SELECT 1 FROM ft1 LIMIT 1; -- open the connection + ?column? +---------- + 1 +(1 row) + +DO $$ BEGIN +PERFORM pg_terminate_backend(pid, 180000) FROM pg_stat_activity + WHERE application_name = 'fdw_retry_check'; +END $$; +-- Outside a subtransaction, the broken connection is reestablished. +BEGIN; +SELECT c1 FROM ft1 ORDER BY c1 LIMIT 3; + c1 +---- + 1 + 3 + 4 +(3 rows) + +DO $$ BEGIN +PERFORM pg_terminate_backend(pid, 180000) FROM pg_stat_activity + WHERE application_name = 'fdw_retry_check'; +END $$; +-- Inside one, it isn't, and the query fails. +SAVEPOINT s2; +-- The text of the error might vary across platforms, so only show SQLSTATE. +\set VERBOSITY sqlstate +SELECT 1 FROM ft1 LIMIT 1; -- should fail +ERROR: 08006 +\set VERBOSITY default +COMMIT; +ALTER FOREIGN TABLE ft1 OPTIONS (DROP streaming_fetch); -- ============================================================================= -- test connection invalidation cases and postgres_fdw_get_connections function -- ============================================================================= @@ -12816,6 +13603,45 @@ SELECT * FROM local_tbl, async_pt WHERE local_tbl.a = async_pt.a AND local_tbl.c ALTER FOREIGN TABLE async_p1 OPTIONS (DROP use_remote_estimate); ALTER FOREIGN TABLE async_p2 OPTIONS (DROP use_remote_estimate); +-- streaming_fetch disables asynchronous execution, whether it is set on the +-- table (async_p1) or on the server (loopback2, used by async_p2). +ALTER FOREIGN TABLE async_p1 OPTIONS (ADD streaming_fetch 'true'); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM async_pt; + QUERY PLAN +---------------------------------------------------------- + Append + -> Foreign Scan on public.async_p1 async_pt_1 + Output: async_pt_1.a, async_pt_1.b, async_pt_1.c + Remote SQL: SELECT a, b, c FROM public.base_tbl1 + Streaming Fetch: true + -> Async Foreign Scan on public.async_p2 async_pt_2 + Output: async_pt_2.a, async_pt_2.b, async_pt_2.c + Remote SQL: SELECT a, b, c FROM public.base_tbl2 + -> Seq Scan on public.async_p3 async_pt_3 + Output: async_pt_3.a, async_pt_3.b, async_pt_3.c +(10 rows) + +ALTER SERVER loopback2 OPTIONS (ADD streaming_fetch 'true'); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM async_pt; + QUERY PLAN +---------------------------------------------------------- + Append + -> Foreign Scan on public.async_p1 async_pt_1 + Output: async_pt_1.a, async_pt_1.b, async_pt_1.c + Remote SQL: SELECT a, b, c FROM public.base_tbl1 + Streaming Fetch: true + -> Foreign Scan on public.async_p2 async_pt_2 + Output: async_pt_2.a, async_pt_2.b, async_pt_2.c + Remote SQL: SELECT a, b, c FROM public.base_tbl2 + Streaming Fetch: true + -> Seq Scan on public.async_p3 async_pt_3 + Output: async_pt_3.a, async_pt_3.b, async_pt_3.c +(11 rows) + +ALTER FOREIGN TABLE async_p1 OPTIONS (DROP streaming_fetch); +ALTER SERVER loopback2 OPTIONS (DROP streaming_fetch); DROP TABLE local_tbl; DROP INDEX base_tbl1_idx; DROP INDEX base_tbl2_idx; diff --git a/contrib/postgres_fdw/expected/query_cancel.out b/contrib/postgres_fdw/expected/query_cancel.out index c3fc585d49f..ba976931eac 100644 --- a/contrib/postgres_fdw/expected/query_cancel.out +++ b/contrib/postgres_fdw/expected/query_cancel.out @@ -32,3 +32,24 @@ SET LOCAL statement_timeout = '10ms'; SELECT count(*) FROM ft1 a CROSS JOIN ft1 b CROSS JOIN ft1 c CROSS JOIN ft1 d; ERROR: canceling statement due to statement timeout COMMIT; +-- Same with streaming_fetch: canceling mid-stream must leave the connection +-- usable. +ALTER FOREIGN TABLE ft1 OPTIONS (ADD streaming_fetch 'true'); +BEGIN; +SELECT count(*) FROM ft1 a; + count +------- + 822 +(1 row) + +SET LOCAL statement_timeout = '10ms'; +SELECT count(*) FROM ft1 a CROSS JOIN ft1 b CROSS JOIN ft1 c CROSS JOIN ft1 d; +ERROR: canceling statement due to statement timeout +COMMIT; +SELECT count(*) FROM ft1; + count +------- + 822 +(1 row) + +ALTER FOREIGN TABLE ft1 OPTIONS (DROP streaming_fetch); diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c index 5b539c4eeef..14e5c5cd32f 100644 --- a/contrib/postgres_fdw/option.c +++ b/contrib/postgres_fdw/option.c @@ -122,6 +122,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS) strcmp(def->defname, "parallel_abort") == 0 || strcmp(def->defname, "keep_connections") == 0 || strcmp(def->defname, "import_stats") == 0 || + strcmp(def->defname, "streaming_fetch") == 0 || strcmp(def->defname, "use_scram_passthrough") == 0) { /* these accept only boolean values */ @@ -262,6 +263,9 @@ InitPgFdwOptions(void) /* fetch_size is available on both server and table */ {"fetch_size", ForeignServerRelationId, false}, {"fetch_size", ForeignTableRelationId, false}, + /* streaming_fetch is available on both server and table */ + {"streaming_fetch", ForeignServerRelationId, false}, + {"streaming_fetch", ForeignTableRelationId, false}, /* batch_size is available on both server and table */ {"batch_size", ForeignServerRelationId, false}, {"batch_size", ForeignTableRelationId, false}, diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index afee95f9b76..6779888aa0b 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -17,10 +17,12 @@ #include "access/htup_details.h" #include "access/sysattr.h" #include "access/table.h" +#include "access/xact.h" #include "catalog/pg_opfamily.h" #include "commands/defrem.h" #include "commands/explain_format.h" #include "commands/explain_state.h" +#include "commands/tablespace.h" #include "commands/vacuum.h" #include "executor/execAsync.h" #include "executor/instrument.h" @@ -44,7 +46,9 @@ #include "pgstat.h" #include "postgres_fdw.h" #include "statistics/statistics.h" +#include "storage/buffile.h" #include "storage/latch.h" +#include "tcop/pquery.h" #include "utils/builtins.h" #include "utils/float.h" #include "utils/fmgroids.h" @@ -52,6 +56,7 @@ #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/rel.h" +#include "utils/resowner.h" #include "utils/sampling.h" #include "utils/selfuncs.h" #include "utils/timestamp.h" @@ -108,6 +113,9 @@ enum FdwScanPrivateIndex * flattens rtables. */ FdwScanPrivateMinRTIndex, + + /* Boolean indicating whether streaming_fetch mode is enabled */ + FdwScanPrivateStreamingFetch, }; /* @@ -207,8 +215,57 @@ typedef struct PgFdwScanState MemoryContext temp_cxt; /* context for per-tuple temporary data */ int fetch_size; /* number of tuples per fetch */ + /* for streaming_fetch mode */ + bool streaming_fetch; /* use streaming_fetch mode? */ + uint64 spool_id; /* see PgFdwSpool; 0 if none */ } PgFdwScanState; +/* + * A spool holds what has been read of a streaming_fetch scan's result but + * not yet returned by the scan. Rows are kept exactly as received: whole + * PGresults while they fit in work_mem, and then as text in a temporary + * file. They are converted only when the scan returns them. + * + * Spools live in transaction-lifespan memory, apart from the scans, and are + * found by a 64-bit ID that is never reused. A connection only records the + * ID of the spool that the result it is carrying belongs to (see + * PgFdwConnState). So a scan's executor state, memory and resource owner + * can go away at any point, e.g. with a cursor that fails while being read in + * a subtransaction, without leaving dangling pointers: its spool is deleted + * at subtransaction abort, and the connection is left with an ID that no + * longer finds anything, so the rest of the result is just thrown away. + */ +typedef struct PgFdwSpool +{ + uint64 id; /* hash key; must be first */ + MemoryContext cxt; /* holds the spool's data and PGresults */ + char *query; /* the remote query, for error messages */ + SubTransactionId subid; /* subtransaction the scan began in */ + Portal portal; /* ActivePortal when the scan began */ + char *portal_name; /* ... and its name */ + bool stream_done; /* has the end of the result been read? */ + bool rows_lost; /* did saving the result fail partway? */ + + /* saved PGresults, while they fit in work_mem */ + List *results; /* PGresults not yet fully returned */ + int result_row; /* next row of linitial(results) */ + Size results_mem; /* memory used by results */ + + /* rows saved beyond work_mem, which come after all of results' */ + BufFile *file; /* owned by TopTransactionResourceOwner */ + int file_nfields; /* number of values per row */ + int64 file_rows_written; + int64 file_rows_read; + int file_read_fileno; /* where to read the next row */ + pgoff_t file_read_offset; + int file_write_fileno; /* where to write the next row */ + pgoff_t file_write_offset; +} PgFdwSpool; + +/* All of the transaction's spools, by ID, in TopTransactionContext */ +static HTAB *spools = NULL; +static uint64 last_spool_id = 0; + /* * Execution state of a foreign insert/update/delete operation. */ @@ -520,6 +577,7 @@ static void estimate_path_cost_size(PlannerInfo *root, Cost *p_startup_cost, Cost *p_total_cost); static void get_remote_estimate(const char *sql, PGconn *conn, + PgFdwConnState *conn_state, double *rows, int *width, Cost *startup_cost, @@ -535,7 +593,9 @@ static void adjust_foreign_grouping_path_cost(PlannerInfo *root, static bool ec_member_matches_foreign(PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, EquivalenceMember *em, void *arg); +static void prepare_query(ForeignScanState *node); static void create_cursor(ForeignScanState *node); +static void reset_batch_state(PgFdwScanState *fsstate); static void fetch_more_data(ForeignScanState *node); static void close_cursor(PGconn *conn, unsigned int cursor_number, PgFdwConnState *conn_state); @@ -601,8 +661,10 @@ static bool fetch_remote_statistics(Relation relation, RemoteStatsResults *remstats, RemoteAttributeMapping **p_remattrmap, int *p_attrcnt); -static PGresult *fetch_relstats(PGconn *conn, Relation relation); -static PGresult *fetch_attstats(PGconn *conn, int server_version_num, +static PGresult *fetch_relstats(PGconn *conn, PgFdwConnState *conn_state, + Relation relation); +static PGresult *fetch_attstats(PGconn *conn, PgFdwConnState *conn_state, + int server_version_num, const char *remote_schemaname, const char *remote_relname, const char *column_list); static RemoteAttributeMapping *build_remattrmap(Relation relation, List *va_cols, @@ -638,6 +700,13 @@ static HeapTuple make_tuple_from_result_row(PGresult *res, List *retrieved_attrs, ForeignScanState *fsstate, MemoryContext temp_context); +static HeapTuple make_tuple_from_strings(const char **valstrs, + int nvals, + Relation rel, + AttInMetadata *attinmeta, + List *retrieved_attrs, + ForeignScanState *fsstate, + MemoryContext temp_context); static void conversion_error_callback(void *arg); static bool foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, RelOptInfo *outerrel, RelOptInfo *innerrel, @@ -670,6 +739,24 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_i); static int get_batch_size_option(Relation rel); +/* streaming_fetch mode support */ +static void init_scan(ForeignScanState *node); +static bool scan_at_eof(PgFdwScanState *fsstate); +static PGresult *fetch_stream_result(PgFdwConnState *conn_state, + PgFdwSpool *spool); +static void discard_stream_result(PgFdwScanState *fsstate); +static void discard_abandoned_result(PgFdwConnState *conn_state); +static void check_stream_rows_lost(PgFdwSpool *spool); +static bool is_active_scan(PgFdwScanState *fsstate); +static void create_spool(PgFdwScanState *fsstate); +static PgFdwSpool *find_spool(uint64 id); +static void delete_spool(uint64 id); +static void reset_spool(PgFdwScanState *fsstate); +static bool spool_has_rows(PgFdwSpool *spool); +static void fetch_spooled_rows(ForeignScanState *node, PgFdwSpool *spool); +static void save_result(PgFdwSpool *spool, PGresult *res); +static HeapTuple read_spooled_row(ForeignScanState *node, PgFdwSpool *spool); +static bool scan_locks_rows(PlannerInfo *root, RelOptInfo *foreignrel); /* * Foreign-data wrapper handler function: return a struct with pointers @@ -779,9 +866,12 @@ postgresGetForeignRelSize(PlannerInfo *root, fpinfo->shippable_extensions = NIL; fpinfo->fetch_size = 100; fpinfo->async_capable = false; + fpinfo->streaming_fetch = false; apply_server_options(fpinfo); apply_table_options(fpinfo); + if (fpinfo->streaming_fetch) + fpinfo->async_capable = false; /* * If the table or the server is configured to use remote estimates, @@ -1372,6 +1462,7 @@ postgresGetForeignPlan(PlannerInfo *root, StringInfoData sql; bool has_final_sort = false; bool has_limit = false; + bool streaming_fetch; ListCell *lc; /* @@ -1537,13 +1628,22 @@ postgresGetForeignPlan(PlannerInfo *root, /* Remember remote_exprs for possible use by postgresPlanDirectModify */ fpinfo->final_remote_exprs = remote_exprs; + /* + * Use a cursor anyway for scans that lock rows, including those under a + * non-direct UPDATE or DELETE: a streamed query would lock every row up + * front, not just the ones fetched. + */ + streaming_fetch = fpinfo->streaming_fetch && + !scan_locks_rows(root, foreignrel); + /* * Build the fdw_private list that will be available to the executor. * Items in the list must match order in enum FdwScanPrivateIndex. */ - fdw_private = list_make3(makeString(sql.data), + fdw_private = list_make4(makeString(sql.data), retrieved_attrs, - makeInteger(fpinfo->fetch_size)); + makeInteger(fpinfo->fetch_size), + makeBoolean(streaming_fetch)); /* * Position FdwScanPrivateRelations: either the EXPLAIN relation string @@ -1759,8 +1859,6 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) */ fsstate->conn = GetConnection(user, false, &fsstate->conn_state); - /* Assign a unique ID for my cursor */ - fsstate->cursor_number = GetCursorNumber(fsstate->conn); fsstate->scan_in_progress = false; /* Get private info created by planner functions. */ @@ -1770,6 +1868,12 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) FdwScanPrivateRetrievedAttrs); fsstate->fetch_size = intVal(list_nth(fsplan->fdw_private, FdwScanPrivateFetchSize)); + fsstate->streaming_fetch = boolVal(list_nth(fsplan->fdw_private, + FdwScanPrivateStreamingFetch)); + + /* Assign a unique ID for my cursor */ + if (!fsstate->streaming_fetch) + fsstate->cursor_number = GetCursorNumber(fsstate->conn); /* Create contexts for batches of tuples and per-tuple temp workspace. */ fsstate->batch_cxt = AllocSetContextCreate(estate->es_query_cxt, @@ -1822,6 +1926,10 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* Set the async-capable flag */ fsstate->async_capable = node->ss.ps.async_capable; + + /* The spool records where the scan began (see PgFdwSpool) */ + if (fsstate->streaming_fetch) + create_spool(fsstate); } /* @@ -1842,7 +1950,12 @@ postgresIterateForeignScan(ForeignScanState *node) * first call after Begin or ReScan. */ if (!fsstate->scan_in_progress) - create_cursor(node); + { + if (fsstate->streaming_fetch) + init_scan(node); + else + create_cursor(node); + } /* * Get some more tuples, if we've run out. @@ -1870,6 +1983,50 @@ postgresIterateForeignScan(ForeignScanState *node) return slot; } +/* + * Reset a scan's batch bookkeeping so the next fetch starts fresh. The + * caller handles scan_in_progress. + */ +static void +reset_batch_state(PgFdwScanState *fsstate) +{ + fsstate->tuples = NULL; + fsstate->num_tuples = 0; + fsstate->next_tuple = 0; + fsstate->fetch_ct_2 = 0; + fsstate->eof_reached = false; +} + +/* + * Does the given foreign scan lock rows on the remote side? This must cover + * every case where deparseLockingClause() adds FOR UPDATE/SHARE; covering a + * few more (e.g. lower subquery rels) only costs an unneeded cursor. + */ +static bool +scan_locks_rows(PlannerInfo *root, RelOptInfo *foreignrel) +{ + int relid = -1; + + if (IS_UPPER_REL(foreignrel)) + return false; + + while ((relid = bms_next_member(foreignrel->relids, relid)) >= 0) + { + PlanRowMark *rc; + + if (bms_is_member(relid, root->all_result_relids) && + (root->parse->commandType == CMD_UPDATE || + root->parse->commandType == CMD_DELETE)) + return true; + + rc = get_plan_rowmark(root->rowMarks, relid); + if (rc && rc->strength != LCS_NONE) + return true; + } + + return false; +} + /* * postgresReScanForeignScan * Restart the scan. @@ -1880,6 +2037,7 @@ postgresReScanForeignScan(ForeignScanState *node) PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state; char sql[64]; PGresult *res; + bool reinitialize_scan = false; /* If no scan is in progress, nothing to do. */ if (!fsstate->scan_in_progress) @@ -1900,43 +2058,67 @@ postgresReScanForeignScan(ForeignScanState *node) * to check the scrollability of it, so destroy and recreate it in any * case. If we've only fetched zero or one batch, we needn't even rewind * the cursor, just rescan what we have. + * + * A streaming_fetch scan can't be rewound, so it is re-run from the + * start, unless it has only read its first batch and saved nothing. */ if (node->ss.ps.chgParam != NULL) - { - fsstate->scan_in_progress = false; - snprintf(sql, sizeof(sql), "CLOSE c%u", - fsstate->cursor_number); - } + reinitialize_scan = true; else if (fsstate->fetch_ct_2 > 1) { - if (PQserverVersion(fsstate->conn) < 150000) + if (!fsstate->streaming_fetch && + PQserverVersion(fsstate->conn) < 150000) + { snprintf(sql, sizeof(sql), "MOVE BACKWARD ALL IN c%u", fsstate->cursor_number); + res = pgfdw_exec_query(fsstate->conn, sql, fsstate->conn_state); + if (PQresultStatus(res) != PGRES_COMMAND_OK) + pgfdw_report_error(res, fsstate->conn, sql); + + PQclear(res); + + /* Now force a fresh FETCH. */ + reset_batch_state(fsstate); + return; + } + else + reinitialize_scan = true; + } + else + { + PgFdwSpool *spool = find_spool(fsstate->spool_id); + + /* + * Easy: just rescan what we already have in memory, if anything. But + * if a drain saved more rows, start over rather than rewind them. + */ + if (spool != NULL && spool_has_rows(spool)) + reinitialize_scan = true; else { - fsstate->scan_in_progress = false; - snprintf(sql, sizeof(sql), "CLOSE c%u", - fsstate->cursor_number); + fsstate->next_tuple = 0; + return; } } - else + if (reinitialize_scan) { - /* Easy: just rescan what we already have in memory, if anything */ - fsstate->next_tuple = 0; - return; + if (fsstate->streaming_fetch) + { + discard_stream_result(fsstate); + } + else + { + snprintf(sql, sizeof(sql), "CLOSE c%u", + fsstate->cursor_number); + res = pgfdw_exec_query(fsstate->conn, sql, fsstate->conn_state); + if (PQresultStatus(res) != PGRES_COMMAND_OK) + pgfdw_report_error(res, fsstate->conn, sql); + PQclear(res); + } + /* Now force a fresh FETCH, and re-open the scan on the next iterate. */ + reset_batch_state(fsstate); + fsstate->scan_in_progress = false; } - - res = pgfdw_exec_query(fsstate->conn, sql, fsstate->conn_state); - if (PQresultStatus(res) != PGRES_COMMAND_OK) - pgfdw_report_error(res, fsstate->conn, sql); - PQclear(res); - - /* Now force a fresh FETCH. */ - fsstate->tuples = NULL; - fsstate->num_tuples = 0; - fsstate->next_tuple = 0; - fsstate->fetch_ct_2 = 0; - fsstate->eof_reached = false; } /* @@ -1952,10 +2134,19 @@ postgresEndForeignScan(ForeignScanState *node) if (fsstate == NULL) return; - /* Close the cursor if open, to prevent accumulation of cursors */ + /* Shut down the remote scan, if one is in progress */ if (fsstate->scan_in_progress) - close_cursor(fsstate->conn, fsstate->cursor_number, - fsstate->conn_state); + { + if (fsstate->streaming_fetch) + discard_stream_result(fsstate); + else + { + close_cursor(fsstate->conn, fsstate->cursor_number, + fsstate->conn_state); + } + } + delete_spool(fsstate->spool_id); + fsstate->spool_id = 0; /* Release remote connection */ ReleaseConnection(fsstate->conn); @@ -3236,9 +3427,14 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) if (es->verbose) { char *sql; + bool streaming_fetch; sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql)); + streaming_fetch = boolVal(list_nth(fdw_private, + FdwScanPrivateStreamingFetch)); ExplainPropertyText("Remote SQL", sql, es); + if (streaming_fetch) + ExplainPropertyBool("Streaming Fetch", true, es); } } @@ -3432,6 +3628,7 @@ estimate_path_cost_size(PlannerInfo *root, List *local_param_join_conds; StringInfoData sql; PGconn *conn; + PgFdwConnState *conn_state; Selectivity local_sel; QualCost local_cost; List *fdw_scan_tlist = NIL; @@ -3475,8 +3672,8 @@ estimate_path_cost_size(PlannerInfo *root, false, &retrieved_attrs, NULL); /* Get the remote estimate */ - conn = GetConnection(fpinfo->user, false, NULL); - get_remote_estimate(sql.data, conn, &rows, &width, + conn = GetConnection(fpinfo->user, false, &conn_state); + get_remote_estimate(sql.data, conn, conn_state, &rows, &width, &startup_cost, &total_cost); ReleaseConnection(conn); @@ -3922,7 +4119,7 @@ estimate_path_cost_size(PlannerInfo *root, * The given "sql" must be an EXPLAIN command. */ static void -get_remote_estimate(const char *sql, PGconn *conn, +get_remote_estimate(const char *sql, PGconn *conn, PgFdwConnState *conn_state, double *rows, int *width, Cost *startup_cost, Cost *total_cost) { @@ -3934,7 +4131,7 @@ get_remote_estimate(const char *sql, PGconn *conn, /* * Execute EXPLAIN remotely. */ - res = pgfdw_exec_query(conn, sql, NULL); + res = pgfdw_exec_query(conn, sql, conn_state); if (PQresultStatus(res) != PGRES_TUPLES_OK) pgfdw_report_error(res, conn, sql); @@ -4041,23 +4238,24 @@ ec_member_matches_foreign(PlannerInfo *root, RelOptInfo *rel, } /* - * Create cursor for node's query with current parameter values. + * Work common to create_cursor() and init_scan(): make the connection idle, + * and convert this scan's parameter values to text. */ static void -create_cursor(ForeignScanState *node) +prepare_query(ForeignScanState *node) { PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state; ExprContext *econtext = node->ss.ps.ps_ExprContext; int numParams = fsstate->numParams; const char **values = fsstate->param_values; - PGconn *conn = fsstate->conn; - StringInfoData buf; - PGresult *res; /* First, process a pending asynchronous request, if any. */ if (fsstate->conn_state->pendingAreq) process_pending_request(fsstate->conn_state->pendingAreq); + /* Likewise, finish any streaming_fetch scan using the connection. */ + drain_active_scan(fsstate->conn_state); + /* * Construct array of query parameter values in text format. We do the * conversions in the short-lived per-tuple context, so as not to cause a @@ -4076,6 +4274,22 @@ create_cursor(ForeignScanState *node) MemoryContextSwitchTo(oldcontext); } +} + +/* + * Create cursor for node's query with current parameter values. + */ +static void +create_cursor(ForeignScanState *node) +{ + PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state; + PGconn *conn = fsstate->conn; + int numParams = fsstate->numParams; + const char **values = fsstate->param_values; + StringInfoData buf; + PGresult *res; + + prepare_query(node); /* Construct the DECLARE CURSOR command */ initStringInfo(&buf); @@ -4114,7 +4328,45 @@ create_cursor(ForeignScanState *node) } /* - * Fetch some more rows from the node's cursor. + * Start the remote query for a streaming_fetch scan in chunked-rows mode; + * the counterpart of create_cursor(). + */ +static void +init_scan(ForeignScanState *node) +{ + PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state; + PGconn *conn = fsstate->conn; + + prepare_query(node); + + /* Rows read from the new stream go to the scan's spool, emptied */ + reset_spool(fsstate); + + if (!PQsendQueryParams(conn, fsstate->query, fsstate->numParams, + NULL, fsstate->param_values, NULL, NULL, 0)) + pgfdw_report_error(NULL, conn, fsstate->query); + + /* Receive the rows in chunks of fetch_size */ + if (!PQsetChunkedRowsMode(conn, fsstate->fetch_size)) + { + pgfdw_cancel_query(fsstate->conn, fsstate->conn_state); + pgfdw_report_error(NULL, conn, fsstate->query); + } + + /* Mark the scan as started, and show no tuples have been retrieved */ + fsstate->scan_in_progress = true; + fsstate->tuples = NULL; + fsstate->num_tuples = 0; + fsstate->next_tuple = 0; + fsstate->fetch_ct_2 = 0; + fsstate->eof_reached = false; + + /* Until the result is consumed, the connection belongs to our spool */ + fsstate->conn_state->active_spool_id = fsstate->spool_id; +} + +/* + * Fetch some more rows from the remote scan. */ static void fetch_more_data(ForeignScanState *node) @@ -4126,14 +4378,18 @@ fetch_more_data(ForeignScanState *node) int i; MemoryContext oldcontext; - /* - * We'll store the tuples in the batch_cxt. First, flush the previous - * batch. - */ fsstate->tuples = NULL; MemoryContextReset(fsstate->batch_cxt); oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt); + /* + * Count every fill of tuples[], whichever branch below supplies it, so + * that rescan knows how to rewind. Counting a fetch that then fails is + * harmless, as the error prevents any rescan. + */ + if (fsstate->fetch_ct_2 < 2) + fsstate->fetch_ct_2++; + if (fsstate->async_capable) { Assert(fsstate->conn_state->pendingAreq); @@ -4150,7 +4406,7 @@ fetch_more_data(ForeignScanState *node) /* Reset per-connection state */ fsstate->conn_state->pendingAreq = NULL; } - else + else if (!fsstate->streaming_fetch) { char sql[64]; @@ -4163,7 +4419,58 @@ fetch_more_data(ForeignScanState *node) if (PQresultStatus(res) != PGRES_TUPLES_OK) pgfdw_report_error(res, conn, fsstate->query); } + else + { + PgFdwSpool *spool = find_spool(fsstate->spool_id); + /* + * The spool can only be missing if abort cleanup deleted it, but then + * the scan should be gone too. + */ + if (spool == NULL) + elog(ERROR, "streaming_fetch spool %" PRIu64 " not found", + fsstate->spool_id); + + /* Don't read past rows that a failed drain consumed but never saved */ + check_stream_rows_lost(spool); + + /* Rows saved by a drain come first */ + if (spool_has_rows(spool)) + { + fetch_spooled_rows(node, spool); + MemoryContextSwitchTo(oldcontext); + return; + } + + if (!is_active_scan(fsstate)) + { + /* + * Nothing saved and nothing to read: EOF, if the stream ended. + * That happens when our last chunk was full, so we didn't know we + * were at EOF, and a drain then found only the end of the stream. + */ + if (spool->stream_done) + { + fsstate->eof_reached = true; + MemoryContextSwitchTo(oldcontext); + return; + } + + /* Otherwise abort cleanup (e.g. ROLLBACK TO SAVEPOINT) ended it */ + ereport(ERROR, + errcode(ERRCODE_INVALID_CURSOR_STATE), + errmsg("could not obtain remaining rows from remote server"), + errdetail("The remote query was canceled when a subtransaction was rolled back.")); + } + + res = fetch_stream_result(fsstate->conn_state, spool); + if (res == NULL) + { + fsstate->eof_reached = true; + MemoryContextSwitchTo(oldcontext); + return; + } + } /* Convert the data into HeapTuples */ numrows = PQntuples(res); fsstate->tuples = palloc0_array(HeapTuple, numrows); @@ -4183,15 +4490,566 @@ fetch_more_data(ForeignScanState *node) fsstate->temp_cxt); } - /* Update fetch_ct_2 */ - if (fsstate->fetch_ct_2 < 2) - fsstate->fetch_ct_2++; + PQclear(res); + + if (fsstate->streaming_fetch) + { + /* + * After a partial chunk, only the end of the stream is left; consume + * it now so the connection is free. (Any unexpected rows would be + * saved.) + */ + if (numrows < fsstate->fetch_size && is_active_scan(fsstate)) + drain_active_scan(fsstate->conn_state); + + /* + * Converting the rows can also run code (e.g. a domain's check) that + * uses this connection, and so drains this very scan. Either way, + * we're at EOF once the stream has ended and nothing is saved. + */ + fsstate->eof_reached = scan_at_eof(fsstate); + } + else + { + /* Must be EOF if we didn't get as many tuples as we asked for. */ + fsstate->eof_reached = (numrows < fsstate->fetch_size); + } + + MemoryContextSwitchTo(oldcontext); +} + +/* + * Is a streaming_fetch scan at EOF: its stream has ended, and its spool has + * no rows left to return? + */ +static bool +scan_at_eof(PgFdwScanState *fsstate) +{ + PgFdwSpool *spool = find_spool(fsstate->spool_id); + + return spool != NULL && spool->stream_done && + !spool_has_rows(spool) && !is_active_scan(fsstate); +} + +/* + * Get the next chunked-rows-mode result of the stream on the connection, + * whose rows belong to the given spool. Returns the result, or NULL once + * the end of the stream has been read. + */ +static PGresult * +fetch_stream_result(PgFdwConnState *conn_state, PgFdwSpool *spool) +{ + PGconn *conn = conn_state->conn; + PGresult *res; + + res = pgfdw_get_next_result(conn); + + if (!res || PQresultStatus(res) == PGRES_FATAL_ERROR) + pgfdw_report_error(res, conn, spool->query); + + /* + * PGRES_TUPLES_OK ends the stream: consume the final NULL, and the + * connection is free again. + */ + if (PQresultStatus(res) == PGRES_TUPLES_OK) + { + /* Ensure that theere are no tuples */ + if (PQntuples(res) != 0); + pgfdw_report_error(res, conn, spool->query); + PQclear(res); + res = pgfdw_get_next_result(conn); + if (res != NULL) + pgfdw_report_error(res, conn, spool->query); + conn_state->active_spool_id = 0; + spool->stream_done = true; + return NULL; + } + + if (PQresultStatus(res) != PGRES_TUPLES_CHUNK) + pgfdw_report_error(res, conn, spool->query); + + return res; +} + +/* + * Consume and discard every remaining chunked-rows result of this scan. + * Used on rescan or early end of scan. We don't cancel the query instead, + * since that would abort the remote transaction. + */ +static void +discard_stream_result(PgFdwScanState *fsstate) +{ + PgFdwSpool *spool; + PGresult *res; + + /* Nothing to do if the stream was already consumed */ + if (!is_active_scan(fsstate)) + return; + + spool = find_spool(fsstate->spool_id); + if (spool == NULL) + { + discard_abandoned_result(fsstate->conn_state); + return; + } + for (;;) + { + CHECK_FOR_INTERRUPTS(); + + res = fetch_stream_result(fsstate->conn_state, spool); + if (res == NULL) + break; + PQclear(res); + } +} + +/* + * Read and throw away the rest of a result whose spool no longer exists, + * because its scan is gone. We can't cancel the query instead, since that + * would abort the remote transaction, which outer transaction levels may + * still be using. If the result ends in an error, the remote transaction is + * aborted anyway, and the next command will report that. + */ +static void +discard_abandoned_result(PgFdwConnState *conn_state) +{ + PGresult *res; + + while ((res = pgfdw_get_next_result(conn_state->conn)) != NULL) + PQclear(res); + conn_state->active_spool_id = 0; +} + +/* + * Error out if a failed drain may have lost some of the scan's rows, rather + * than silently return short results. + */ +static void +check_stream_rows_lost(PgFdwSpool *spool) +{ + if (spool->rows_lost) + ereport(ERROR, + errcode(ERRCODE_INVALID_CURSOR_STATE), + errmsg("could not obtain all rows from remote server"), + errdetail("An earlier error interrupted reading the remote query's result.")); +} - /* Must be EOF if we didn't get as many tuples as we asked for. */ - fsstate->eof_reached = (numrows < fsstate->fetch_size); +/* + * Return true if fsstate is the scan whose result the connection is + * currently carrying. + */ +static bool +is_active_scan(PgFdwScanState *fsstate) +{ + return fsstate->streaming_fetch && fsstate->spool_id != 0 && + fsstate->conn_state->active_spool_id == fsstate->spool_id; +} + +/* + * Create the scan's spool when the scan begins, recording the subtransaction + * and portal it began in, and set its spool_id. + */ +static void +create_spool(PgFdwScanState *fsstate) +{ + MemoryContext cxt; + PgFdwSpool *spool; + uint64 id; + + if (spools == NULL) + { + HASHCTL ctl; + + ctl.keysize = sizeof(uint64); + ctl.entrysize = sizeof(PgFdwSpool); + ctl.hcxt = TopTransactionContext; + spools = hash_create("postgres_fdw spools", 16, &ctl, + HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); + } + + cxt = AllocSetContextCreate(TopTransactionContext, + "postgres_fdw spool", + ALLOCSET_DEFAULT_SIZES); + id = ++last_spool_id; + spool = hash_search(spools, &id, HASH_ENTER, NULL); + memset(spool, 0, sizeof(PgFdwSpool)); + spool->id = id; + spool->cxt = cxt; + spool->query = MemoryContextStrdup(cxt, fsstate->query); + spool->subid = GetCurrentSubTransactionId(); + spool->portal = ActivePortal; + if (ActivePortal) + spool->portal_name = MemoryContextStrdup(cxt, ActivePortal->name); + + fsstate->spool_id = id; +} + +/* + * Find a spool by ID; NULL if it doesn't exist (any more). + */ +static PgFdwSpool * +find_spool(uint64 id) +{ + if (spools == NULL || id == 0) + return NULL; + return (PgFdwSpool *) hash_search(spools, &id, HASH_FIND, NULL); +} + +/* + * Delete a spool, and everything saved in it. It's fine if it doesn't + * exist. A connection may still be reading a result into it; that result + * will be discarded instead. + */ +static void +delete_spool(uint64 id) +{ + PgFdwSpool *spool = find_spool(id); + + if (spool == NULL) + return; + if (spool->file) + BufFileClose(spool->file); + MemoryContextDelete(spool->cxt); /* frees the PGresults too */ + hash_search(spools, &id, HASH_REMOVE, NULL); +} + +/* + * Empty the scan's spool, ready for a new stream. + */ +static void +reset_spool(PgFdwScanState *fsstate) +{ + PgFdwSpool *spool = find_spool(fsstate->spool_id); + ListCell *lc; + + /* Only abort cleanup deletes a spool, and then the scan is gone too */ + if (spool == NULL) + elog(ERROR, "streaming_fetch spool %" PRIu64 " not found", + fsstate->spool_id); + + foreach(lc, spool->results) + PQclear((PGresult *) lfirst(lc)); + list_free(spool->results); + spool->results = NIL; + spool->result_row = 0; + spool->results_mem = 0; + + if (spool->file) + BufFileClose(spool->file); + spool->file = NULL; + spool->file_rows_written = spool->file_rows_read = 0; + spool->file_read_fileno = spool->file_write_fileno = 0; + spool->file_read_offset = spool->file_write_offset = 0; + + spool->stream_done = false; + spool->rows_lost = false; +} + +/* + * Subtransaction end: delete the spools of scans that began in an aborted + * subtransaction, or whose portal has failed (e.g. a cursor from an outer + * level that failed while being read in it) or is gone. At commit, spools + * just move to the parent subtransaction. + */ +void +pgfdw_spools_at_subxact_end(bool isCommit, SubTransactionId mySubid, + SubTransactionId parentSubid) +{ + HASH_SEQ_STATUS status; + PgFdwSpool *spool; + + if (spools == NULL) + return; + + hash_seq_init(&status, spools); + while ((spool = hash_seq_search(&status)) != NULL) + { + bool drop; + + if (isCommit) + { + if (spool->subid == mySubid) + spool->subid = parentSubid; + continue; + } + + drop = (spool->subid == mySubid); + if (!drop && spool->portal != NULL) + { + Portal portal = GetPortalByName(spool->portal_name); + + drop = (portal != spool->portal || + portal->status == PORTAL_FAILED); + } + if (drop) + delete_spool(spool->id); + } +} + +/* + * Transaction end: delete all spools. Normally every scan has deleted its + * own by now. + */ +void +pgfdw_spools_at_xact_end(void) +{ + HASH_SEQ_STATUS status; + PgFdwSpool *spool; + + if (spools == NULL) + return; + + /* Close the files; the memory goes with TopTransactionContext */ + hash_seq_init(&status, spools); + while ((spool = hash_seq_search(&status)) != NULL) + { + if (spool->file) + BufFileClose(spool->file); + } + spools = NULL; +} + +/* + * Does the spool have rows that haven't been returned yet? + */ +static bool +spool_has_rows(PgFdwSpool *spool) +{ + return spool->results != NIL || + spool->file_rows_read < spool->file_rows_written; +} + +/* + * Return the next batch of up to fetch_size of the rows saved in the spool: + * first those in saved PGresults, then those in the file. The rows are + * saved unconverted, so this is where they are converted, as part of the + * scan's own execution. + */ +static void +fetch_spooled_rows(ForeignScanState *node, PgFdwSpool *spool) +{ + PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state; + int numrows = 0; + + /* The tuples are built in the caller's context, batch_cxt */ + fsstate->tuples = palloc0_array(HeapTuple, fsstate->fetch_size); + while (numrows < fsstate->fetch_size) + { + if (spool->results != NIL) + { + PGresult *res = (PGresult *) linitial(spool->results); + + if (spool->result_row < PQntuples(res)) + { + fsstate->tuples[numrows++] = + make_tuple_from_result_row(res, spool->result_row++, + fsstate->rel, + fsstate->attinmeta, + fsstate->retrieved_attrs, + node, + fsstate->temp_cxt); + continue; + } + /* Done with this PGresult */ + spool->results = list_delete_first(spool->results); + spool->results_mem -= PQresultMemorySize(res->res); + spool->result_row = 0; + PQclear(res); + } + else if (spool->file_rows_read < spool->file_rows_written) + fsstate->tuples[numrows++] = read_spooled_row(node, spool); + else + break; + } + fsstate->num_tuples = numrows; + fsstate->next_tuple = 0; + + /* Close the file once everything in it has been returned */ + if (!spool_has_rows(spool) && spool->file) + { + BufFileClose(spool->file); + spool->file = NULL; + spool->file_rows_written = spool->file_rows_read = 0; + } + + fsstate->eof_reached = scan_at_eof(fsstate); +} + +/* + * Save one chunk of a stream's result in its spool, unconverted. The + * PGresult itself is kept while the spool's results fit in work_mem; beyond + * that, its rows are written to the spool's file as text, and it is freed. + * After the first spill, everything goes to the file, so that the rows stay + * in order. + * + * Each row is written as its values in order, each an int32 length (-1 for + * NULL) followed by that many bytes. + * + * The caller must have made the spool's memory context current, so that the + * PGresult belongs to it, and TopTransactionResourceOwner the current resource + * owner, so that the file does. + */ +static void +save_result(PgFdwSpool *spool, PGresult *res) +{ + Size size = PQresultMemorySize(res->res); + int nfields = PQnfields(res); + int ntuples = PQntuples(res); + + if (spool->file == NULL && + spool->results_mem + size <= (Size) work_mem * 1024) + { + spool->results = lappend(spool->results, res); + spool->results_mem += size; + return; + } + + if (spool->file == NULL) + { + PrepareTempTablespaces(); + spool->file = BufFileCreateTemp(false); + spool->file_nfields = nfields; + } + else if (nfields != spool->file_nfields) + elog(ERROR, "remote query result does not match the foreign table"); + + if (BufFileSeek(spool->file, spool->file_write_fileno, + spool->file_write_offset, SEEK_SET) != 0) + elog(ERROR, "could not seek in postgres_fdw temporary file"); + + for (int i = 0; i < ntuples; i++) + { + for (int k = 0; k < nfields; k++) + { + int32 len; + + len = PQgetisnull(res, i, k) ? -1 : PQgetlength(res, i, k); + BufFileWrite(spool->file, &len, sizeof(len)); + if (len > 0) + BufFileWrite(spool->file, PQgetvalue(res, i, k), len); + } + spool->file_rows_written++; + } + + BufFileTell(spool->file, &spool->file_write_fileno, + &spool->file_write_offset); PQclear(res); +} + +/* + * Read the next row from the spool's file, and convert it to a tuple. + */ +static HeapTuple +read_spooled_row(ForeignScanState *node, PgFdwSpool *spool) +{ + PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state; + int nfields = spool->file_nfields; + const char **valstrs; + MemoryContext oldcontext; + + if (BufFileSeek(spool->file, spool->file_read_fileno, + spool->file_read_offset, SEEK_SET) != 0) + elog(ERROR, "could not seek in postgres_fdw temporary file"); + + /* make_tuple_from_strings() resets temp_cxt when it's done */ + oldcontext = MemoryContextSwitchTo(fsstate->temp_cxt); + valstrs = palloc_array(const char *, nfields); + for (int k = 0; k < nfields; k++) + { + int32 len; + char *val; + + BufFileReadExact(spool->file, &len, sizeof(len)); + if (len < 0) + { + valstrs[k] = NULL; + continue; + } + val = palloc(len + 1); + if (len > 0) + BufFileReadExact(spool->file, val, len); + val[len] = '\0'; + valstrs[k] = val; + } + MemoryContextSwitchTo(oldcontext); + + BufFileTell(spool->file, &spool->file_read_fileno, + &spool->file_read_offset); + spool->file_rows_read++; + + return make_tuple_from_strings(valstrs, nfields, + fsstate->rel, + fsstate->attinmeta, + fsstate->retrieved_attrs, + node, + fsstate->temp_cxt); +} +/* + * A connection can carry only one query result at a time. If a + * streaming_fetch scan's result is still being read, save the rest of it in + * the scan's spool, so that the connection can be used for something else. + * Every path that sends a query must call this first. + * + * This can happen in the middle of an unrelated statement, as a different + * user, or in a transaction callback, so it must not run any user-defined + * code: rows are saved as received, and converted only when the scan + * returns them. It also doesn't need the scan itself, which may be gone: + * then its spool is gone too, and the rest of the result is thrown away. + */ +void +drain_active_scan(PgFdwConnState *conn_state) +{ + PgFdwSpool *spool; + MemoryContext oldcontext; + ResourceOwner oldowner; + bool rows_already_lost; + + if (conn_state->active_spool_id == 0) + return; + + spool = find_spool(conn_state->active_spool_id); + if (spool == NULL) + { + discard_abandoned_result(conn_state); + return; + } + + /* Rows lost by an earlier failed drain stay lost */ + rows_already_lost = spool->rows_lost; + + /* See save_result() */ + oldcontext = MemoryContextSwitchTo(spool->cxt); + oldowner = CurrentResourceOwner; + CurrentResourceOwner = TopTransactionResourceOwner; + + /* Save each chunk until fetch_stream_result() reports the end */ + for (;;) + { + PGresult *res; + + CHECK_FOR_INTERRUPTS(); + + /* + * An error before this chunk is fully saved loses rows, and may abort + * only a subtransaction, leaving the scan readable at an outer level. + * Flag that until the chunk is saved. + */ + spool->rows_lost = true; + + res = fetch_stream_result(conn_state, spool); + if (res == NULL) + { + spool->rows_lost = rows_already_lost; + break; + } + + save_result(spool, res); + spool->rows_lost = rows_already_lost; + } + + CurrentResourceOwner = oldowner; MemoryContextSwitchTo(oldcontext); } @@ -4419,6 +5277,9 @@ execute_foreign_modify(EState *estate, if (fmstate->conn_state->pendingAreq) process_pending_request(fmstate->conn_state->pendingAreq); + /* Likewise, finish any streaming_fetch scan using the connection. */ + drain_active_scan(fmstate->conn_state); + /* * If the existing query was deparsed and prepared for a different number * of rows, rebuild it for the proper number. @@ -4845,6 +5706,9 @@ execute_dml_stmt(ForeignScanState *node) if (dmstate->conn_state->pendingAreq) process_pending_request(dmstate->conn_state->pendingAreq); + /* Likewise, finish any streaming_fetch scan using the connection. */ + drain_active_scan(dmstate->conn_state); + /* * Construct array of query parameter values in text format. */ @@ -5215,6 +6079,7 @@ postgresAnalyzeForeignTable(Relation relation, ForeignTable *table; UserMapping *user; PGconn *conn; + PgFdwConnState *conn_state; StringInfoData sql; PGresult *res; @@ -5234,7 +6099,7 @@ postgresAnalyzeForeignTable(Relation relation, */ table = GetForeignTable(RelationGetRelid(relation)); user = GetUserMapping(relation->rd_rel->relowner, table->serverid); - conn = GetConnection(user, false, NULL); + conn = GetConnection(user, false, &conn_state); /* * Construct command to get page count for relation. @@ -5242,7 +6107,7 @@ postgresAnalyzeForeignTable(Relation relation, initStringInfo(&sql); deparseAnalyzeSizeSql(&sql, relation); - res = pgfdw_exec_query(conn, sql.data, NULL); + res = pgfdw_exec_query(conn, sql.data, conn_state); if (PQresultStatus(res) != PGRES_TUPLES_OK) pgfdw_report_error(res, conn, sql.data); @@ -5269,6 +6134,7 @@ postgresGetAnalyzeInfoForForeignTable(Relation relation, bool *can_tablesample) ForeignTable *table; UserMapping *user; PGconn *conn; + PgFdwConnState *conn_state; StringInfoData sql; PGresult *res; double reltuples; @@ -5283,7 +6149,7 @@ postgresGetAnalyzeInfoForForeignTable(Relation relation, bool *can_tablesample) */ table = GetForeignTable(RelationGetRelid(relation)); user = GetUserMapping(relation->rd_rel->relowner, table->serverid); - conn = GetConnection(user, false, NULL); + conn = GetConnection(user, false, &conn_state); /* * Construct command to get page count for relation. @@ -5291,7 +6157,7 @@ postgresGetAnalyzeInfoForForeignTable(Relation relation, bool *can_tablesample) initStringInfo(&sql); deparseAnalyzeInfoSql(&sql, relation); - res = pgfdw_exec_query(conn, sql.data, NULL); + res = pgfdw_exec_query(conn, sql.data, conn_state); if (PQresultStatus(res) != PGRES_TUPLES_OK) pgfdw_report_error(res, conn, sql.data); @@ -5337,6 +6203,7 @@ postgresAcquireSampleRowsFunc(Relation relation, int elevel, ForeignServer *server; UserMapping *user; PGconn *conn; + PgFdwConnState *conn_state; int server_version_num; PgFdwSamplingMethod method = ANALYZE_SAMPLE_AUTO; /* auto is default */ double sample_frac = -1.0; @@ -5372,7 +6239,7 @@ postgresAcquireSampleRowsFunc(Relation relation, int elevel, table = GetForeignTable(RelationGetRelid(relation)); server = GetForeignServer(table->serverid); user = GetUserMapping(relation->rd_rel->relowner, table->serverid); - conn = GetConnection(user, false, NULL); + conn = GetConnection(user, false, &conn_state); /* We'll need server version, so fetch it now. */ server_version_num = PQserverVersion(conn); @@ -5522,7 +6389,7 @@ postgresAcquireSampleRowsFunc(Relation relation, int elevel, deparseAnalyzeSql(&sql, relation, method, sample_frac, &astate.retrieved_attrs); - res = pgfdw_exec_query(conn, sql.data, NULL); + res = pgfdw_exec_query(conn, sql.data, conn_state); if (PQresultStatus(res) != PGRES_COMMAND_OK) pgfdw_report_error(res, conn, sql.data); PQclear(res); @@ -5573,7 +6440,7 @@ postgresAcquireSampleRowsFunc(Relation relation, int elevel, */ /* Fetch some rows */ - res = pgfdw_exec_query(conn, fetch_sql, NULL); + res = pgfdw_exec_query(conn, fetch_sql, conn_state); /* On error, report the original query, not the FETCH. */ if (PQresultStatus(res) != PGRES_TUPLES_OK) pgfdw_report_error(res, conn, sql.data); @@ -5591,7 +6458,7 @@ postgresAcquireSampleRowsFunc(Relation relation, int elevel, } /* Close the cursor, just to be tidy. */ - close_cursor(conn, cursor_number, NULL); + close_cursor(conn, cursor_number, conn_state); ReleaseConnection(conn); @@ -5807,6 +6674,7 @@ fetch_remote_statistics(Relation relation, const char *remote_relname = NULL; UserMapping *user; PGconn *conn; + PgFdwConnState *conn_state; PGresult *relstats = NULL; PGresult *attstats = NULL; int server_version_num; @@ -5838,11 +6706,11 @@ fetch_remote_statistics(Relation relation, * from ImportForeignStatistics(). */ user = GetUserMapping(GetUserId(), table->serverid); - conn = GetConnection(user, false, NULL); + conn = GetConnection(user, false, &conn_state); remstats->version = server_version_num = PQserverVersion(conn); /* Fetch relation stats. */ - remstats->rel = relstats = fetch_relstats(conn, relation); + remstats->rel = relstats = fetch_relstats(conn, conn_state, relation); /* * Verify that the remote table is the sort that can have meaningful stats @@ -5928,7 +6796,7 @@ fetch_remote_statistics(Relation relation, } /* Fetch attribute stats. */ - remstats->att = attstats = fetch_attstats(conn, + remstats->att = attstats = fetch_attstats(conn, conn_state, server_version_num, remote_schemaname, remote_relname, @@ -5976,7 +6844,8 @@ fetch_cleanup: * Attempt to fetch remote relation stats. */ static PGresult * -fetch_relstats(PGconn *conn, Relation relation) +fetch_relstats(PGconn *conn, PgFdwConnState *conn_state, + Relation relation) { StringInfoData sql; PGresult *res; @@ -5984,7 +6853,7 @@ fetch_relstats(PGconn *conn, Relation relation) initStringInfo(&sql); deparseAnalyzeInfoSql(&sql, relation); - res = pgfdw_exec_query(conn, sql.data, NULL); + res = pgfdw_exec_query(conn, sql.data, conn_state); if (PQresultStatus(res) != PGRES_TUPLES_OK) pgfdw_report_error(res, conn, sql.data); @@ -5998,7 +6867,8 @@ fetch_relstats(PGconn *conn, Relation relation) * Attempt to fetch remote attribute stats. */ static PGresult * -fetch_attstats(PGconn *conn, int server_version_num, +fetch_attstats(PGconn *conn, PgFdwConnState *conn_state, + int server_version_num, const char *remote_schemaname, const char *remote_relname, const char *column_list) { @@ -6072,7 +6942,7 @@ fetch_attstats(PGconn *conn, int server_version_num, appendStringInfoString(&sql, " ORDER BY attname::text COLLATE \"C\", inherited DESC"); - res = pgfdw_exec_query(conn, sql.data, NULL); + res = pgfdw_exec_query(conn, sql.data, conn_state); if (PQresultStatus(res) != PGRES_TUPLES_OK) pgfdw_report_error(res, conn, sql.data); @@ -6526,6 +7396,7 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid) ForeignServer *server; UserMapping *mapping; PGconn *conn; + PgFdwConnState *conn_state; StringInfoData buf; PGresult *res; int numrows, @@ -6557,7 +7428,7 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid) */ server = GetForeignServer(serverOid); mapping = GetUserMapping(GetUserId(), server->serverid); - conn = GetConnection(mapping, false, NULL); + conn = GetConnection(mapping, false, &conn_state); /* Don't attempt to import collation if remote server hasn't got it */ if (PQserverVersion(conn) < 90100) @@ -6570,7 +7441,7 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid) appendStringInfoString(&buf, "SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = "); deparseStringLiteral(&buf, stmt->remote_schema); - res = pgfdw_exec_query(conn, buf.data, NULL); + res = pgfdw_exec_query(conn, buf.data, conn_state); if (PQresultStatus(res) != PGRES_TUPLES_OK) pgfdw_report_error(res, conn, buf.data); @@ -6684,7 +7555,7 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid) appendStringInfoString(&buf, " ORDER BY c.relname, a.attnum"); /* Fetch the data */ - res = pgfdw_exec_query(conn, buf.data, NULL); + res = pgfdw_exec_query(conn, buf.data, conn_state); if (PQresultStatus(res) != PGRES_TUPLES_OK) pgfdw_report_error(res, conn, buf.data); @@ -7601,6 +8472,8 @@ apply_server_options(PgFdwRelationInfo *fpinfo) (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL); else if (strcmp(def->defname, "async_capable") == 0) fpinfo->async_capable = defGetBoolean(def); + else if (strcmp(def->defname, "streaming_fetch") == 0) + fpinfo->streaming_fetch = defGetBoolean(def); } } @@ -7624,6 +8497,8 @@ apply_table_options(PgFdwRelationInfo *fpinfo) (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL); else if (strcmp(def->defname, "async_capable") == 0) fpinfo->async_capable = defGetBoolean(def); + else if (strcmp(def->defname, "streaming_fetch") == 0) + fpinfo->streaming_fetch = defGetBoolean(def); } } @@ -7659,6 +8534,7 @@ merge_fdw_options(PgFdwRelationInfo *fpinfo, fpinfo->use_remote_estimate = fpinfo_o->use_remote_estimate; fpinfo->fetch_size = fpinfo_o->fetch_size; fpinfo->async_capable = fpinfo_o->async_capable; + fpinfo->streaming_fetch = fpinfo_o->streaming_fetch; /* Merge the table level options from either side of the join. */ if (fpinfo_i) @@ -7690,6 +8566,11 @@ merge_fdw_options(PgFdwRelationInfo *fpinfo, */ fpinfo->async_capable = fpinfo_o->async_capable || fpinfo_i->async_capable; + fpinfo->streaming_fetch = fpinfo_o->streaming_fetch || + fpinfo_i->streaming_fetch; + /* streaming_fetch and async execution are mutually exclusive */ + if (fpinfo->streaming_fetch) + fpinfo->async_capable = false; } } @@ -8844,6 +9725,9 @@ fetch_more_data_begin(AsyncRequest *areq) if (!fsstate->scan_in_progress) create_cursor(node); + /* PQsendQuery() below doesn't drain a streaming_fetch scan; do it here */ + drain_active_scan(fsstate->conn_state); + /* We will send this query, but not wait for the response. */ snprintf(sql, sizeof(sql), "FETCH %d FROM c%u", fsstate->fetch_size, fsstate->cursor_number); @@ -8933,6 +9817,42 @@ make_tuple_from_result_row(PGresult *res, List *retrieved_attrs, ForeignScanState *fsstate, MemoryContext temp_context) +{ + int nfields = PQnfields(res); + const char **valstrs; + MemoryContext oldcontext; + int j; + + Assert(row < PQntuples(res)); + + /* make_tuple_from_strings() resets temp_context when it's done */ + oldcontext = MemoryContextSwitchTo(temp_context); + valstrs = palloc_array(const char *, nfields); + for (j = 0; j < nfields; j++) + valstrs[j] = PQgetisnull(res, row, j) ? NULL : PQgetvalue(res, row, j); + MemoryContextSwitchTo(oldcontext); + + return make_tuple_from_strings(valstrs, nfields, rel, attinmeta, + retrieved_attrs, fsstate, temp_context); +} + +/* + * Create a tuple from the textual values of one remote row, as received + * (valstrs[j] is the j'th column of the remote query's result, or NULL). + * The other arguments are as for make_tuple_from_result_row(). + * + * This runs the columns' input functions, which can execute arbitrary code + * (e.g. a domain's CHECK constraints), so it must only be called while the + * scan itself is executing. + */ +static HeapTuple +make_tuple_from_strings(const char **valstrs, + int nvals, + Relation rel, + AttInMetadata *attinmeta, + List *retrieved_attrs, + ForeignScanState *fsstate, + MemoryContext temp_context) { HeapTuple tuple; TupleDesc tupdesc; @@ -8945,8 +9865,6 @@ make_tuple_from_result_row(PGresult *res, ListCell *lc; int j; - Assert(row < PQntuples(res)); - /* * Do the following work in a temp context that we reset after each tuple. * This cleans up not only the data we have direct access to, but any @@ -8992,10 +9910,9 @@ make_tuple_from_result_row(PGresult *res, const char *valstr; /* fetch next column's textual value */ - if (PQgetisnull(res, row, j)) - valstr = NULL; - else - valstr = PQgetvalue(res, row, j); + if (j >= nvals) + elog(ERROR, "remote query result does not match the foreign table"); + valstr = valstrs[j]; /* * convert value to internal representation @@ -9034,10 +9951,10 @@ make_tuple_from_result_row(PGresult *res, error_context_stack = errcallback.previous; /* - * Check we got the expected number of columns. Note: j == 0 and - * PQnfields == 1 is expected, since deparse emits a NULL if no columns. + * Check we got the expected number of columns. Note: j == 0 with a + * single value is expected, since deparse emits a NULL if no columns. */ - if (j > 0 && j != PQnfields(res)) + if (j > 0 && j != nvals) elog(ERROR, "remote query result does not match the foreign table"); /* diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index da7da1c2ea9..6de6c9f0f9f 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -88,6 +88,7 @@ typedef struct PgFdwRelationInfo UserMapping *user; /* only set in use_remote_estimate mode */ int fetch_size; /* fetch size for this remote table */ + bool streaming_fetch; /* true if cursor-free fetch is enabled */ /* * Name of the relation, for use while EXPLAINing ForeignScan. It is used @@ -146,7 +147,11 @@ typedef struct PgFdwRelationInfo */ typedef struct PgFdwConnState { + PGconn *conn; /* the connection this state belongs to */ AsyncRequest *pendingAreq; /* pending async request */ + uint64 active_spool_id; /* if not 0, a streaming_fetch result is + * being read on this connection, and this + * is the ID of the spool it belongs to */ } PgFdwConnState; /* @@ -165,6 +170,11 @@ typedef enum PgFdwSamplingMethod extern int set_transmission_modes(void); extern void reset_transmission_modes(int nestlevel); extern void process_pending_request(AsyncRequest *areq); +extern void drain_active_scan(PgFdwConnState *conn_state); +extern void pgfdw_spools_at_subxact_end(bool isCommit, + SubTransactionId mySubid, + SubTransactionId parentSubid); +extern void pgfdw_spools_at_xact_end(void); /* in connection.c */ extern PGconn *GetConnection(UserMapping *user, bool will_prep_stmt, @@ -174,8 +184,10 @@ extern unsigned int GetCursorNumber(PGconn *conn); extern unsigned int GetPrepStmtNumber(PGconn *conn); extern void do_sql_command(PGconn *conn, const char *sql); extern PGresult *pgfdw_get_result(PGconn *conn); +extern PGresult *pgfdw_get_next_result(PGconn *conn); extern PGresult *pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state); +extern bool pgfdw_cancel_query(PGconn *conn, PgFdwConnState *state); pg_noreturn extern void pgfdw_report_error(PGresult *res, PGconn *conn, const char *sql); extern void pgfdw_report(int elevel, PGresult *res, PGconn *conn, diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 77c9a25a890..f9a98369738 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -244,6 +244,26 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again ANALYZE ft1; ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true'); +-- =================================================================== +-- test streaming_fetch option +-- =================================================================== +CREATE SERVER fetch_stream_srv FOREIGN DATA WRAPPER postgres_fdw + OPTIONS (streaming_fetch 'true'); +CREATE USER MAPPING FOR CURRENT_USER SERVER fetch_stream_srv; +CREATE FOREIGN TABLE ft_stream (c1 int) SERVER fetch_stream_srv; +-- Set on the server; EXPLAIN VERBOSE shows "Streaming Fetch: true". +EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_stream; +-- A table-level setting overrides the server's, in either direction. +ALTER FOREIGN TABLE ft_stream OPTIONS (ADD streaming_fetch 'false'); +EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_stream; +ALTER SERVER fetch_stream_srv OPTIONS (SET streaming_fetch 'false'); +ALTER FOREIGN TABLE ft_stream OPTIONS (SET streaming_fetch 'true'); +EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_stream; +ALTER FOREIGN TABLE ft_stream OPTIONS (SET streaming_fetch 'yes'); -- ERROR +DROP FOREIGN TABLE ft_stream; +DROP USER MAPPING FOR CURRENT_USER SERVER fetch_stream_srv; +DROP SERVER fetch_stream_srv; + -- =================================================================== -- test subscription -- =================================================================== @@ -363,6 +383,374 @@ EXPLAIN (VERBOSE, COSTS OFF) WHERE a.c2 = 6 AND b.c1 = a.c1 AND a.c8 = 'foo' AND b.c7 = upper(a.c7); SELECT * FROM ft2 a, ft2 b WHERE a.c2 = 6 AND b.c1 = a.c1 AND a.c8 = 'foo' AND b.c7 = upper(a.c7); + +-- =================================================================== +-- streaming_fetch scans sharing a connection +-- =================================================================== +-- ft1_s and ft2_s stream the same remote table as ft1 and ft2, and all four +-- share the loopback connection. ft2_s gets its rows in chunks of 5. +CREATE FOREIGN TABLE ft1_s ( + c1 int NOT NULL, + c2 int NOT NULL, + c3 text, + c4 timestamptz, + c5 timestamp, + c6 varchar(10), + c7 char(10) default 'ft1', + c8 user_enum +) SERVER loopback OPTIONS (schema_name 'S 1', table_name 'T 1', + streaming_fetch 'true'); +ALTER FOREIGN TABLE ft1_s ALTER COLUMN c1 OPTIONS (column_name 'C 1'); +CREATE FOREIGN TABLE ft2_s ( + c1 int NOT NULL, + c2 int NOT NULL, + c3 text, + c4 timestamptz, + c5 timestamp, + c6 varchar(10), + c7 char(10) default 'ft2', + c8 user_enum +) SERVER loopback OPTIONS (schema_name 'S 1', table_name 'T 1', + streaming_fetch 'true', fetch_size '5', + use_remote_estimate 'true'); +ALTER FOREIGN TABLE ft2_s ALTER COLUMN c1 OPTIONS (column_name 'C 1'); + +-- Nested loops: each time the inner scan starts, the rest of the outer +-- scan's result is saved locally, and later read back in fetch_size batches. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM ft2_s a, ft2_s b +WHERE a.c2 = 6 AND b.c1 = a.c1 AND a.c8 = 'foo' AND b.c7 = upper(a.c7); +SELECT count(*), sum(b.c1) FROM ft2_s a, ft2_s b +WHERE a.c2 = 6 AND b.c1 = a.c1 AND a.c8 = 'foo' AND b.c7 = upper(a.c7); + +-- An EXISTS subquery stops its streaming scan at the first match, leaving +-- the rest of its result unread. The connection must still work for the +-- outer cursor's later FETCHes (ft1 needs several with fetch_size 5), for a +-- per-row UPDATE, and for a pushed-down UPDATE on ft4. +CREATE FUNCTION direct_modify_ft4(id int) RETURNS void AS $$ + UPDATE ft4 SET c3 = c3 WHERE c1 = id; +$$ LANGUAGE sql; +ALTER FOREIGN TABLE ft1 OPTIONS (ADD fetch_size '5'); +SET enable_hashagg = off; +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_material = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT a.c1, a.c2 FROM ft1 a +WHERE a.c1 < 20 AND a.c8 = 'foo' AND EXISTS (SELECT 1 FROM ft2_s b WHERE b.c2 = a.c2) +ORDER BY a.c1; +SELECT a.c1, a.c2 FROM ft1 a +WHERE a.c1 < 20 AND a.c8 = 'foo' AND EXISTS (SELECT 1 FROM ft2_s b WHERE b.c2 = a.c2) +ORDER BY a.c1; +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE ft1 SET c3 = c3 +WHERE c1 < 20 AND c8 = 'foo' AND EXISTS (SELECT 1 FROM ft2_s b WHERE b.c2 = ft1.c2); +EXPLAIN (VERBOSE, COSTS OFF) UPDATE ft4 SET c3 = c3 WHERE c1 = 1; +BEGIN; +WITH u AS (UPDATE ft1 SET c3 = c3 + WHERE c1 < 20 AND c8 = 'foo' AND EXISTS (SELECT 1 FROM ft2_s b WHERE b.c2 = ft1.c2) + RETURNING c1) +SELECT count(*) FROM u; +SELECT count(*) FROM (SELECT direct_modify_ft4(a.c1) FROM ft1 a + WHERE a.c1 < 20 AND a.c8 = 'foo' AND EXISTS (SELECT 1 FROM ft2_s b WHERE b.c2 = a.c2) + OFFSET 0) s; +ROLLBACK; +-- A rescan of a scan that gets no new parameters (here, the outer row is +-- only used above it) replays the chunk it has in memory; but once one of +-- the outer cursor's FETCHes has saved the rest of its result, it is re-run. +SET enable_memoize = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT a.c1, s.c1 FROM ft1 a, + LATERAL (SELECT b.c1 FROM (SELECT c1, c2 FROM ft2_s OFFSET 0) b + WHERE b.c2 = a.c2 LIMIT 1) s +WHERE a.c1 < 20; +SELECT count(*) FROM ft1 a, + LATERAL (SELECT b.c1 FROM (SELECT c1, c2 FROM ft2_s OFFSET 0) b + WHERE b.c2 = a.c2 LIMIT 1) s +WHERE a.c1 < 20; +RESET enable_memoize; +RESET enable_hashagg; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_material; +ALTER FOREIGN TABLE ft1 OPTIONS (DROP fetch_size); +DROP FUNCTION direct_modify_ft4(int); + +-- Scans that lock rows, including those under a non-direct UPDATE or DELETE, +-- use a cursor (no "Streaming Fetch"). +EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft2_s WHERE c1 = 1 FOR UPDATE; +EXPLAIN (VERBOSE, COSTS OFF) DELETE FROM ft2_s WHERE c1 = 1 AND random() >= 0; +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE ft2_s f1 SET c3 = f2.c3 FROM ft1_s f2 +WHERE f1.c1 = f2.c1 AND f1.c1 = 3 AND random() >= 0; + +-- A scan that fetches ctid without locking rows streams, and the ctid of +-- rows saved by a drain (6 to 12) is kept. +EXPLAIN (VERBOSE, COSTS OFF) SELECT c1, ctid FROM ft2_s WHERE c1 <= 12; +BEGIN; +DECLARE c CURSOR FOR SELECT c1, ctid FROM ft2_s WHERE c1 <= 12 ORDER BY c1; +FETCH 1 FROM c; +SELECT count(*) FROM ft1; -- saves rows 6 to 12 +FETCH ALL FROM c; +COMMIT; + +-- A cursor whose last chunk was full can't tell it is at EOF. If a drain +-- then finds only the end of its stream, the next FETCH must return nothing. +BEGIN; +DECLARE c CURSOR FOR SELECT c1 FROM ft2_s WHERE c1 <= 10 ORDER BY c1; +MOVE 10 IN c; -- two full chunks +SELECT count(*) FROM ft1; -- reads the end of c's stream +FETCH ALL FROM c; +COMMIT; + +DROP FOREIGN TABLE ft1_s, ft2_s; + +-- Failures while a streaming scan's rows are read. Row 6's x can't be +-- converted to an int. +CREATE TABLE loct_lost (id int, x text); +INSERT INTO loct_lost SELECT g, g::text FROM generate_series(1, 5) g; +INSERT INTO loct_lost VALUES (6, 'not_an_int'), (7, '7'), (8, '8'); + +CREATE FOREIGN TABLE ft_lost (id int, x int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_lost', + streaming_fetch 'true', fetch_size '2'); +CREATE FOREIGN TABLE ft_lost_other (id int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_lost'); + +\set VERBOSITY terse + +-- If the remote query itself fails while its rows are being saved, inside a +-- subtransaction, the scan must fail at the outer level rather than return +-- short results. The view fails at row 3000, after the rows saved before +-- the error have spilled to a temporary file. +CREATE VIEW loct_lost_big AS + SELECT g AS id, repeat('x', 100) AS pad, 1 / (g - 3000) AS x + FROM generate_series(1, 5000) g; +CREATE FOREIGN TABLE ft_lost_big (id int, pad text, x int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_lost_big', + streaming_fetch 'true', fetch_size '100'); +BEGIN; +SET LOCAL work_mem = '64kB'; +DECLARE c_lost CURSOR FOR SELECT id, length(pad), x FROM ft_lost_big; +FETCH 1 FROM c_lost; +SAVEPOINT sp; +SELECT count(*) FROM ft_lost_other; -- ERROR at row 3000 +ROLLBACK TO SAVEPOINT sp; +FETCH ALL FROM c_lost; -- ERROR +COMMIT; +SELECT count(*) FROM ft_lost_other; -- connection still works + +-- A cursor that fails while being read in a subtransaction is abandoned, +-- with its remote query still sending rows. The rest of that result must be +-- discarded before the connection is next used: by a query while the failed +-- cursor is still open, by one after it is closed, or by COMMIT. The last +-- two fail in lost_boom(), at row 3, in a cursor whose remote query only +-- starts inside the subtransaction. +CREATE FUNCTION lost_boom(id int) RETURNS int LANGUAGE plpgsql AS $$ +BEGIN + IF id = 3 THEN RAISE 'boom'; END IF; + RETURN id; +END $$; +BEGIN; +DECLARE c_lost CURSOR FOR SELECT id, x FROM ft_lost ORDER BY id; +FETCH 1 FROM c_lost; +SAVEPOINT sp; +FETCH 6 FROM c_lost; -- ERROR at row 6 +ROLLBACK TO SAVEPOINT sp; +SELECT count(*) FROM ft_lost_other; +COMMIT; +BEGIN; +DECLARE c_lost CURSOR FOR SELECT lost_boom(id) FROM ft_lost ORDER BY id; +SAVEPOINT sp; +FETCH 5 FROM c_lost; -- ERROR at row 3 +ROLLBACK TO SAVEPOINT sp; +CLOSE c_lost; +SELECT count(*) FROM ft_lost_other; +COMMIT; +BEGIN; +DECLARE c_lost CURSOR FOR SELECT lost_boom(id) FROM ft_lost ORDER BY id; +SAVEPOINT sp; +FETCH 5 FROM c_lost; -- ERROR at row 3 +ROLLBACK TO SAVEPOINT sp; +COMMIT; +\set VERBOSITY default + +-- A domain's input checks can run arbitrary code, so they must run only +-- while the scan itself is reading: these NOTICEs come from the FETCHes, not +-- from the query that saves the rest of the cursor's rows. +CREATE FUNCTION lost_note(x int) RETURNS bool LANGUAGE plpgsql AS $$ +BEGIN + RAISE NOTICE 'checking %', x; + RETURN true; +END $$; +CREATE DOMAIN lost_note_int AS int CHECK (lost_note(VALUE)); +CREATE FOREIGN TABLE ft_lost_note (id int, x lost_note_int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_lost', + streaming_fetch 'true', fetch_size '2'); +BEGIN; +DECLARE c_lost CURSOR FOR + SELECT id, x FROM ft_lost_note WHERE id <= 4 ORDER BY id; +FETCH 1 FROM c_lost; +SELECT count(*) FROM ft_lost_other; -- saves rows 3 and 4 +FETCH ALL FROM c_lost; +COMMIT; + +-- Such code can also use the connection the scan is reading from, in the +-- middle of converting the scan's own rows, which saves the rest of the +-- scan's result. +CREATE FUNCTION lost_query(x int) RETURNS bool LANGUAGE plpgsql AS $$ +BEGIN + IF x = current_setting('test.lost_query_at')::int THEN + PERFORM count(*) FROM ft_lost_other; + END IF; + RETURN true; +END $$; +CREATE DOMAIN lost_query_int AS int CHECK (lost_query(VALUE)); +CREATE FOREIGN TABLE ft_lost_query (id int, x lost_query_int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_lost', + streaming_fetch 'true', fetch_size '2'); +SET test.lost_query_at = 1; +SELECT id, x FROM ft_lost_query WHERE id <= 4 ORDER BY id; +RESET test.lost_query_at; + +DROP FOREIGN TABLE ft_lost_note, ft_lost_query; +DROP DOMAIN lost_note_int, lost_query_int; +DROP FUNCTION lost_boom(int), lost_note(int), lost_query(int); +DROP FOREIGN TABLE ft_lost, ft_lost_other, ft_lost_big; +DROP VIEW loct_lost_big; +DROP TABLE loct_lost; + +-- Transaction control with a cursor whose remote query is still streaming +-- when postgres_fdw sends RELEASE SAVEPOINT, ROLLBACK TO SAVEPOINT or +-- COMMIT. Each case must return every row or fail cleanly, and leave the +-- connection usable. +CREATE TABLE loct_xact (id int, x text); +INSERT INTO loct_xact SELECT g, g::text FROM generate_series(1, 10) g; +CREATE FOREIGN TABLE ft_xact (id int, x int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_xact', + streaming_fetch 'true', fetch_size '2'); +CREATE FOREIGN TABLE ft_xact_other (id int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_xact'); + +-- Nested savepoints, released one at a time; parallel_commit sends each +-- RELEASE SAVEPOINT asynchronously. +ALTER SERVER loopback OPTIONS (ADD parallel_commit 'true'); +BEGIN; +SAVEPOINT s1; +SAVEPOINT s2; +DECLARE c CURSOR FOR SELECT id FROM ft_xact ORDER BY id; +FETCH 3 FROM c; +RELEASE SAVEPOINT s2; +FETCH 2 FROM c; +RELEASE SAVEPOINT s1; +FETCH ALL FROM c; +COMMIT; +ALTER SERVER loopback OPTIONS (DROP parallel_commit); + +-- Rolling back the subtransaction in which the cursor was first read +-- cancels the remote query, so the cursor must report an error. +BEGIN; +DECLARE c CURSOR FOR SELECT id FROM ft_xact ORDER BY id; +SAVEPOINT s; +SELECT count(*) FROM ft_xact_other; +FETCH 3 FROM c; +ROLLBACK TO SAVEPOINT s; +FETCH ALL FROM c; -- ERROR +COMMIT; +SELECT count(*) FROM ft_xact_other; -- connection still works + +-- Cursor opened in a subtransaction that is rolled back goes away with it. +BEGIN; +SAVEPOINT s; +DECLARE c CURSOR FOR SELECT id FROM ft_xact ORDER BY id; +FETCH 3 FROM c; +ROLLBACK TO SAVEPOINT s; +SELECT count(*) FROM ft_xact_other; +COMMIT; + +-- Rows saved at RELEASE SAVEPOINT are converted later, so a bad one is +-- reported by the FETCH that reaches it. +INSERT INTO loct_xact VALUES (11, 'not_an_int'); +\set VERBOSITY terse +BEGIN; +SAVEPOINT s; +DECLARE c CURSOR FOR SELECT id, x FROM ft_xact ORDER BY id; +FETCH 3 FROM c; +RELEASE SAVEPOINT s; +FETCH ALL FROM c; -- ERROR at row 11 +ROLLBACK; +\set VERBOSITY default +SELECT count(*) FROM ft_xact_other; -- connection still works +DELETE FROM loct_xact WHERE id = 11; + +-- A holdable cursor is read to the end at COMMIT and keeps all its rows. +BEGIN; +DECLARE c CURSOR WITH HOLD FOR SELECT id FROM ft_xact ORDER BY id; +FETCH 3 FROM c; +COMMIT; +FETCH ALL FROM c; +CLOSE c; + +DROP FOREIGN TABLE ft_xact, ft_xact_other; +DROP TABLE loct_xact; + +-- Rows saved locally on behalf of a cursor may spill to a temp file. That +-- file belongs to the cursor, so it must survive the rollback of the +-- subtransaction in which it was written. Every other row has a NULL. +CREATE TABLE loct_spill (id int, pad text); +INSERT INTO loct_spill + SELECT g, CASE WHEN g % 2 = 0 THEN repeat('x', 100) END + FROM generate_series(1, 5000) g; +CREATE FOREIGN TABLE ft_spill (id int, pad text) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_spill', + streaming_fetch 'true', fetch_size '10'); +CREATE FOREIGN TABLE ft_spill_other (id int) + SERVER loopback OPTIONS (schema_name 'public', table_name 'loct_spill'); + +BEGIN; +SET LOCAL work_mem = '64kB'; +DECLARE c CURSOR FOR SELECT id, length(pad) FROM ft_spill ORDER BY id; +FETCH 1 FROM c; +SAVEPOINT s; +SELECT count(*) FROM ft_spill_other; -- saves c's rows, spilling to disk +ROLLBACK TO SAVEPOINT s; +MOVE 4995 FROM c; +FETCH ALL FROM c; +COMMIT; + +-- Rows still in a temp file are released when a rescan starts the scan over, +-- and when a cursor holding them fails. spill_fn() uses the connection at +-- row 1, which saves the rest of the scan's own result, spilling to disk. +CREATE FUNCTION spill_fn(id int) RETURNS int LANGUAGE plpgsql AS $$ +BEGIN + IF id = 1 THEN + PERFORM count(*) FROM ft_spill_other; + ELSIF id = 4000 THEN + RAISE 'boom'; + END IF; + RETURN id; +END $$; +BEGIN; +SET LOCAL work_mem = '64kB'; +SET LOCAL enable_material = off; +SET LOCAL enable_memoize = off; +SELECT v.x, s.id FROM (VALUES (1), (2)) v(x), + LATERAL (SELECT id FROM ft_spill WHERE spill_fn(id) > 0 AND v.x > 0 + ORDER BY id LIMIT 1) s; +COMMIT; +\set VERBOSITY terse +BEGIN; +SET LOCAL work_mem = '64kB'; +DECLARE c CURSOR FOR SELECT spill_fn(id) FROM ft_spill ORDER BY id; +FETCH 1 FROM c; +MOVE ALL IN c; -- ERROR at row 4000 +ROLLBACK; +\set VERBOSITY default +DROP FUNCTION spill_fn(int); + +DROP FOREIGN TABLE ft_spill, ft_spill_other; +DROP TABLE loct_spill; + -- bug before 9.3.5 due to sloppy handling of remote-estimate parameters SELECT * FROM ft1 WHERE c1 = ANY (ARRAY(SELECT c1 FROM ft2 WHERE c1 < 5)); SELECT * FROM ft2 WHERE c1 = ANY (ARRAY(SELECT c1 FROM ft1 WHERE c1 < 5)); @@ -3856,6 +4244,31 @@ SELECT 1 FROM ft1 LIMIT 1; -- should fail \set VERBOSITY default COMMIT; +-- =================================================================== +-- streaming_fetch: reconnecting after the remote backend terminates +-- =================================================================== +ALTER FOREIGN TABLE ft1 OPTIONS (ADD streaming_fetch 'true'); +SELECT 1 FROM ft1 LIMIT 1; -- open the connection +DO $$ BEGIN +PERFORM pg_terminate_backend(pid, 180000) FROM pg_stat_activity + WHERE application_name = 'fdw_retry_check'; +END $$; +-- Outside a subtransaction, the broken connection is reestablished. +BEGIN; +SELECT c1 FROM ft1 ORDER BY c1 LIMIT 3; +DO $$ BEGIN +PERFORM pg_terminate_backend(pid, 180000) FROM pg_stat_activity + WHERE application_name = 'fdw_retry_check'; +END $$; +-- Inside one, it isn't, and the query fails. +SAVEPOINT s2; +-- The text of the error might vary across platforms, so only show SQLSTATE. +\set VERBOSITY sqlstate +SELECT 1 FROM ft1 LIMIT 1; -- should fail +\set VERBOSITY default +COMMIT; +ALTER FOREIGN TABLE ft1 OPTIONS (DROP streaming_fetch); + -- ============================================================================= -- test connection invalidation cases and postgres_fdw_get_connections function -- ============================================================================= @@ -4424,6 +4837,16 @@ SELECT * FROM local_tbl, async_pt WHERE local_tbl.a = async_pt.a AND local_tbl.c ALTER FOREIGN TABLE async_p1 OPTIONS (DROP use_remote_estimate); ALTER FOREIGN TABLE async_p2 OPTIONS (DROP use_remote_estimate); +-- streaming_fetch disables asynchronous execution, whether it is set on the +-- table (async_p1) or on the server (loopback2, used by async_p2). +ALTER FOREIGN TABLE async_p1 OPTIONS (ADD streaming_fetch 'true'); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM async_pt; +ALTER SERVER loopback2 OPTIONS (ADD streaming_fetch 'true'); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM async_pt; +ALTER FOREIGN TABLE async_p1 OPTIONS (DROP streaming_fetch); +ALTER SERVER loopback2 OPTIONS (DROP streaming_fetch); DROP TABLE local_tbl; DROP INDEX base_tbl1_idx; DROP INDEX base_tbl2_idx; diff --git a/contrib/postgres_fdw/sql/query_cancel.sql b/contrib/postgres_fdw/sql/query_cancel.sql index a6830705843..a7238608e64 100644 --- a/contrib/postgres_fdw/sql/query_cancel.sql +++ b/contrib/postgres_fdw/sql/query_cancel.sql @@ -20,3 +20,14 @@ SET LOCAL statement_timeout = '10ms'; -- This would take very long if not canceled: SELECT count(*) FROM ft1 a CROSS JOIN ft1 b CROSS JOIN ft1 c CROSS JOIN ft1 d; COMMIT; + +-- Same with streaming_fetch: canceling mid-stream must leave the connection +-- usable. +ALTER FOREIGN TABLE ft1 OPTIONS (ADD streaming_fetch 'true'); +BEGIN; +SELECT count(*) FROM ft1 a; +SET LOCAL statement_timeout = '10ms'; +SELECT count(*) FROM ft1 a CROSS JOIN ft1 b CROSS JOIN ft1 c CROSS JOIN ft1 d; +COMMIT; +SELECT count(*) FROM ft1; +ALTER FOREIGN TABLE ft1 OPTIONS (DROP streaming_fetch); diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml index 01577d8d69b..661c5548499 100644 --- a/doc/src/sgml/postgres-fdw.sgml +++ b/doc/src/sgml/postgres-fdw.sgml @@ -484,6 +484,57 @@ OPTIONS (ADD password_required 'false'); + + streaming_fetch (boolean) + + + This option controls whether postgres_fdw reads the + results of a foreign scan without declaring a cursor on the remote + server. Because the execution of a cursor's query can be suspended + between fetches, the remote server never uses a parallel plan for it + (see ). With + streaming_fetch enabled, the remote query instead runs + to completion in a single execution and may be parallelized, which can + significantly speed up large scans. It can be specified for a foreign + table or a foreign server. The option specified on a table overrides an + option specified for the server. The default is false. + Asynchronous execution is not supported in this mode and is disabled + automatically when it is enabled. + + + + Even when this option is enabled, a scan that locks rows, such as one + using FOR UPDATE or FOR SHARE or + one feeding an UPDATE or DELETE + that cannot be pushed down to the remote server, still uses a cursor. + EXPLAIN VERBOSE shows Streaming Fetch: + true for scans that use this mode. + + + + In this mode the rows of a scan are streamed from the remote server in + chunks of fetch_size rows, and a connection can carry + only one such stream at a time. If another scan or statement needs the + same connection while a streaming scan has not yet returned all of its + rows, postgres_fdw reads the remainder of that + scan's rows and saves them locally, in memory up to + work_mem and in a temporary file beyond that, and + returns them from there. + + + + If a streaming scan is stopped before all of its rows have been read + (for example by a LIMIT that cannot be pushed to the + remote server, or by a rescan), the remaining rows must still be read + from the connection and discarded before it can be reused; likewise a + rescan with changed parameters re-executes the whole remote query rather + than rewinding a cursor. For queries that read only a small fraction of + their rows, streaming_fetch can therefore be slower + than the default cursor-based mode. + + + + diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b964e5ee907..695e7576fb1 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2288,6 +2288,7 @@ PgFdwPathExtraData PgFdwRelationInfo PgFdwSamplingMethod PgFdwScanState +PgFdwSpool PgIfAddrCallback PgStatShared_Archiver PgStatShared_Backend -- 2.39.5 (Apple Git-154)