CREATE SERVER testserver1 FOREIGN DATA WRAPPER postgres_fdw;
DO $d$
BEGIN
EXECUTE $$CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (dbname '$$||current_database()||$$',
port '$$||current_setting('port')||$$'
)$$;
EXECUTE $$CREATE SERVER loopback2 FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (dbname '$$||current_database()||$$',
port '$$||current_setting('port')||$$'
)$$;
EXECUTE $$CREATE SERVER loopback3 FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (dbname '$$||current_database()||$$',
port '$$||current_setting('port')||$$'
)$$;
END;
$d$;
CREATE USER MAPPING FOR public SERVER testserver1
OPTIONS (user 'value', password 'value'); CREATE USER MAPPING FORCURRENT_USER SERVER loopback; CREATE USER MAPPING FORCURRENT_USER SERVER loopback2; CREATE USER MAPPING FOR public SERVER loopback3;
CREATEFOREIGNTABLE ft4 (
c1 intNOTNULL,
c2 intNOTNULL,
c3 text
) SERVER loopback OPTIONS (schema_name 'S 1', table_name 'T 3');
CREATEFOREIGNTABLE ft5 (
c1 intNOTNULL,
c2 intNOTNULL,
c3 text
) SERVER loopback OPTIONS (schema_name 'S 1', table_name 'T 4');
CREATEFOREIGNTABLE ft6 (
c1 intNOTNULL,
c2 intNOTNULL,
c3 text
) SERVER loopback2 OPTIONS (schema_name 'S 1', table_name 'T 4');
CREATEFOREIGNTABLE ft7 (
c1 intNOTNULL,
c2 intNOTNULL,
c3 text
) SERVER loopback3 OPTIONS (schema_name 'S 1', table_name 'T 4');
-- =================================================================== -- tests for validator -- =================================================================== -- requiressl and some other parameters are omitted because -- valid values for them depend on configure options ALTER SERVER testserver1 OPTIONS (
use_remote_estimate 'false',
updatable 'true',
fdw_startup_cost '123.456',
fdw_tuple_cost '0.123',
service 'value',
connect_timeout 'value',
dbname 'value',
host 'value',
hostaddr 'value',
port 'value', --client_encoding 'value',
application_name 'value', --fallback_application_name 'value',
keepalives 'value',
keepalives_idle 'value',
keepalives_interval 'value',
tcp_user_timeout 'value', -- requiressl 'value',
sslcompression 'value',
sslmode 'value',
sslcert 'value',
sslkey 'value',
sslrootcert 'value',
sslcrl 'value', --requirepeer 'value',
krbsrvname 'value',
gsslib 'value',
gssdelegation 'value' --replication 'value'
);
-- Error, invalid list syntax ALTER SERVER testserver1 OPTIONS (ADD extensions 'foo; bar');
-- OK but gets a warning ALTER SERVER testserver1 OPTIONS (ADD extensions 'foo, bar'); ALTER SERVER testserver1 OPTIONS (DROP extensions);
ALTER USER MAPPING FOR public SERVER testserver1
OPTIONS (DROP user, DROP password);
-- Attempt to add a valid option that's not allowed in a user mapping ALTER USER MAPPING FOR public SERVER testserver1
OPTIONS (ADD sslmode 'require');
-- But we can add valid ones fine ALTER USER MAPPING FOR public SERVER testserver1
OPTIONS (ADD sslpassword 'dummy');
-- Ensure valid options we haven't used in a user mapping yet are -- permitted to check validation. ALTER USER MAPPING FOR public SERVER testserver1
OPTIONS (ADD sslkey 'value', ADD sslcert 'value');
-- OAuth options are not allowed in either context ALTER SERVER testserver1 OPTIONS (ADD oauth_issuer 'https://example.com'); ALTER SERVER testserver1 OPTIONS (ADD oauth_client_id 'myID'); ALTER USER MAPPING FOR public SERVER testserver1
OPTIONS (ADD oauth_issuer 'https://example.com'); ALTER USER MAPPING FOR public SERVER testserver1
OPTIONS (ADD oauth_client_id 'myID');
-- Test that alteration of server options causes reconnection -- Remote's errors might be non-English, so hide them to ensure stable results
\set VERBOSITY terse SELECT c3, c4 FROM ft1 ORDERBY c3, c1 LIMIT1; -- should work ALTER SERVER loopback OPTIONS (SET dbname 'no such database'); SELECT c3, c4 FROM ft1 ORDERBY c3, c1 LIMIT1; -- should fail
DO $d$
BEGIN
EXECUTE $$ALTER SERVER loopback
OPTIONS (SET dbname '$$||current_database()||$$')$$;
END;
$d$; SELECT c3, c4 FROM ft1 ORDERBY c3, c1 LIMIT1; -- should work again
-- Test that alteration of user mapping options causes reconnection ALTER USER MAPPING FORCURRENT_USER SERVER loopback
OPTIONS (ADD user 'no such user'); SELECT c3, c4 FROM ft1 ORDERBY c3, c1 LIMIT1; -- should fail ALTER USER MAPPING FORCURRENT_USER SERVER loopback
OPTIONS (DROP user); SELECT c3, c4 FROM ft1 ORDERBY c3, c1 LIMIT1; -- should work again
\set VERBOSITY default
-- Now we should be able to run ANALYZE. -- To exercise multiple code paths, we use local stats on ft1 -- and remote-estimate mode on ft2. ANALYZE ft1; ALTERFOREIGNTABLE ft2 OPTIONS (use_remote_estimate 'true');
-- =================================================================== -- test error case for create publication on foreign table -- =================================================================== CREATE PUBLICATION testpub_ftbl FORTABLE ft1; -- should fail
-- =================================================================== -- simple queries -- =================================================================== -- single table without alias EXPLAIN (COSTS OFF) SELECT * FROM ft1 ORDERBY c3, c1 OFFSET 100LIMIT10; SELECT * FROM ft1 ORDERBY c3, c1 OFFSET 100LIMIT10; -- single table with alias - also test that tableoid sort is not pushed to remote side EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 ORDERBY t1.c3, t1.c1, t1.tableoid OFFSET 100LIMIT10; SELECT * FROM ft1 t1 ORDERBY t1.c3, t1.c1, t1.tableoid OFFSET 100LIMIT10; -- whole-row reference EXPLAIN (VERBOSE, COSTS OFF) SELECT t1 FROM ft1 t1 ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10; SELECT t1 FROM ft1 t1 ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10; -- empty result SELECT * FROM ft1 WHEREfalse; -- with WHERE clause EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101AND t1.c6 = '1'AND t1.c7 >= '1'; SELECT * FROM ft1 t1 WHERE t1.c1 = 101AND t1.c6 = '1'AND t1.c7 >= '1'; -- with FOR UPDATE/SHARE EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = 101FORUPDATE; SELECT * FROM ft1 t1 WHERE c1 = 101FORUPDATE; EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = 102FOR SHARE; SELECT * FROM ft1 t1 WHERE c1 = 102FOR SHARE; -- aggregate SELECT COUNT(*) FROM ft1 t1; -- subquery SELECT * FROM ft1 t1 WHERE t1.c3 IN (SELECT c3 FROM ft2 t2 WHERE c1 <= 10) ORDERBY c1; -- subquery+MAX SELECT * FROM ft1 t1 WHERE t1.c3 = (SELECT MAX(c3) FROM ft2 t2) ORDERBY c1; -- used in CTE WITH t1 AS (SELECT * FROM ft1 WHERE c1 <= 10) SELECT t2.c1, t2.c2, t2.c3, t2.c4 FROM t1, ft2 t2 WHEREt1.c1 = t2.c1 ORDERBY t1.c1; -- fixed values SELECT'fixed', NULLFROM ft1 t1 WHERE c1 = 1; -- Test forcing the remote server to produce sorted data for a merge join. SET enable_hashjoin TOfalse; SET enable_nestloop TOfalse; -- inner join; expressions in the clauses appear in the equivalence class list EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2."C 1"FROM ft2 t1 JOIN"S 1"."T 1" t2 ON (t1.c1 = t2."C 1") OFFSET 100LIMIT10; SELECT t1.c1, t2."C 1"FROM ft2 t1 JOIN"S 1"."T 1" t2 ON (t1.c1 = t2."C 1") OFFSET 100LIMIT10; -- outer join; expressions in the clauses do not appear in equivalence class -- list but no output change as compared to the previous query EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2."C 1"FROM ft2 t1 LEFTJOIN"S 1"."T 1" t2 ON (t1.c1 = t2."C 1") OFFSET 100LIMIT10; SELECT t1.c1, t2."C 1"FROM ft2 t1 LEFTJOIN"S 1"."T 1" t2 ON (t1.c1 = t2."C 1") OFFSET 100LIMIT10; -- A join between local table and foreign join. ORDER BY clause is added to the -- foreign join so that the local table can be joined using merge join strategy. EXPLAIN (VERBOSE, COSTS OFF) SELECT t1."C 1"FROM"S 1"."T 1" t1 leftjoin ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100LIMIT10; SELECT t1."C 1"FROM"S 1"."T 1" t1 leftjoin ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100LIMIT10; -- Test similar to above, except that the full join prevents any equivalence -- classes from being merged. This produces single relation equivalence classes -- included in join restrictions. EXPLAIN (VERBOSE, COSTS OFF) SELECT t1."C 1", t2.c1, t3.c1 FROM"S 1"."T 1" t1 leftjoin ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100LIMIT10; SELECT t1."C 1", t2.c1, t3.c1 FROM"S 1"."T 1" t1 leftjoin ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100LIMIT10; -- Test similar to above with all full outer joins EXPLAIN (VERBOSE, COSTS OFF) SELECT t1."C 1", t2.c1, t3.c1 FROM"S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100LIMIT10; SELECT t1."C 1", t2.c1, t3.c1 FROM"S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100LIMIT10;
RESET enable_hashjoin;
RESET enable_nestloop;
-- Test executing assertion in estimate_path_cost_size() that makes sure that -- retrieved_rows for foreign rel re-used to cost pre-sorted foreign paths is -- a sensible value even when the rel has tuples=0 CREATETABLE loct_empty (c1 intNOTNULL, c2 text); CREATEFOREIGNTABLE ft_empty (c1 intNOTNULL, c2 text)
SERVER loopback OPTIONS (table_name 'loct_empty'); INSERTINTO loct_empty SELECT id, 'AAA' || to_char(id, 'FM000') FROM generate_series(1, 100) id; DELETEFROM loct_empty; ANALYZE ft_empty; EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_empty ORDERBY c1;
-- test restriction on non-system foreign tables. SET restrict_nonsystem_relation_kind TO'foreign-table'; SELECT * from ft1 where c1 < 1; -- ERROR INSERTINTO ft1 (c1) VALUES (1); -- ERROR DELETEFROM ft1 WHERE c1 = 1; -- ERROR
TRUNCATE ft1; -- ERROR
RESET restrict_nonsystem_relation_kind;
-- =================================================================== -- WHERE with remotely-executable conditions -- =================================================================== EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 1; -- Var, OpExpr(b), Const EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 100AND t1.c2 = 0; -- BoolExpr EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c3 ISNULL; -- NullTest EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c3 ISNOTNULL; -- NullTest EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE round(abs(c1), 0) = 1; -- FuncExpr EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = -c1; -- OpExpr(l) EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE (c1 ISNOTNULL) ISDISTINCTFROM (c1 ISNOTNULL); -- DistinctExpr EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = ANY(ARRAY[c2, 1, c1 + 0]); -- ScalarArrayOpExpr EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = (ARRAY[c1,c2,3])[1]; -- SubscriptingRef EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c6 = E'foo''s\\bar'; -- check special chars EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c8 = 'foo'; -- can't be sent to remote -- parameterized remote path for foreign table EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM"S 1"."T 1" a, ft2 b WHERE a."C 1" = 47AND b.c1 = a.c2; SELECT * FROM"S 1"."T 1" a, ft2 b WHERE a."C 1" = 47AND b.c1 = a.c2;
-- check both safe and unsafe join conditions EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft2 a, ft2 b WHERE a.c2 = 6AND b.c1 = a.c1 AND a.c8 = 'foo'AND b.c7 = upper(a.c7); SELECT * FROM ft2 a, ft2 b WHERE a.c2 = 6AND b.c1 = a.c1 AND a.c8 = 'foo'AND b.c7 = upper(a.c7); -- 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));
-- user-defined operator/function CREATE FUNCTION postgres_fdw_abs(int) RETURNS intAS $$
BEGIN RETURN abs($1);
END
$$ LANGUAGE plpgsql IMMUTABLE; CREATE OPERATOR === (
LEFTARG = int,
RIGHTARG = int, PROCEDURE = int4eq,
COMMUTATOR = ===
);
-- built-in operators and functions can be shipped for remote execution EXPLAIN (VERBOSE, COSTS OFF) SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = abs(t1.c2); SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = abs(t1.c2); EXPLAIN (VERBOSE, COSTS OFF) SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = t1.c2; SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = t1.c2;
-- by default, user-defined ones cannot EXPLAIN (VERBOSE, COSTS OFF) SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = postgres_fdw_abs(t1.c2); SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = postgres_fdw_abs(t1.c2); EXPLAIN (VERBOSE, COSTS OFF) SELECT count(c3) FROM ft1 t1 WHERE t1.c1 === t1.c2; SELECT count(c3) FROM ft1 t1 WHERE t1.c1 === t1.c2;
-- ORDER BY can be shipped, though EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 === t1.c2 orderby t1.c2 limit1; SELECT * FROM ft1 t1 WHERE t1.c1 === t1.c2 orderby t1.c2 limit1;
-- but let's put them in an extension ... ALTER EXTENSION postgres_fdw ADD FUNCTION postgres_fdw_abs(int); ALTER EXTENSION postgres_fdw ADD OPERATOR === (int, int); ALTER SERVER loopback OPTIONS (ADD extensions 'postgres_fdw');
-- ... now they can be shipped EXPLAIN (VERBOSE, COSTS OFF) SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = postgres_fdw_abs(t1.c2); SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = postgres_fdw_abs(t1.c2); EXPLAIN (VERBOSE, COSTS OFF) SELECT count(c3) FROM ft1 t1 WHERE t1.c1 === t1.c2; SELECT count(c3) FROM ft1 t1 WHERE t1.c1 === t1.c2;
-- and both ORDER BY and LIMIT can be shipped EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 === t1.c2 orderby t1.c2 limit1; SELECT * FROM ft1 t1 WHERE t1.c1 === t1.c2 orderby t1.c2 limit1;
-- Ensure we don't ship FETCH FIRST .. WITH TIES EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c2 FROM ft1 t1 WHERE t1.c1 > 960ORDERBY t1.c2 FETCH FIRST 2 ROWS WITH TIES; SELECT t1.c2 FROM ft1 t1 WHERE t1.c1 > 960ORDERBY t1.c2 FETCH FIRST 2 ROWS WITH TIES;
-- Test CASE pushdown EXPLAIN (VERBOSE, COSTS OFF) SELECT c1,c2,c3 FROM ft2 WHERECASEWHEN c1 > 990THEN c1 END < 1000ORDERBY c1; SELECT c1,c2,c3 FROM ft2 WHERECASEWHEN c1 > 990THEN c1 END < 1000ORDERBY c1;
-- Nested CASE EXPLAIN (VERBOSE, COSTS OFF) SELECT c1,c2,c3 FROM ft2 WHERECASECASEWHEN c2 > 0THEN c2 END WHEN100THEN601WHEN c2 THEN c2 ELSE0 END > 600ORDERBY c1;
SELECT c1,c2,c3 FROM ft2 WHERECASECASEWHEN c2 > 0THEN c2 END WHEN100THEN601WHEN c2 THEN c2 ELSE0 END > 600ORDERBY c1;
-- CASE arg WHEN EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 WHERE c1 > (CASEmod(c1, 4) WHEN0THEN1WHEN2THEN50ELSE100 END);
-- CASE cannot be pushed down because of unshippable arg clause EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 WHERE c1 > (CASE random()::integerWHEN0THEN1WHEN2THEN50ELSE100 END);
-- these are shippable EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 WHERECASE c6 WHEN'foo'THENtrueELSE c3 < 'bar' END; EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 WHERECASE c3 WHEN c6 THENtrueELSE c3 < 'bar' END;
-- but this is not because of collation EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 WHERECASE c3 COLLATE"C"WHEN c6 THENtrueELSE c3 < 'bar' END;
-- a regconfig constant referring to this text search configuration -- is initially unshippable CREATE TEXT SEARCH CONFIGURATION public.custom_search
(COPY = pg_catalog.english); EXPLAIN (VERBOSE, COSTS OFF) SELECT c1, to_tsvector('custom_search'::regconfig, c3) FROM ft1 WHERE c1 = 642AND length(to_tsvector('custom_search'::regconfig, c3)) > 0; SELECT c1, to_tsvector('custom_search'::regconfig, c3) FROM ft1 WHERE c1 = 642AND length(to_tsvector('custom_search'::regconfig, c3)) > 0; -- but if it's in a shippable extension, it can be shipped ALTER EXTENSION postgres_fdw ADD TEXT SEARCH CONFIGURATION public.custom_search; -- however, that doesn't flush the shippability cache, so do a quick reconnect
\c - EXPLAIN (VERBOSE, COSTS OFF) SELECT c1, to_tsvector('custom_search'::regconfig, c3) FROM ft1 WHERE c1 = 642AND length(to_tsvector('custom_search'::regconfig, c3)) > 0; SELECT c1, to_tsvector('custom_search'::regconfig, c3) FROM ft1 WHERE c1 = 642AND length(to_tsvector('custom_search'::regconfig, c3)) > 0;
-- =================================================================== -- ORDER BY queries -- =================================================================== -- we should not push order by clause with volatile expressions or unsafe -- collations EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft2 ORDERBY ft2.c1, random(); EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft2 ORDERBY ft2.c1, ft2.c3 collate"C";
-- Ensure we don't push ORDER BY expressions which are Consts at the UNION -- child level to the foreign server. EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ( SELECT1AS type,c1 FROM ft1 UNIONALL SELECT2AS type,c1 FROM ft2
) a ORDERBY type,c1;
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ( SELECT1AS type,c1 FROM ft1 UNIONALL SELECT2AS type,c1 FROM ft2
) a ORDERBY type;
-- =================================================================== -- JOIN queries -- =================================================================== -- Analyze ft4 and ft5 so that we have better statistics. These tables do not -- have use_remote_estimate set. ANALYZE ft4; ANALYZE ft5;
-- join two tables EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10; SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10; -- join three tables EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t3.c3 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) JOIN ft4 t3 ON (t3.c1 = t1.c1) ORDERBY t1.c3, t1.c1 OFFSET 10LIMIT10; SELECT t1.c1, t2.c2, t3.c3 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) JOIN ft4 t3 ON (t3.c1 = t1.c1) ORDERBY t1.c3, t1.c1 OFFSET 10LIMIT10; -- left outer join EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft4 t1 LEFTJOIN ft5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10; SELECT t1.c1, t2.c1 FROM ft4 t1 LEFTJOIN ft5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10; -- left outer join three tables EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFTJOIN ft2 t2 ON (t1.c1 = t2.c1) LEFTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFTJOIN ft2 t2 ON (t1.c1 = t2.c1) LEFTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; -- left outer join + placement of clauses. -- clauses within the nullable side are not pulled up, but top level clause on -- non-nullable side is pushed into non-nullable side EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t1.c2, t2.c1, t2.c2 FROM ft4 t1 LEFTJOIN (SELECT * FROM ft5 WHERE c1 < 10) t2 ON (t1.c1 = t2.c1) WHERE t1.c1 < 10; SELECT t1.c1, t1.c2, t2.c1, t2.c2 FROM ft4 t1 LEFTJOIN (SELECT * FROM ft5 WHERE c1 < 10) t2 ON (t1.c1 = t2.c1) WHERE t1.c1 < 10; -- clauses within the nullable side are not pulled up, but the top level clause -- on nullable side is not pushed down into nullable side EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t1.c2, t2.c1, t2.c2 FROM ft4 t1 LEFTJOIN (SELECT * FROM ft5 WHERE c1 < 10) t2 ON (t1.c1 = t2.c1) WHERE (t2.c1 < 10OR t2.c1 ISNULL) AND t1.c1 < 10; SELECT t1.c1, t1.c2, t2.c1, t2.c2 FROM ft4 t1 LEFTJOIN (SELECT * FROM ft5 WHERE c1 < 10) t2 ON (t1.c1 = t2.c1) WHERE (t2.c1 < 10OR t2.c1 ISNULL) AND t1.c1 < 10; -- right outer join EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft5 t1 RIGHTJOIN ft4 t2 ON (t1.c1 = t2.c1) ORDERBY t2.c1, t1.c1 OFFSET 10LIMIT10; SELECT t1.c1, t2.c1 FROM ft5 t1 RIGHTJOIN ft4 t2 ON (t1.c1 = t2.c1) ORDERBY t2.c1, t1.c1 OFFSET 10LIMIT10; -- right outer join three tables EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHTJOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHTJOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; -- full outer join EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft4 t1 FULL JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 45LIMIT10; SELECT t1.c1, t2.c1 FROM ft4 t1 FULL JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 45LIMIT10; -- full outer join with restrictions on the joining relations -- a. the joining relations are both base relations EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t1 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between50and60) t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1; SELECT t1.c1, t2.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t1 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between50and60) t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1; EXPLAIN (VERBOSE, COSTS OFF) SELECT1FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t1 FULL JOIN (SELECT c1 FROM ft5 WHEREc1 between50and60) t2 ON (TRUE) OFFSET 10LIMIT10; SELECT1FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t1 FULL JOIN (SELECT c1 FROM ft5 WHEREc1 between50and60) t2 ON (TRUE) OFFSET 10LIMIT10; -- b. one of the joining relations is a base relation and the other is a join -- relation EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t1 FULL JOIN (SELECTt2.c1, t3.c1 FROM ft4 t2 LEFTJOIN ft5 t3 ON (t2.c1 = t3.c1) WHERE (t2.c1 between50and60)) ss(a, b) ON (t1.c1 = ss.a) ORDERBY t1.c1, ss.a, ss.b; SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t1 FULL JOIN (SELECTt2.c1, t3.c1 FROM ft4 t2 LEFTJOIN ft5 t3 ON (t2.c1 = t3.c1) WHERE (t2.c1 between50and60)) ss(a, b) ON (t1.c1 = ss.a) ORDERBY t1.c1, ss.a, ss.b; -- c. test deparsing the remote query as nested subqueries EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t1 FULL JOIN (SELECTt2.c1, t3.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t2 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between50and60) t3 ON (t2.c1 = t3.c1) WHERE t2.c1 ISNULLOR t2.c1 ISNOTNULL) ss(a, b) ON (t1.c1 = ss.a) ORDERBY t1.c1, ss.a, ss.b; SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t1 FULL JOIN (SELECTt2.c1, t3.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t2 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between50and60) t3 ON (t2.c1 = t3.c1) WHERE t2.c1 ISNULLOR t2.c1 ISNOTNULL) ss(a, b) ON (t1.c1 = ss.a) ORDERBY t1.c1, ss.a, ss.b; -- d. test deparsing rowmarked relations as subqueries EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM"S 1"."T 3"WHERE c1 = 50) t1 INNERJOIN (SELECT t2.c1, t3.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t2 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between50and60) t3 ON (t2.c1 = t3.c1) WHERE t2.c1 ISNULLOR t2.c1 ISNOTNULL) ss(a, b) ON (TRUE) ORDERBY t1.c1, ss.a, ss.b FORUPDATE OF t1; SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM"S 1"."T 3"WHERE c1 = 50) t1 INNERJOIN (SELECT t2.c1, t3.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between50and60) t2 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between50and60) t3 ON (t2.c1 = t3.c1) WHERE t2.c1 ISNULLOR t2.c1 ISNOTNULL) ss(a, b) ON (TRUE) ORDERBY t1.c1, ss.a, ss.b FORUPDATE OF t1; -- full outer join + inner join EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1, t3.c1 FROM ft4 t1 INNERJOIN ft5 t2 ON (t1.c1 = t2.c1 + 1and t1.c1 between50and60) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) ORDERBY t1.c1, t2.c1, t3.c1 LIMIT10; SELECT t1.c1, t2.c1, t3.c1 FROM ft4 t1 INNERJOIN ft5 t2 ON (t1.c1 = t2.c1 + 1and t1.c1 between50and60) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) ORDERBY t1.c1, t2.c1, t3.c1 LIMIT10; -- full outer join three tables EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; -- full outer join + right outer join EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; -- right outer join + full outer join EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHTJOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHTJOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; -- full outer join + left outer join EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) LEFTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) LEFTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; -- left outer join + full outer join EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFTJOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFTJOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; SET enable_memoize TO off; -- right outer join + left outer join EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHTJOIN ft2 t2 ON (t1.c1 = t2.c1) LEFTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHTJOIN ft2 t2 ON (t1.c1 = t2.c1) LEFTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10;
RESET enable_memoize; -- left outer join + right outer join EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFTJOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFTJOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHTJOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10LIMIT10; -- full outer join + WHERE clause, only matched rows EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft4 t1 FULL JOIN ft5 t2 ON (t1.c1 = t2.c1) WHERE (t1.c1 = t2.c1 OR t1.c1 ISNULL) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10; SELECT t1.c1, t2.c1 FROM ft4 t1 FULL JOIN ft5 t2 ON (t1.c1 = t2.c1) WHERE (t1.c1 = t2.c1 OR t1.c1 ISNULL) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10; -- full outer join + WHERE clause with shippable extensions set EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t1.c3 FROM ft1 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE postgres_fdw_abs(t1.c1) > 0 OFFSET 10LIMIT10; ALTER SERVER loopback OPTIONS (DROP extensions); -- full outer join + WHERE clause with shippable extensions not set EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2, t1.c3 FROM ft1 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE postgres_fdw_abs(t1.c1) > 0 OFFSET 10LIMIT10; ALTER SERVER loopback OPTIONS (ADD extensions 'postgres_fdw'); -- join two tables with FOR UPDATE clause -- tests whole-row reference for row marks EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10FORUPDATE OF t1; SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10FORUPDATE OF t1; EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10FORUPDATE; SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10FORUPDATE; -- join two tables with FOR SHARE clause EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10FOR SHARE OF t1; SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10FOR SHARE OF t1; EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10FOR SHARE; SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10FOR SHARE; -- join in CTE EXPLAIN (VERBOSE, COSTS OFF) WITH t (c1_1, c1_3, c2_1) AS MATERIALIZED (SELECT t1.c1, t1.c3, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1)) SELECT c1_1, c2_1 FROM t ORDERBY c1_3, c1_1 OFFSET 100LIMIT10; WITH t (c1_1, c1_3, c2_1) AS MATERIALIZED (SELECT t1.c1, t1.c3, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1)) SELECT c1_1, c2_1 FROM t ORDERBY c1_3, c1_1 OFFSET 100LIMIT10; -- ctid with whole-row reference EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.ctid, t1, t2, t1.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10; -- SEMI JOIN EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1 FROM ft1 t1 WHEREEXISTS (SELECT1FROM ft2 t2 WHERE t1.c1 = t2.c1) ORDERBY t1.c1 OFFSET 100LIMIT10; SELECT t1.c1 FROM ft1 t1 WHEREEXISTS (SELECT1FROM ft2 t2 WHERE t1.c1 = t2.c1) ORDERBY t1.c1 OFFSET 100LIMIT10; -- ANTI JOIN, not pushed down EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1 FROM ft1 t1 WHERENOTEXISTS (SELECT1FROM ft2 t2 WHERE t1.c1 = t2.c2) ORDERBY t1.c1 OFFSET 100LIMIT10; SELECT t1.c1 FROM ft1 t1 WHERENOTEXISTS (SELECT1FROM ft2 t2 WHERE t1.c1 = t2.c2) ORDERBY t1.c1 OFFSET 100LIMIT10; -- CROSS JOIN can be pushed down EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft1 t1 CROSSJOIN ft2 t2 ORDERBY t1.c1, t2.c1 OFFSET 100LIMIT10; SELECT t1.c1, t2.c1 FROM ft1 t1 CROSSJOIN ft2 t2 ORDERBY t1.c1, t2.c1 OFFSET 100LIMIT10; -- different server, not pushed down. No result expected. EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 100LIMIT10; SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 100LIMIT10; -- unsafe join conditions (c8 has a UDT), not pushed down. Practically a CROSS -- JOIN since c8 in both tables has same value. EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft1 t1 LEFTJOIN ft2 t2 ON (t1.c8 = t2.c8) ORDERBY t1.c1, t2.c1 OFFSET 100LIMIT10; SELECT t1.c1, t2.c1 FROM ft1 t1 LEFTJOIN ft2 t2 ON (t1.c8 = t2.c8) ORDERBY t1.c1, t2.c1 OFFSET 100LIMIT10; -- unsafe conditions on one side (c8 has a UDT), not pushed down. EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft1 t1 LEFTJOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c8 = 'foo'ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10; SELECT t1.c1, t2.c1 FROM ft1 t1 LEFTJOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c8 = 'foo'ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10; -- join where unsafe to pushdown condition in WHERE clause has a column not -- in the SELECT clause. In this test unsafe clause needs to have column -- references from both joining sides so that the clause is not pushed down -- into one of the joining sides. EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c8 = t2.c8 ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10; SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c8 = t2.c8 ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10; -- Aggregate after UNION, for testing setrefs EXPLAIN (VERBOSE, COSTS OFF) SELECT t1c1, avg(t1c1 + t2c1) FROM (SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) UNIONSELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1)) AS t (t1c1, t2c1) GROUPBY t1c1 ORDERBY t1c1 OFFSET 100LIMIT10; SELECT t1c1, avg(t1c1 + t2c1) FROM (SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) UNIONSELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1)) AS t (t1c1, t2c1) GROUPBY t1c1 ORDERBY t1c1 OFFSET 100LIMIT10; -- join with lateral reference EXPLAIN (VERBOSE, COSTS OFF) SELECT t1."C 1"FROM"S 1"."T 1" t1, LATERAL (SELECTDISTINCT t2.c1, t3.c1 FROM ft1 t2, ft2 t3 WHERE t2.c1 = t3.c1 AND t2.c2 = t1.c2) q ORDERBY t1."C 1" OFFSET 10LIMIT10; SELECT t1."C 1"FROM"S 1"."T 1" t1, LATERAL (SELECTDISTINCT t2.c1, t3.c1 FROM ft1 t2, ft2 t3 WHERE t2.c1 = t3.c1 AND t2.c2 = t1.c2) q ORDERBY t1."C 1" OFFSET 10LIMIT10; -- join with pseudoconstant quals EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1 ANDCURRENT_USER = SESSION_USER) ORDERBY t1.c3, t1.c1 OFFSET 100LIMIT10;
-- non-Var items in targetlist of the nullable rel of a join preventing -- push-down in some cases -- unable to push {ft1, ft2} EXPLAIN (VERBOSE, COSTS OFF) SELECT q.a, ft2.c1 FROM (SELECT13FROM ft1 WHERE c1 = 13) q(a) RIGHTJOIN ft2 ON (q.a = ft2.c1) WHERE ft2.c1 BETWEEN10AND15; SELECT q.a, ft2.c1 FROM (SELECT13FROM ft1 WHERE c1 = 13) q(a) RIGHTJOIN ft2 ON (q.a = ft2.c1) WHERE ft2.c1 BETWEEN10AND15;
-- ok to push {ft1, ft2} but not {ft1, ft2, ft4} EXPLAIN (VERBOSE, COSTS OFF) SELECT ft4.c1, q.* FROM ft4 LEFTJOIN (SELECT13, ft1.c1, ft2.c1 FROM ft1 RIGHTJOIN ft2 ON (ft1.c1 = ft2.c1) WHERE ft1.c1 = 12) q(a, b, c) ON (ft4.c1 = q.b) WHERE ft4.c1 BETWEEN10AND15; SELECT ft4.c1, q.* FROM ft4 LEFTJOIN (SELECT13, ft1.c1, ft2.c1 FROM ft1 RIGHTJOIN ft2 ON (ft1.c1 = ft2.c1) WHERE ft1.c1 = 12) q(a, b, c) ON (ft4.c1 = q.b) WHERE ft4.c1 BETWEEN10AND15;
-- join with nullable side with some columns with null values UPDATE ft5 SET c3 = nullwhere c1 % 9 = 0; EXPLAIN (VERBOSE, COSTS OFF) SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 leftjoin ft4 on ft5.c1 = ft4.c1 WHERE ft4.c1 BETWEEN10and30ORDERBY ft5.c1, ft4.c1; SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 leftjoin ft4 on ft5.c1 = ft4.c1 WHERE ft4.c1 BETWEEN10and30ORDERBY ft5.c1, ft4.c1;
-- multi-way join involving multiple merge joins -- (this case used to have EPQ-related planning problems) CREATETABLE local_tbl (c1 intNOTNULL, c2 intNOTNULL, c3 text, CONSTRAINT local_tbl_pkey PRIMARYKEY (c1)); INSERTINTO local_tbl SELECT id, id % 10, to_char(id, 'FM0000') FROM generate_series(1, 1000) id; ANALYZE local_tbl; SET enable_nestloop TOfalse; SET enable_hashjoin TOfalse; EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1, ft2, ft4, ft5, local_tbl WHERE ft1.c1 = ft2.c1 AND ft1.c2 = ft4.c1 AND ft1.c2 = ft5.c1 AND ft1.c2 = local_tbl.c1 AND ft1.c1 < 100AND ft2.c1 < 100FORUPDATE; SELECT * FROM ft1, ft2, ft4, ft5, local_tbl WHERE ft1.c1 = ft2.c1 AND ft1.c2 = ft4.c1 AND ft1.c2 = ft5.c1 AND ft1.c2 = local_tbl.c1 AND ft1.c1 < 100AND ft2.c1 < 100FORUPDATE; EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1, ft4, ft5, local_tbl WHERE ft1.c1 = ft4.c1 AND ft1.c1 = ft5.c1 AND ft1.c2 = local_tbl.c1 AND ft1.c1 < 100AND ft5.c1 < 100FORUPDATE; SELECT * FROM ft1, ft4, ft5, local_tbl WHERE ft1.c1 = ft4.c1 AND ft1.c1 = ft5.c1 AND ft1.c2 = local_tbl.c1 AND ft1.c1 < 100AND ft5.c1 < 100FORUPDATE;
RESET enable_nestloop;
RESET enable_hashjoin;
-- test that add_paths_with_pathkeys_for_rel() arranges for the epq_path to -- return columns needed by the parent ForeignScan node EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM local_tbl LEFTJOIN (SELECT ft1.*, COALESCE(ft1.c3 || ft2.c3, 'foobar') FROM ft1 INNERJOIN ft2 ON (ft1.c1 = ft2.c1 AND ft1.c1 < 100)) ss ON (local_tbl.c1 = ss.c1) ORDERBY local_tbl.c1 FORUPDATE OF local_tbl;
ALTER SERVER loopback OPTIONS (DROP extensions); ALTER SERVER loopback OPTIONS (ADD fdw_startup_cost '10000.0'); EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM local_tbl LEFTJOIN (SELECT ft1.* FROM ft1 INNERJOIN ft2 ON (ft1.c1 = ft2.c1 AND ft1.c1 < 100AND (ft1.c1 - postgres_fdw_abs(ft2.c2)) = 0)) ss ON (local_tbl.c3 = ss.c3) ORDERBY local_tbl.c1 FORUPDATE OF local_tbl; ALTER SERVER loopback OPTIONS (DROP fdw_startup_cost); ALTER SERVER loopback OPTIONS (ADD extensions 'postgres_fdw');
DROPTABLE local_tbl;
-- check join pushdown in situations where multiple userids are involved CREATE ROLE regress_view_owner SUPERUSER; CREATE USER MAPPING FOR regress_view_owner SERVER loopback; GRANTSELECTON ft4 TO regress_view_owner; GRANTSELECTON ft5 TO regress_view_owner;
CREATE VIEW v4 ASSELECT * FROM ft4; CREATE VIEW v5 ASSELECT * FROM ft5; ALTER VIEW v5 OWNER TO regress_view_owner; EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2 FROM v4 t1 LEFTJOIN v5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10; -- can't be pushed down, different view owners SELECT t1.c1, t2.c2 FROM v4 t1 LEFTJOIN v5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10; ALTER VIEW v4 OWNER TO regress_view_owner; EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2 FROM v4 t1 LEFTJOIN v5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10; -- can be pushed down SELECT t1.c1, t2.c2 FROM v4 t1 LEFTJOIN v5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10;
EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2 FROM v4 t1 LEFTJOIN ft5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10; -- can't be pushed down, view owner not current user SELECT t1.c1, t2.c2 FROM v4 t1 LEFTJOIN ft5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10; ALTER VIEW v4 OWNER TOCURRENT_USER; EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.c1, t2.c2 FROM v4 t1 LEFTJOIN ft5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10; -- can be pushed down SELECT t1.c1, t2.c2 FROM v4 t1 LEFTJOIN ft5 t2 ON (t1.c1 = t2.c1) ORDERBY t1.c1, t2.c1 OFFSET 10LIMIT10; ALTER VIEW v4 OWNER TO regress_view_owner;
-- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL -- ==================================================================== CREATE ROLE regress_view_owner_another; ALTER VIEW v4 OWNER TO regress_view_owner_another; GRANTSELECTON ft4 TO regress_view_owner_another; ALTERFOREIGNTABLE ft4 OPTIONS (ADD use_remote_estimate 'true'); -- The following should query the remote backing table of ft4 as user -- regress_view_owner_another, the view owner, though it fails as expected -- due to the lack of a user mapping for that user. EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM v4; -- Likewise, but with the query under an UNION ALL EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM (SELECT * FROM v4 UNIONALLSELECT * FROM v4); -- Should not get that error once a user mapping is created CREATE USER MAPPING FOR regress_view_owner_another SERVER loopback OPTIONS (password_required 'false'); EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM v4; EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM (SELECT * FROM v4 UNIONALLSELECT * FROM v4); DROP USER MAPPING FOR regress_view_owner_another SERVER loopback; DROP OWNED BY regress_view_owner_another; DROP ROLE regress_view_owner_another; ALTERFOREIGNTABLE ft4 OPTIONS (SET use_remote_estimate 'false');
-- cleanup DROP OWNED BY regress_view_owner; DROP ROLE regress_view_owner;
-- =================================================================== -- Aggregate and grouping queries -- ===================================================================
-- Aggregate is not pushed down as aggregation contains random() explain (verbose, costs off) select sum(c1 * (random() <= 1)::int) as sum, avg(c1) from ft1;
-- Aggregate over join query explain (verbose, costs off) select count(*), sum(t1.c1), avg(t2.c1) from ft1 t1 innerjoin ft1 t2 on (t1.c2 = t2.c2) where t1.c2 = 6; select count(*), sum(t1.c1), avg(t2.c1) from ft1 t1 innerjoin ft1 t2 on (t1.c2 = t2.c2) where t1.c2 = 6;
-- Not pushed down due to local conditions present in underneath input rel explain (verbose, costs off) select sum(t1.c1), count(t2.c1) from ft1 t1 innerjoin ft2 t2 on (t1.c1 = t2.c1) where ((t1.c1 * t2.c1)/(t1.c1 * t2.c1)) * random() <= 1;
-- GROUP BY clause having expressions explain (verbose, costs off) select c2/2, sum(c2) * (c2/2) from ft1 groupby c2/2orderby c2/2; select c2/2, sum(c2) * (c2/2) from ft1 groupby c2/2orderby c2/2;
-- Aggregates in subquery are pushed down. set enable_incremental_sort = off; explain (verbose, costs off) select count(x.a), sum(x.a) from (select c2 a, sum(c1) b from ft1 groupby c2, sqrt(c1) orderby1, 2) x; select count(x.a), sum(x.a) from (select c2 a, sum(c1) b from ft1 groupby c2, sqrt(c1) orderby1, 2) x;
reset enable_incremental_sort;
-- Aggregate is still pushed down by taking unshippable expression out explain (verbose, costs off) select c2 * (random() <= 1)::intas sum1, sum(c1) * c2 as sum2 from ft1 groupby c2 orderby1, 2; select c2 * (random() <= 1)::intas sum1, sum(c1) * c2 as sum2 from ft1 groupby c2 orderby1, 2;
-- Aggregate with unshippable GROUP BY clause are not pushed explain (verbose, costs off) select c2 * (random() <= 1)::intas c2 from ft2 groupby c2 * (random() <= 1)::intorderby1;
-- GROUP BY clause in various forms, cardinal, alias and constant expression explain (verbose, costs off) select count(c2) w, c2 x, 5 y, 7.0 z from ft1 groupby2, y, 9.0::intorderby2; select count(c2) w, c2 x, 5 y, 7.0 z from ft1 groupby2, y, 9.0::intorderby2;
-- GROUP BY clause referring to same column multiple times -- Also, ORDER BY contains an aggregate function explain (verbose, costs off) select c2, c2 from ft1 where c2 > 6groupby1, 2orderby sum(c1); select c2, c2 from ft1 where c2 > 6groupby1, 2orderby sum(c1);
-- Testing HAVING clause shippability explain (verbose, costs off) select c2, sum(c1) from ft2 groupby c2 having avg(c1) < 500and sum(c1) < 49800orderby c2; select c2, sum(c1) from ft2 groupby c2 having avg(c1) < 500and sum(c1) < 49800orderby c2;
-- Unshippable HAVING clause will be evaluated locally, and other qual in HAVING clause is pushed down explain (verbose, costs off) select count(*) from (select c5, count(c1) from ft1 groupby c5, sqrt(c2) having (avg(c1) / avg(c1)) * random() <= 1and avg(c1) < 500) x; select count(*) from (select c5, count(c1) from ft1 groupby c5, sqrt(c2) having (avg(c1) / avg(c1)) * random() <= 1and avg(c1) < 500) x;
-- Aggregate in HAVING clause is not pushable, and thus aggregation is not pushed down explain (verbose, costs off) select sum(c1) from ft1 groupby c2 having avg(c1 * (random() <= 1)::int) > 100orderby1;
-- Remote aggregate in combination with a local Param (for the output -- of an initplan) can be trouble, per bug #15781 explain (verbose, costs off) selectexists(select1from pg_enum), sum(c1) from ft1; selectexists(select1from pg_enum), sum(c1) from ft1;
explain (verbose, costs off) selectexists(select1from pg_enum), sum(c1) from ft1 groupby1; selectexists(select1from pg_enum), sum(c1) from ft1 groupby1;
-- Testing ORDER BY, DISTINCT, FILTER, Ordered-sets and VARIADIC within aggregates
-- ORDER BY within aggregate, same column used to order explain (verbose, costs off) select array_agg(c1 orderby c1) from ft1 where c1 < 100groupby c2 orderby1; select array_agg(c1 orderby c1) from ft1 where c1 < 100groupby c2 orderby1;
-- ORDER BY within aggregate, different column used to order also using DESC explain (verbose, costs off) select array_agg(c5 orderby c1 desc) from ft2 where c2 = 6and c1 < 50; select array_agg(c5 orderby c1 desc) from ft2 where c2 = 6and c1 < 50;
-- DISTINCT within aggregate explain (verbose, costs off) select array_agg(distinct (t1.c1)%5) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20or (t1.c1 isnulland t2.c1 < 5) groupby (t2.c1)%3orderby1; select array_agg(distinct (t1.c1)%5) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20or (t1.c1 isnulland t2.c1 < 5) groupby (t2.c1)%3orderby1;
-- DISTINCT combined with ORDER BY within aggregate explain (verbose, costs off) select array_agg(distinct (t1.c1)%5orderby (t1.c1)%5) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20or (t1.c1 isnulland t2.c1 < 5) groupby (t2.c1)%3orderby1; select array_agg(distinct (t1.c1)%5orderby (t1.c1)%5) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20or (t1.c1 isnulland t2.c1 < 5) groupby (t2.c1)%3orderby1;
explain (verbose, costs off) select array_agg(distinct (t1.c1)%5orderby (t1.c1)%5desc nulls last) from ft4 t1 full joinft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20or (t1.c1 isnulland t2.c1 < 5) groupby (t2.c1)%3orderby1; select array_agg(distinct (t1.c1)%5orderby (t1.c1)%5desc nulls last) from ft4 t1 full joinft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20or (t1.c1 isnulland t2.c1 < 5) groupby (t2.c1)%3orderby1;
-- DISTINCT, ORDER BY and FILTER within aggregate explain (verbose, costs off) select sum(c1%3), sum(distinct c1%3orderby c1%3) filter (where c1%3 < 2), c2 from ft1 where c2 = 6groupby c2; select sum(c1%3), sum(distinct c1%3orderby c1%3) filter (where c1%3 < 2), c2 from ft1 where c2 = 6groupby c2;
-- Outer query is aggregation query explain (verbose, costs off) selectdistinct (select count(*) filter (where t2.c2 = 6and t2.c1 < 10) from ft1 t1 where t1.c1 = 6) from ft2 t2 where t2.c2 % 6 = 0orderby1; selectdistinct (select count(*) filter (where t2.c2 = 6and t2.c1 < 10) from ft1 t1 where t1.c1 = 6) from ft2 t2 where t2.c2 % 6 = 0orderby1; -- Inner query is aggregation query explain (verbose, costs off) selectdistinct (select count(t1.c1) filter (where t2.c2 = 6and t2.c1 < 10) from ft1 t1 where t1.c1 = 6) from ft2 t2 where t2.c2 % 6 = 0orderby1; selectdistinct (select count(t1.c1) filter (where t2.c2 = 6and t2.c1 < 10) from ft1 t1 where t1.c1 = 6) from ft2 t2 where t2.c2 % 6 = 0orderby1;
-- Aggregate not pushed down as FILTER condition is not pushable explain (verbose, costs off) select sum(c1) filter (where (c1 / c1) * random() <= 1) from ft1 groupby c2 orderby1; explain (verbose, costs off) select sum(c2) filter (where c2 in (select c2 from ft1 where c2 < 5)) from ft1;
-- Ordered-sets within aggregate explain (verbose, costs off) select c2, rank('10'::varchar) within group (orderby c6), percentile_cont(c2/10::numeric) within group (orderby c1) from ft1 where c2 < 10groupby c2 having percentile_cont(c2/10::numeric) within group (orderby c1) < 500orderby c2; select c2, rank('10'::varchar) within group (orderby c6), percentile_cont(c2/10::numeric) within group (orderby c1) from ft1 where c2 < 10groupby c2 having percentile_cont(c2/10::numeric) within group (orderby c1) < 500orderby c2;
-- Using multiple arguments within aggregates explain (verbose, costs off) select c1, rank(c1, c2) within group (orderby c1, c2) from ft1 groupby c1, c2 having c1 = 6orderby1; select c1, rank(c1, c2) within group (orderby c1, c2) from ft1 groupby c1, c2 having c1 = 6orderby1;
-- User defined function for user defined aggregate, VARIADIC create function least_accum(anyelement, variadic anyarray)
returns anyelement language sqlas 'select least($1, min($2[i])) from generate_subscripts($2,1) g(i)'; create aggregate least_agg(variadic items anyarray) (
stype = anyelement, sfunc = least_accum
);
-- Disable hash aggregation for plan stability. set enable_hashagg tofalse;
-- Not pushed down due to user defined aggregate explain (verbose, costs off) select c2, least_agg(c1) from ft1 groupby c2 orderby c2;
-- Add function and aggregate into extension alter extension postgres_fdw add function least_accum(anyelement, variadic anyarray); alter extension postgres_fdw add aggregate least_agg(variadic items anyarray); alter server loopback options (set extensions 'postgres_fdw');
-- Now aggregate will be pushed. Aggregate will display VARIADIC argument. explain (verbose, costs off) select c2, least_agg(c1) from ft1 where c2 < 100groupby c2 orderby c2; select c2, least_agg(c1) from ft1 where c2 < 100groupby c2 orderby c2;
-- Remove function and aggregate from extension alter extension postgres_fdw drop function least_accum(anyelement, variadic anyarray); alter extension postgres_fdw drop aggregate least_agg(variadic items anyarray); alter server loopback options (set extensions 'postgres_fdw');
-- Not pushed down as we have dropped objects from extension. explain (verbose, costs off) select c2, least_agg(c1) from ft1 groupby c2 orderby c2;
-- Cleanup
reset enable_hashagg; drop aggregate least_agg(variadic items anyarray); drop function least_accum(anyelement, variadic anyarray);
-- Testing USING OPERATOR() in ORDER BY within aggregate. -- For this, we need user defined operators along with operator family and -- operator class. Create those and then add them in extension. Note that -- user defined objects are considered unshippable unless they are part of -- the extension. create operator public.<^ (
leftarg = int4,
rightarg = int4, procedure = int4eq
);
create function my_op_cmp(a int, b int) returns intas
$$begin return btint4cmp(a, b); end $$ language plpgsql;
create operator class my_op_class for type intusing btree family my_op_family as
operator 1 public.<^,
operator 3 public.=^,
operator 5 public.>^,
function 1 my_op_cmp(int, int);
-- This will not be pushed as user defined sort operator is not part of the -- extension yet. explain (verbose, costs off) select array_agg(c1 orderby c1 using operator(public.<^)) from ft2 where c2 = 6and c1 < 100groupby c2;
-- This should not be pushed either. explain (verbose, costs off) select * from ft2 orderby c1 using operator(public.<^);
-- Update local stats on ft2 ANALYZE ft2;
-- Add into extension alter extension postgres_fdw add operator class my_op_class using btree; alter extension postgres_fdw add function my_op_cmp(a int, b int); alter extension postgres_fdw add operator family my_op_family using btree; alter extension postgres_fdw add operator public.<^(int, int); alter extension postgres_fdw add operator public.=^(int, int); alter extension postgres_fdw add operator public.>^(int, int); alter server loopback options (set extensions 'postgres_fdw');
-- Now this will be pushed as sort operator is part of the extension. alter server loopback options (add fdw_tuple_cost '0.5'); explain (verbose, costs off) select array_agg(c1 orderby c1 using operator(public.<^)) from ft2 where c2 = 6and c1 < 100groupby c2; select array_agg(c1 orderby c1 using operator(public.<^)) from ft2 where c2 = 6and c1 < 100groupby c2; alter server loopback options (drop fdw_tuple_cost);
-- This should be pushed too. explain (verbose, costs off) select * from ft2 orderby c1 using operator(public.<^);
-- Remove from extension alter extension postgres_fdw drop operator class my_op_class using btree; alter extension postgres_fdw drop function my_op_cmp(a int, b int); alter extension postgres_fdw drop operator family my_op_family using btree; alter extension postgres_fdw drop operator public.<^(int, int); alter extension postgres_fdw drop operator public.=^(int, int); alter extension postgres_fdw drop operator public.>^(int, int); alter server loopback options (set extensions 'postgres_fdw');
-- This will not be pushed as sort operator is now removed from the extension. explain (verbose, costs off) select array_agg(c1 orderby c1 using operator(public.<^)) from ft2 where c2 = 6and c1 < 100groupby c2;
-- Cleanup drop operator class my_op_class using btree; drop function my_op_cmp(a int, b int); drop operator family my_op_family using btree; drop operator public.>^(int, int); drop operator public.=^(int, int); drop operator public.<^(int, int);
-- Input relation to aggregate push down hook is not safe to pushdown and thus -- the aggregate cannot be pushed down to foreign server. explain (verbose, costs off) select count(t1.c3) from ft2 t1 leftjoin ft2 t2 on (t1.c1 = random() * t2.c2);
-- Subquery in FROM clause having aggregate explain (verbose, costs off) select count(*), x.b from ft1, (select c2 a, sum(c1) b from ft1 groupby c2) x where ft1.c2 = x.a groupby x.b orderby1, 2; select count(*), x.b from ft1, (select c2 a, sum(c1) b from ft1 groupby c2) x where ft1.c2 = x.a groupby x.b orderby1, 2;
-- FULL join with IS NULL check in HAVING explain (verbose, costs off) select avg(t1.c1), sum(t2.c1) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) groupby t2.c1 having (avg(t1.c1) isnulland sum(t2.c1) < 10) or sum(t2.c1) isnullorderby1 nulls last, 2; select avg(t1.c1), sum(t2.c1) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) groupby t2.c1 having (avg(t1.c1) isnulland sum(t2.c1) < 10) or sum(t2.c1) isnullorderby1 nulls last, 2;
-- Aggregate over FULL join needing to deparse the joining relations as -- subqueries. explain (verbose, costs off) select count(*), sum(t1.c1), avg(t2.c1) from (select c1 from ft4 where c1 between50and60) t1 full join (select c1 from ft5 where c1 between50and60) t2 on (t1.c1 = t2.c1); select count(*), sum(t1.c1), avg(t2.c1) from (select c1 from ft4 where c1 between50and60) t1 full join (select c1 from ft5 where c1 between50and60) t2 on (t1.c1 = t2.c1);
-- ORDER BY expression is part of the target list but not pushed down to -- foreign server. explain (verbose, costs off) select sum(c2) * (random() <= 1)::intas sum from ft1 orderby1; select sum(c2) * (random() <= 1)::intas sum from ft1 orderby1;
-- LATERAL join, with parameterization set enable_hashagg tofalse; explain (verbose, costs off) select c2, sum from"S 1"."T 1" t1, lateral (select sum(t2.c1 + t1."C 1") sum from ft2 t2 groupby t2.c1) qry where t1.c2 * 2 = qry.sum and t1.c2 < 3and t1."C 1" < 100orderby1; select c2, sum from"S 1"."T 1" t1, lateral (select sum(t2.c1 + t1."C 1") sum from ft2 t2 groupby t2.c1) qry where t1.c2 * 2 = qry.sum and t1.c2 < 3and t1."C 1" < 100orderby1;
reset enable_hashagg;
-- bug #15613: bad plan for foreign table scan with lateral reference EXPLAIN (VERBOSE, COSTS OFF) SELECT ref_0.c2, subq_1.* FROM "S 1"."T 1"AS ref_0,
LATERAL ( SELECT ref_0."C 1" c1, subq_0.* FROM (SELECT ref_0.c2, ref_1.c3 FROM ft1 AS ref_1) AS subq_0 RIGHTJOIN ft2 AS ref_3 ON (subq_0.c3 = ref_3.c3)
) AS subq_1 WHERE ref_0."C 1" < 10AND subq_1.c3 = '00001' ORDERBY ref_0."C 1";
SELECT ref_0.c2, subq_1.* FROM "S 1"."T 1"AS ref_0,
LATERAL ( SELECT ref_0."C 1" c1, subq_0.* FROM (SELECT ref_0.c2, ref_1.c3 FROM ft1 AS ref_1) AS subq_0 RIGHTJOIN ft2 AS ref_3 ON (subq_0.c3 = ref_3.c3)
) AS subq_1 WHERE ref_0."C 1" < 10AND subq_1.c3 = '00001' ORDERBY ref_0."C 1";
-- Check with placeHolderVars explain (verbose, costs off) select sum(q.a), count(q.b) from ft4 leftjoin (select13, avg(ft1.c1), sum(ft2.c1) from ft1 rightjoin ft2 on (ft1.c1 = ft2.c1)) q(a, b, c) on (ft4.c1 <= q.b); select sum(q.a), count(q.b) from ft4 leftjoin (select13, avg(ft1.c1), sum(ft2.c1) from ft1 rightjoin ft2 on (ft1.c1 = ft2.c1)) q(a, b, c) on (ft4.c1 <= q.b);
-- Not supported cases -- Grouping sets explain (verbose, costs off) select c2, sum(c1) from ft1 where c2 < 3groupby rollup(c2) orderby1 nulls last; select c2, sum(c1) from ft1 where c2 < 3groupby rollup(c2) orderby1 nulls last; explain (verbose, costs off) select c2, sum(c1) from ft1 where c2 < 3groupby cube(c2) orderby1 nulls last; select c2, sum(c1) from ft1 where c2 < 3groupby cube(c2) orderby1 nulls last; explain (verbose, costs off) select c2, c6, sum(c1) from ft1 where c2 < 3groupby grouping sets(c2, c6) orderby1 nulls last, 2 nulls last; select c2, c6, sum(c1) from ft1 where c2 < 3groupby grouping sets(c2, c6) orderby1 nulls last, 2 nulls last; explain (verbose, costs off) select c2, sum(c1), grouping(c2) from ft1 where c2 < 3groupby c2 orderby1 nulls last; select c2, sum(c1), grouping(c2) from ft1 where c2 < 3groupby c2 orderby1 nulls last;
-- DISTINCT itself is not pushed down, whereas underneath aggregate is pushed explain (verbose, costs off) selectdistinct sum(c1)/1000 s from ft2 where c2 < 6groupby c2 orderby1; selectdistinct sum(c1)/1000 s from ft2 where c2 < 6groupby c2 orderby1;
-- WindowAgg explain (verbose, costs off) select c2, sum(c2), count(c2) over (partition by c2%2) from ft2 where c2 < 10groupby c2 orderby1; select c2, sum(c2), count(c2) over (partition by c2%2) from ft2 where c2 < 10groupby c2 orderby1; explain (verbose, costs off) select c2, array_agg(c2) over (partition by c2%2orderby c2 desc) from ft1 where c2 < 10groupby c2 orderby1; select c2, array_agg(c2) over (partition by c2%2orderby c2 desc) from ft1 where c2 < 10groupby c2 orderby1; explain (verbose, costs off) select c2, array_agg(c2) over (partition by c2%2orderby c2 range between current row and unbounded following) from ft1 where c2 < 10groupby c2 orderby1; select c2, array_agg(c2) over (partition by c2%2orderby c2 range between current row and unbounded following) from ft1 where c2 < 10groupby c2 orderby1;
-- =================================================================== -- parameterized queries -- =================================================================== -- simple join
PREPARE st1(int, int) ASSELECT t1.c3, t2.c3 FROM ft1 t1, ft2 t2 WHERE t1.c1 = $1AND t2.c1 = $2; EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st1(1, 2);
EXECUTE st1(1, 1);
EXECUTE st1(101, 101); SET enable_hashjoin TO off; SET enable_sort TO off; -- subquery using stable function (can't be sent to remote)
PREPARE st2(int) ASSELECT * FROM ft1 t1 WHERE t1.c1 < $2AND t1.c3 IN (SELECT c3 FROM ft2 t2 WHERE c1 > $1AND date(c4) = '1970-01-17'::date) ORDERBY c1; EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st2(10, 20);
EXECUTE st2(10, 20);
EXECUTE st2(101, 121);
RESET enable_hashjoin;
RESET enable_sort; -- subquery using immutable function (can be sent to remote)
PREPARE st3(int) ASSELECT * FROM ft1 t1 WHERE t1.c1 < $2AND t1.c3 IN (SELECT c3 FROM ft2 t2 WHERE c1 > $1AND date(c5) = '1970-01-17'::date) ORDERBY c1; EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st3(10, 20);
EXECUTE st3(10, 20);
EXECUTE st3(20, 30); -- custom plan should be chosen initially
PREPARE st4(int) ASSELECT * FROM ft1 t1 WHERE t1.c1 = $1; EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); -- once we try it enough times, should switch to generic plan EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); -- value of $1 should not be sent to remote
PREPARE st5(user_enum,int) ASSELECT * FROM ft1 t1 WHERE c8 = $1and c1 = $2; EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1); EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1); EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1); EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1); EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1); EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1);
EXECUTE st5('foo', 1);
-- System columns, except ctid and oid, should not be sent to remote EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.tableoid = 'pg_class'::regclass LIMIT1; SELECT * FROM ft1 t1 WHERE t1.tableoid = 'ft1'::regclass LIMIT1; EXPLAIN (VERBOSE, COSTS OFF) SELECT tableoid::regclass, * FROM ft1 t1 LIMIT1; SELECT tableoid::regclass, * FROM ft1 t1 LIMIT1; EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.ctid = '(0,2)'; SELECT * FROM ft1 t1 WHERE t1.ctid = '(0,2)'; EXPLAIN (VERBOSE, COSTS OFF) SELECT ctid, * FROM ft1 t1 LIMIT1; SELECT ctid, * FROM ft1 t1 LIMIT1;
-- =================================================================== -- used in PL/pgSQL function -- =================================================================== CREATEORREPLACE FUNCTION f_test(p_c1 int) RETURNS intAS $$ DECLARE
v_c1 int;
BEGIN SELECT c1 INTO v_c1 FROM ft1 WHERE c1 = p_c1 LIMIT1;
PERFORM c1 FROM ft1 WHERE c1 = p_c1 AND p_c1 = v_c1 LIMIT1; RETURN v_c1;
END;
$$ LANGUAGE plpgsql; SELECT f_test(100); DROP FUNCTION f_test(int);
-- =================================================================== -- REINDEX -- =================================================================== -- remote table is not created here CREATEFOREIGNTABLE reindex_foreign (c1 int, c2 int)
SERVER loopback2 OPTIONS (table_name 'reindex_local');
REINDEX TABLE reindex_foreign; -- error
REINDEX TABLE CONCURRENTLY reindex_foreign; -- error DROPFOREIGNTABLE reindex_foreign; -- partitions and foreign tables CREATETABLE reind_fdw_parent (c1 int) PARTITION BY RANGE (c1); CREATETABLE reind_fdw_0_10 PARTITION OF reind_fdw_parent FORVALUESFROM (0) TO (10); CREATEFOREIGNTABLE reind_fdw_10_20 PARTITION OF reind_fdw_parent FORVALUESFROM (10) TO (20)
SERVER loopback OPTIONS (table_name 'reind_local_10_20');
REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok DROPTABLE reind_fdw_parent;
-- =================================================================== -- conversion error -- =================================================================== ALTERFOREIGNTABLE ft1 ALTERCOLUMN c8 TYPE int; SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR SELECT ftx.x1, ft2.c2, ftx.x8 FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2 WHERE ftx.x1 = ft2.c1 AND ftx.x1 = 1; -- ERROR SELECT ftx.x1, ft2.c2, ftx FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2 WHERE ftx.x1 = ft2.c1 AND ftx.x1 = 1; -- ERROR SELECT sum(c2), array_agg(c8) FROM ft1 GROUPBY c8; -- ERROR ANALYZE ft1; -- ERROR ALTERFOREIGNTABLE ft1 ALTERCOLUMN c8 TYPE user_enum;
-- =================================================================== -- local type can be different from remote type in some cases, -- in particular if similarly-named operators do equivalent things -- =================================================================== ALTERFOREIGNTABLE ft1 ALTERCOLUMN c8 TYPE text; EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 WHERE c8 = 'foo'LIMIT1; SELECT * FROM ft1 WHERE c8 = 'foo'LIMIT1; EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 WHERE'foo' = c8 LIMIT1; SELECT * FROM ft1 WHERE'foo' = c8 LIMIT1; -- we declared c8 to be text locally, but it's still the same type on -- the remote which will balk if we try to do anything incompatible -- with that remote type SELECT * FROM ft1 WHERE c8 LIKE'foo'LIMIT1; -- ERROR SELECT * FROM ft1 WHERE c8::text LIKE'foo'LIMIT1; -- ERROR; cast not pushed down ALTERFOREIGNTABLE ft1 ALTERCOLUMN c8 TYPE user_enum;
-- =================================================================== -- test handling of collations -- =================================================================== createtable loct3 (f1 text collate"C"unique, f2 text, f3 varchar(10) unique); createforeigntable ft3 (f1 text collate"C", f2 text, f3 varchar(10))
server loopback options (table_name 'loct3', use_remote_estimate 'true');
-- can be sent to remote explain (verbose, costs off) select * from ft3 where f1 = 'foo'; explain (verbose, costs off) select * from ft3 where f1 COLLATE"C" = 'foo'; explain (verbose, costs off) select * from ft3 where f2 = 'foo'; explain (verbose, costs off) select * from ft3 where f3 = 'foo'; explain (verbose, costs off) select * from ft3 f, loct3 l where f.f3 = l.f3 and l.f1 = 'foo'; -- can't be sent to remote explain (verbose, costs off) select * from ft3 where f1 COLLATE"POSIX" = 'foo'; explain (verbose, costs off) select * from ft3 where f1 = 'foo'COLLATE"C"; explain (verbose, costs off) select * from ft3 where f2 COLLATE"C" = 'foo'; explain (verbose, costs off) select * from ft3 where f2 = 'foo'COLLATE"C"; explain (verbose, costs off) select * from ft3 f, loct3 l where f.f3 = l.f3 COLLATE"POSIX"and l.f1 = 'foo';
-- =================================================================== -- test SEMI-JOIN pushdown -- =================================================================== EXPLAIN (verbose, costs off) SELECT ft2.*, ft4.* FROM ft2 INNERJOIN ft4 ON ft2.c2 = ft4.c1 WHERE ft2.c1 > 900 ANDEXISTS (SELECT1FROM ft5 WHERE ft4.c1 = ft5.c1) ORDERBY ft2.c1; SELECT ft2.*, ft4.* FROM ft2 INNERJOIN ft4 ON ft2.c2 = ft4.c1 WHERE ft2.c1 > 900 ANDEXISTS (SELECT1FROM ft5 WHERE ft4.c1 = ft5.c1) ORDERBY ft2.c1;
-- The same query, different join order EXPLAIN (verbose, costs off) SELECT ft2.*, ft4.* FROM ft2 INNERJOIN
(SELECT * FROM ft4 WHERE EXISTS (SELECT1FROM ft5 WHERE ft4.c1 = ft5.c1)) ft4 ON ft2.c2 = ft4.c1 WHERE ft2.c1 > 900 ORDERBY ft2.c1; SELECT ft2.*, ft4.* FROM ft2 INNERJOIN
(SELECT * FROM ft4 WHERE EXISTS (SELECT1FROM ft5 WHERE ft4.c1 = ft5.c1)) ft4 ON ft2.c2 = ft4.c1 WHERE ft2.c1 > 900 ORDERBY ft2.c1;
-- Left join EXPLAIN (verbose, costs off) SELECT ft2.*, ft4.* FROM ft2 LEFTJOIN
(SELECT * FROM ft4 WHERE EXISTS (SELECT1FROM ft5 WHERE ft4.c1 = ft5.c1)) ft4 ON ft2.c2 = ft4.c1 WHERE ft2.c1 > 900 ORDERBY ft2.c1 LIMIT10; SELECT ft2.*, ft4.* FROM ft2 LEFTJOIN
(SELECT * FROM ft4 WHERE EXISTS (SELECT1FROM ft5 WHERE ft4.c1 = ft5.c1)) ft4 ON ft2.c2 = ft4.c1 WHERE ft2.c1 > 900 ORDERBY ft2.c1 LIMIT10;
-- Several semi-joins per upper level join EXPLAIN (verbose, costs off) SELECT ft2.*, ft4.* FROM ft2 INNERJOIN
(SELECT * FROM ft4 WHERE EXISTS (SELECT1FROM ft5 WHERE ft4.c1 = ft5.c1)) ft4 ON ft2.c2 = ft4.c1 INNERJOIN (SELECT * FROM ft5 WHERE EXISTS (SELECT1FROM ft4 WHERE ft4.c1 = ft5.c1)) ft5 ON ft2.c2 <= ft5.c1 WHERE ft2.c1 > 900 ORDERBY ft2.c1 LIMIT10; SELECT ft2.*, ft4.* FROM ft2 INNERJOIN
(SELECT * FROM ft4 WHERE EXISTS (SELECT1FROM ft5 WHERE ft4.c1 = ft5.c1)) ft4 ON ft2.c2 = ft4.c1 INNERJOIN (SELECT * FROM ft5 WHERE EXISTS (SELECT1FROM ft4 WHERE ft4.c1 = ft5.c1)) ft5 ON ft2.c2 <= ft5.c1 WHERE ft2.c1 > 900 ORDERBY ft2.c1 LIMIT10;
-- Semi-join below Semi-join EXPLAIN (verbose, costs off) SELECT ft2.* FROM ft2 WHERE
c1 = ANY ( SELECT c1 FROM ft2 WHERE EXISTS (SELECT1FROM ft4 WHERE ft4.c2 = ft2.c2)) AND ft2.c1 > 900 ORDERBY ft2.c1 LIMIT10; SELECT ft2.* FROM ft2 WHERE
c1 = ANY ( SELECT c1 FROM ft2 WHERE EXISTS (SELECT1FROM ft4 WHERE ft4.c2 = ft2.c2)) AND ft2.c1 > 900 ORDERBY ft2.c1 LIMIT10;
-- Upper level relations shouldn't refer EXISTS() subqueries EXPLAIN (verbose, costs off) SELECT * FROM ft2 ftupper WHERE EXISTS ( SELECT c1 FROM ft2 WHERE EXISTS (SELECT1FROM ft4 WHERE ft4.c2 = ft2.c2) AND c1 = ftupper.c1 ) AND ftupper.c1 > 900 ORDERBY ftupper.c1 LIMIT10; SELECT * FROM ft2 ftupper WHERE EXISTS ( SELECT c1 FROM ft2 WHERE EXISTS (SELECT1FROM ft4 WHERE ft4.c2 = ft2.c2) AND c1 = ftupper.c1 ) AND ftupper.c1 > 900 ORDERBY ftupper.c1 LIMIT10;
-- EXISTS should be propagated to the highest upper inner join EXPLAIN (verbose, costs off) SELECT ft2.*, ft4.* FROM ft2 INNERJOIN
(SELECT * FROM ft4 WHEREEXISTS ( SELECT1FROM ft2 WHERE ft2.c2 = ft4.c2)) ft4 ON ft2.c2 = ft4.c1 INNERJOIN
(SELECT * FROM ft2 WHEREEXISTS ( SELECT1FROM ft4 WHERE ft2.c2 = ft4.c2)) ft21 ON ft2.c2 = ft21.c2 WHERE ft2.c1 > 900 ORDERBY ft2.c1 LIMIT10; SELECT ft2.*, ft4.* FROM ft2 INNERJOIN
(SELECT * FROM ft4 WHEREEXISTS ( SELECT1FROM ft2 WHERE ft2.c2 = ft4.c2)) ft4 ON ft2.c2 = ft4.c1 INNERJOIN
(SELECT * FROM ft2 WHEREEXISTS ( SELECT1FROM ft4 WHERE ft2.c2 = ft4.c2)) ft21 ON ft2.c2 = ft21.c2 WHERE ft2.c1 > 900 ORDERBY ft2.c1 LIMIT10;
-- Semi-join conditions shouldn't pop up as left/right join clauses. SET enable_material TO off; EXPLAIN (verbose, costs off) SELECT x1.c1 FROM
(SELECT * FROM ft2 WHEREEXISTS (SELECT1FROM ft4 WHERE ft4.c1 = ft2.c1 AND ft2.c2 < 10)) x1 RIGHTJOIN
(SELECT * FROM ft2 WHEREEXISTS (SELECT1FROM ft4 WHERE ft4.c1 = ft2.c1 AND ft2.c2 < 10)) x2 ON (x1.c1 = x2.c1) ORDERBY x1.c1 LIMIT10; SELECT x1.c1 FROM
(SELECT * FROM ft2 WHEREEXISTS (SELECT1FROM ft4 WHERE ft4.c1 = ft2.c1 AND ft2.c2 < 10)) x1 RIGHTJOIN
(SELECT * FROM ft2 WHEREEXISTS (SELECT1FROM ft4 WHERE ft4.c1 = ft2.c1 AND ft2.c2 < 10)) x2 ON (x1.c1 = x2.c1) ORDERBY x1.c1 LIMIT10;
RESET enable_material;
-- Can't push down semi-join with inner rel vars in targetlist EXPLAIN (verbose, costs off) SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
ft1.c1 IN ( SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1) ORDERBY ft1.c1 LIMIT5;
-- =================================================================== -- test writable foreign table stuff -- =================================================================== EXPLAIN (verbose, costs off) INSERTINTO ft2 (c1,c2,c3) SELECT c1+1000,c2+100, c3 || c3 FROM ft2 LIMIT20; INSERTINTO ft2 (c1,c2,c3) SELECT c1+1000,c2+100, c3 || c3 FROM ft2 LIMIT20; INSERTINTO ft2 (c1,c2,c3) VALUES (1101,201,'aaa'), (1102,202,'bbb'), (1103,203,'ccc') RETURNING old, new, old.*, new.*; INSERTINTO ft2 (c1,c2,c3) VALUES (1104,204,'ddd'), (1105,205,'eee'); EXPLAIN (verbose, costs off) UPDATE ft2 SET c2 = c2 + 300, c3 = c3 || '_update3'WHERE c1 % 10 = 3; -- can be pushed down UPDATE ft2 SET c2 = c2 + 300, c3 = c3 || '_update3'WHERE c1 % 10 = 3; EXPLAIN (verbose, costs off) UPDATE ft2 SET c2 = c2 + 400, c3 = c3 || '_update7'WHERE c1 % 10 = 7 RETURNING *; -- can be pushed down UPDATE ft2 SET c2 = c2 + 400, c3 = c3 || '_update7'WHERE c1 % 10 = 7 RETURNING *;
BEGIN; EXPLAIN (verbose, costs off) UPDATE ft2 SET c2 = c2 + 400, c3 = c3 || '_update7b'WHERE c1 % 10 = 7AND c1 < 40
RETURNING old.*, new.*; -- can't be pushed down UPDATE ft2 SET c2 = c2 + 400, c3 = c3 || '_update7b'WHERE c1 % 10 = 7AND c1 < 40
RETURNING old.*, new.*;
ROLLBACK; EXPLAIN (verbose, costs off) UPDATE ft2 SET c2 = ft2.c2 + 500, c3 = ft2.c3 || '_update9', c7 = DEFAULT FROM ft1 WHERE ft1.c1 = ft2.c2 AND ft1.c1 % 10 = 9; -- can be pushed down UPDATE ft2 SET c2 = ft2.c2 + 500, c3 = ft2.c3 || '_update9', c7 = DEFAULT FROM ft1 WHERE ft1.c1 = ft2.c2 AND ft1.c1 % 10 = 9; EXPLAIN (verbose, costs off) DELETEFROM ft2 WHERE c1 % 10 = 5 RETURNING c1, c4; -- can be pushed down DELETEFROM ft2 WHERE c1 % 10 = 5 RETURNING c1, c4;
BEGIN; EXPLAIN (verbose, costs off) DELETEFROM ft2 WHERE c1 % 10 = 6AND c1 < 40 RETURNING old.c1, c4; -- can't be pushed down DELETEFROM ft2 WHERE c1 % 10 = 6AND c1 < 40 RETURNING old.c1, c4;
ROLLBACK; EXPLAIN (verbose, costs off) DELETEFROM ft2 USING ft1 WHERE ft1.c1 = ft2.c2 AND ft1.c1 % 10 = 2; -- can be pushed down DELETEFROM ft2 USING ft1 WHERE ft1.c1 = ft2.c2 AND ft1.c1 % 10 = 2; SELECT c1,c2,c3,c4 FROM ft2 ORDERBY c1; EXPLAIN (verbose, costs off) INSERTINTO ft2 (c1,c2,c3) VALUES (1200,999,'foo') RETURNING tableoid::regclass; INSERTINTO ft2 (c1,c2,c3) VALUES (1200,999,'foo') RETURNING tableoid::regclass; EXPLAIN (verbose, costs off) UPDATE ft2 SET c3 = 'bar'WHERE c1 = 1200 RETURNING tableoid::regclass; -- can be pushed down UPDATE ft2 SET c3 = 'bar'WHERE c1 = 1200 RETURNING tableoid::regclass; EXPLAIN (verbose, costs off) DELETEFROM ft2 WHERE c1 = 1200 RETURNING tableoid::regclass; -- can be pushed down DELETEFROM ft2 WHERE c1 = 1200 RETURNING tableoid::regclass;
-- Test UPDATE/DELETE with RETURNING on a three-table join INSERTINTO ft2 (c1,c2,c3) SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id; EXPLAIN (verbose, costs off) UPDATE ft2 SET c3 = 'foo' FROM ft4 INNERJOIN ft5 ON (ft4.c1 = ft5.c1) WHERE ft2.c1 > 1200AND ft2.c2 = ft4.c1
RETURNING ft2, ft2.*, ft4, ft4.*; -- can be pushed down UPDATE ft2 SET c3 = 'foo' FROM ft4 INNERJOIN ft5 ON (ft4.c1 = ft5.c1) WHERE ft2.c1 > 1200AND ft2.c2 = ft4.c1
RETURNING ft2, ft2.*, ft4, ft4.*;
BEGIN; EXPLAIN (verbose, costs off) UPDATE ft2 SET c3 = 'bar' FROM ft4 INNERJOIN ft5 ON (ft4.c1 = ft5.c1) WHERE ft2.c1 > 1200AND ft2.c2 = ft4.c1
RETURNING old, new, ft2, ft2.*, ft4, ft4.*; -- can't be pushed down UPDATE ft2 SET c3 = 'bar' FROM ft4 INNERJOIN ft5 ON (ft4.c1 = ft5.c1) WHERE ft2.c1 > 1200AND ft2.c2 = ft4.c1
RETURNING old, new, ft2, ft2.*, ft4, ft4.*;
ROLLBACK; EXPLAIN (verbose, costs off) DELETEFROM ft2 USING ft4 LEFTJOIN ft5 ON (ft4.c1 = ft5.c1) WHERE ft2.c1 > 1200AND ft2.c1 % 10 = 0AND ft2.c2 = ft4.c1
RETURNING 100; -- can be pushed down DELETEFROM ft2 USING ft4 LEFTJOIN ft5 ON (ft4.c1 = ft5.c1) WHERE ft2.c1 > 1200AND ft2.c1 % 10 = 0AND ft2.c2 = ft4.c1
RETURNING 100; DELETEFROM ft2 WHERE ft2.c1 > 1200;
-- Test UPDATE with a MULTIEXPR sub-select -- (maybe someday this'll be remotely executable, but not today) EXPLAIN (verbose, costs off) UPDATE ft2 AS target SET (c2, c7) = ( SELECT c2 * 10, c7 FROM ft2 AS src WHERE target.c1 = src.c1
) WHERE c1 > 1100; UPDATE ft2 AS target SET (c2, c7) = ( SELECT c2 * 10, c7 FROM ft2 AS src WHERE target.c1 = src.c1
) WHERE c1 > 1100;
UPDATE ft2 AS target SET (c2) = ( SELECT c2 / 10 FROM ft2 AS src WHERE target.c1 = src.c1
) WHERE c1 > 1100;
-- Test UPDATE involving a join that can be pushed down, -- but a SET clause that can't be EXPLAIN (VERBOSE, COSTS OFF) UPDATE ft2 d SET c2 = CASEWHEN random() >= 0THEN d.c2 ELSE0 END FROM ft2 AS t WHERE d.c1 = t.c1 AND d.c1 > 1000; UPDATE ft2 d SET c2 = CASEWHEN random() >= 0THEN d.c2 ELSE0 END FROM ft2 AS t WHERE d.c1 = t.c1 AND d.c1 > 1000;
-- Test UPDATE/DELETE with WHERE or JOIN/ON conditions containing -- user-defined operators/functions ALTER SERVER loopback OPTIONS (DROP extensions); INSERTINTO ft2 (c1,c2,c3) SELECT id, id % 10, to_char(id, 'FM00000') FROM generate_series(2001, 2010) id;
-- this will do a remote seqscan, causing unstable result order, so sort EXPLAIN (verbose, costs off) WITH cte AS ( UPDATE ft2 SET c3 = 'bar'WHERE postgres_fdw_abs(c1) > 2000 RETURNING *
) SELECT * FROM cte ORDERBY c1; -- can't be pushed down WITH cte AS ( UPDATE ft2 SET c3 = 'bar'WHERE postgres_fdw_abs(c1) > 2000 RETURNING *
) SELECT * FROM cte ORDERBY c1;
EXPLAIN (verbose, costs off) UPDATE ft2 SET c3 = 'baz' FROM ft4 INNERJOIN ft5 ON (ft4.c1 = ft5.c1) WHERE ft2.c1 > 2000AND ft2.c2 === ft4.c1
RETURNING ft2.*, ft4.*, ft5.*; -- can't be pushed down UPDATE ft2 SET c3 = 'baz' FROM ft4 INNERJOIN ft5 ON (ft4.c1 = ft5.c1) WHERE ft2.c1 > 2000AND ft2.c2 === ft4.c1
RETURNING ft2.*, ft4.*, ft5.*; EXPLAIN (verbose, costs off) DELETEFROM ft2 USING ft4 INNERJOIN ft5 ON (ft4.c1 === ft5.c1) WHERE ft2.c1 > 2000AND ft2.c2 = ft4.c1
RETURNING ft2.c1, ft2.c2, ft2.c3; -- can't be pushed down DELETEFROM ft2 USING ft4 INNERJOIN ft5 ON (ft4.c1 === ft5.c1) WHERE ft2.c1 > 2000AND ft2.c2 = ft4.c1
RETURNING ft2.c1, ft2.c2, ft2.c3; DELETEFROM ft2 WHERE ft2.c1 > 2000; ALTER SERVER loopback OPTIONS (ADD extensions 'postgres_fdw');
-- Test that trigger on remote table works as expected CREATEORREPLACE FUNCTION "S 1".F_BRTRIG() RETURNS triggerAS $$
BEGIN
NEW.c3 = NEW.c3 || '_trig_update'; RETURN NEW;
END;
$$ LANGUAGE plpgsql; CREATETRIGGER t1_br_insert BEFOREINSERTORUPDATE ON"S 1"."T 1"FOREACH ROW EXECUTE PROCEDURE"S 1".F_BRTRIG();
-- Test errors thrown on remote side during update ALTERTABLE"S 1"."T 1"ADDCONSTRAINT c2positive CHECK (c2 >= 0);
INSERTINTO ft1(c1, c2) VALUES(11, 12); -- duplicate key INSERTINTO ft1(c1, c2) VALUES(11, 12) ON CONFLICT DO NOTHING; -- works INSERTINTO ft1(c1, c2) VALUES(11, 12) ON CONFLICT (c1, c2) DO NOTHING; -- unsupported INSERTINTO ft1(c1, c2) VALUES(11, 12) ON CONFLICT (c1, c2) DO UPDATESET c3 = 'ffg'; -- unsupported INSERTINTO ft1(c1, c2) VALUES(1111, -2); -- c2positive UPDATE ft1 SET c2 = -c2 WHERE c1 = 1; -- c2positive
-- Test savepoint/rollback behavior select c2, count(*) from ft2 where c2 < 500groupby1orderby1; select c2, count(*) from"S 1"."T 1"where c2 < 500groupby1orderby1;
begin; update ft2 set c2 = 42where c2 = 0; select c2, count(*) from ft2 where c2 < 500groupby1orderby1;
savepoint s1; update ft2 set c2 = 44where c2 = 4; select c2, count(*) from ft2 where c2 < 500groupby1orderby1; release savepoint s1; select c2, count(*) from ft2 where c2 < 500groupby1orderby1;
savepoint s2; update ft2 set c2 = 46where c2 = 6; select c2, count(*) from ft2 where c2 < 500groupby1orderby1;
rollback to savepoint s2; select c2, count(*) from ft2 where c2 < 500groupby1orderby1; release savepoint s2; select c2, count(*) from ft2 where c2 < 500groupby1orderby1;
savepoint s3; update ft2 set c2 = -2where c2 = 42and c1 = 10; -- fail on remote side
rollback to savepoint s3; select c2, count(*) from ft2 where c2 < 500groupby1orderby1; release savepoint s3; select c2, count(*) from ft2 where c2 < 500groupby1orderby1; -- none of the above is committed yet remotely select c2, count(*) from"S 1"."T 1"where c2 < 500groupby1orderby1; commit; select c2, count(*) from ft2 where c2 < 500groupby1orderby1; select c2, count(*) from"S 1"."T 1"where c2 < 500groupby1orderby1;
VACUUM ANALYZE"S 1"."T 1";
-- Above DMLs add data with c6 as NULL in ft1, so test ORDER BY NULLS LAST and NULLs -- FIRST behavior here. -- ORDER BY DESC NULLS LAST options EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 ORDERBY c6 DESC NULLS LAST, c1 OFFSET 795LIMIT10; SELECT * FROM ft1 ORDERBY c6 DESC NULLS LAST, c1 OFFSET 795LIMIT10; -- ORDER BY DESC NULLS FIRST options EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 ORDERBY c6 DESC NULLS FIRST, c1 OFFSET 15LIMIT10; SELECT * FROM ft1 ORDERBY c6 DESC NULLS FIRST, c1 OFFSET 15LIMIT10; -- ORDER BY ASC NULLS FIRST options EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 ORDERBY c6 ASC NULLS FIRST, c1 OFFSET 15LIMIT10; SELECT * FROM ft1 ORDERBY c6 ASC NULLS FIRST, c1 OFFSET 15LIMIT10;
-- Test ReScan code path that recreates the cursor even when no parameters -- change (bug #17889) CREATETABLE loct1 (c1 int); CREATETABLE loct2 (c1 int, c2 text); INSERTINTO loct1 VALUES (1001); INSERTINTO loct1 VALUES (1002); INSERTINTO loct2 SELECT id, to_char(id, 'FM0000') FROM generate_series(1, 1000) id; INSERTINTO loct2 VALUES (1001, 'foo'); INSERTINTO loct2 VALUES (1002, 'bar'); CREATEFOREIGNTABLE remt2 (c1 int, c2 text) SERVER loopback OPTIONS (table_name 'loct2'); ANALYZE loct1; ANALYZE remt2; SET enable_mergejoin TOfalse; SET enable_hashjoin TOfalse; SET enable_material TOfalse; EXPLAIN (VERBOSE, COSTS OFF) UPDATE remt2 SET c2 = remt2.c2 || remt2.c2 FROM loct1 WHERE loct1.c1 = remt2.c1 RETURNING remt2.*; UPDATE remt2 SET c2 = remt2.c2 || remt2.c2 FROM loct1 WHERE loct1.c1 = remt2.c1 RETURNING remt2.*;
RESET enable_mergejoin;
RESET enable_hashjoin;
RESET enable_material; DROPFOREIGNTABLE remt2; DROPTABLE loct1; DROPTABLE loct2;
-- =================================================================== -- test check constraints -- ===================================================================
-- Consistent check constraints provide consistent results ALTERFOREIGNTABLE ft1 ADDCONSTRAINT ft1_c2positive CHECK (c2 >= 0); EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 < 0; SELECT count(*) FROM ft1 WHERE c2 < 0; SET constraint_exclusion = 'on'; EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 < 0; SELECT count(*) FROM ft1 WHERE c2 < 0;
RESET constraint_exclusion; -- check constraint is enforced on the remote side, not locally INSERTINTO ft1(c1, c2) VALUES(1111, -2); -- c2positive UPDATE ft1 SET c2 = -c2 WHERE c1 = 1; -- c2positive ALTERFOREIGNTABLE ft1 DROPCONSTRAINT ft1_c2positive;
-- But inconsistent check constraints provide inconsistent results ALTERFOREIGNTABLE ft1 ADDCONSTRAINT ft1_c2negative CHECK (c2 < 0); EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 >= 0; SELECT count(*) FROM ft1 WHERE c2 >= 0; SET constraint_exclusion = 'on'; EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 >= 0; SELECT count(*) FROM ft1 WHERE c2 >= 0;
RESET constraint_exclusion; -- local check constraint is not actually enforced INSERTINTO ft1(c1, c2) VALUES(1111, 2); UPDATE ft1 SET c2 = c2 + 1WHERE c1 = 1; ALTERFOREIGNTABLE ft1 DROPCONSTRAINT ft1_c2negative;
-- =================================================================== -- test WITH CHECK OPTION constraints -- ===================================================================
CREATE FUNCTION row_before_insupd_trigfunc() RETURNS triggerAS $$BEGIN NEW.a := NEW.a + 10; RETURN NEW; END$$ LANGUAGE plpgsql;
CREATETABLE base_tbl (a int, b int); ALTERTABLE base_tbl SET (autovacuum_enabled = 'false'); CREATETRIGGER row_before_insupd_trigger BEFOREINSERTORUPDATEON base_tbl FOREACH ROW EXECUTE PROCEDURE row_before_insupd_trigfunc(); CREATEFOREIGNTABLE foreign_tbl (a int, b int)
SERVER loopback OPTIONS (table_name 'base_tbl'); CREATE VIEW rw_view ASSELECT * FROM foreign_tbl WHERE a < b WITHCHECKOPTION;
\d+ rw_view
EXPLAIN (VERBOSE, COSTS OFF) UPDATE rw_view SET b = b + 5; UPDATE rw_view SET b = b + 5; -- should fail EXPLAIN (VERBOSE, COSTS OFF) UPDATE rw_view SET b = b + 15; UPDATE rw_view SET b = b + 15; -- ok SELECT * FROM foreign_tbl;
-- We don't allow batch insert when there are any WCO constraints ALTER SERVER loopback OPTIONS (ADD batch_size '10'); EXPLAIN (VERBOSE, COSTS OFF) INSERTINTO rw_view VALUES (0, 15), (0, 5); INSERTINTO rw_view VALUES (0, 15), (0, 5); -- should fail SELECT * FROM foreign_tbl; ALTER SERVER loopback OPTIONS (DROP batch_size);
DROPFOREIGNTABLE foreign_tbl CASCADE; DROPTRIGGER row_before_insupd_trigger ON base_tbl; DROPTABLE base_tbl;
-- test WCO for partitions
CREATETABLE child_tbl (a int, b int); ALTERTABLE child_tbl SET (autovacuum_enabled = 'false'); CREATETRIGGER row_before_insupd_trigger BEFOREINSERTORUPDATEON child_tbl FOREACH ROW EXECUTE PROCEDURE row_before_insupd_trigfunc(); CREATEFOREIGNTABLE foreign_tbl (a int, b int)
SERVER loopback OPTIONS (table_name 'child_tbl');
CREATETABLE parent_tbl (a int, b int) PARTITION BY RANGE(a); ALTERTABLE parent_tbl ATTACH PARTITION foreign_tbl FORVALUESFROM (0) TO (100); -- Detach and re-attach once, to stress the concurrent detach case. ALTERTABLE parent_tbl DETACH PARTITION foreign_tbl CONCURRENTLY; ALTERTABLE parent_tbl ATTACH PARTITION foreign_tbl FORVALUESFROM (0) TO (100);
CREATE VIEW rw_view ASSELECT * FROM parent_tbl WHERE a < b WITHCHECKOPTION;
\d+ rw_view
EXPLAIN (VERBOSE, COSTS OFF) UPDATE rw_view SET b = b + 5; UPDATE rw_view SET b = b + 5; -- should fail EXPLAIN (VERBOSE, COSTS OFF) UPDATE rw_view SET b = b + 15; UPDATE rw_view SET b = b + 15; -- ok SELECT * FROM foreign_tbl;
-- We don't allow batch insert when there are any WCO constraints ALTER SERVER loopback OPTIONS (ADD batch_size '10'); EXPLAIN (VERBOSE, COSTS OFF) INSERTINTO rw_view VALUES (0, 15), (0, 5); INSERTINTO rw_view VALUES (0, 15), (0, 5); -- should fail SELECT * FROM foreign_tbl; ALTER SERVER loopback OPTIONS (DROP batch_size);
DROPFOREIGNTABLE foreign_tbl CASCADE; DROPTRIGGER row_before_insupd_trigger ON child_tbl; DROPTABLE parent_tbl CASCADE;
DROP FUNCTION row_before_insupd_trigfunc;
-- Try a more complex permutation of WCO where there are multiple levels of -- partitioned tables with columns not all in the same order CREATETABLE parent_tbl (a int, b text, c numeric) PARTITION BY RANGE(a); CREATETABLE sub_parent (c numeric, a int, b text) PARTITION BY RANGE(a); ALTERTABLE parent_tbl ATTACH PARTITION sub_parent FORVALUESFROM (1) TO (10); CREATETABLE child_local (b text, c numeric, a int); CREATEFOREIGNTABLE child_foreign (b text, c numeric, a int)
SERVER loopback OPTIONS (table_name 'child_local'); ALTERTABLE sub_parent ATTACH PARTITION child_foreign FORVALUESFROM (1) TO (10); CREATE VIEW rw_view ASSELECT * FROM parent_tbl WHERE a < 5WITHCHECKOPTION;
INSERTINTO parent_tbl (a) VALUES(1),(5); EXPLAIN (VERBOSE, COSTS OFF) UPDATE rw_view SET b = 'text', c = 123.456; UPDATE rw_view SET b = 'text', c = 123.456; SELECT * FROM parent_tbl ORDERBY a;
-- =================================================================== -- test serial columns (ie, sequence-based defaults) -- =================================================================== createtable loc1 (f1 serial, f2 text); altertable loc1 set (autovacuum_enabled = 'false'); createforeigntable rem1 (f1 serial, f2 text)
server loopback options(table_name 'loc1'); select pg_catalog.setval('rem1_f1_seq', 10, false); insertinto loc1(f2) values('hi'); insertinto rem1(f2) values('hi remote'); insertinto loc1(f2) values('bye'); insertinto rem1(f2) values('bye remote'); select * from loc1; select * from rem1;
-- =================================================================== -- test generated columns -- =================================================================== createtable gloc1 (
a int,
b int generated always as (a * 2) stored,
c int
); altertable gloc1 set (autovacuum_enabled = 'false'); createforeigntable grem1 (
a int,
b int generated always as (a * 2) stored,
c int generated always as (a * 3) virtual
) server loopback options(table_name 'gloc1'); explain (verbose, costs off) insertinto grem1 (a) values (1), (2); insertinto grem1 (a) values (1), (2); explain (verbose, costs off) update grem1 set a = 22where a = 2; update grem1 set a = 22where a = 2; select * from gloc1; select * from grem1; deletefrom grem1;
-- test copy from
copy grem1 from stdin; 1 2
\. select * from gloc1; select * from grem1; deletefrom grem1;
-- test batch insert alter server loopback options (add batch_size '10'); explain (verbose, costs off) insertinto grem1 (a) values (1), (2); insertinto grem1 (a) values (1), (2); select * from gloc1; select * from grem1; deletefrom grem1; -- batch insert with foreign partitions. -- This schema uses two partitions, one local and one remote with a modulo -- to loop across all of them in batches. createtable tab_batch_local (id int, data text); insertinto tab_batch_local select i, 'test'|| i from generate_series(1, 45) i; createtable tab_batch_sharded (id int, data text) partition by hash(id); createtable tab_batch_sharded_p0 partition of tab_batch_sharded forvalueswith (modulus 2, remainder 0); createtable tab_batch_sharded_p1_remote (id int, data text); createforeigntable tab_batch_sharded_p1 partition of tab_batch_sharded forvalueswith (modulus 2, remainder 1)
server loopback options (table_name 'tab_batch_sharded_p1_remote'); insertinto tab_batch_sharded select * from tab_batch_local; select count(*) from tab_batch_sharded; droptable tab_batch_local; droptable tab_batch_sharded; droptable tab_batch_sharded_p1_remote;
alter server loopback options (drop batch_size);
-- =================================================================== -- test local triggers -- ===================================================================
-- Trigger functions "borrowed" from triggers regress test. CREATE FUNCTION trigger_func() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'trigger_func(%) called: action = %, when = %, level = %',
TG_ARGV[0], TG_OP, TG_WHEN, TG_LEVEL; RETURNNULL;
END;$$;
CREATETRIGGER trig_stmt_before BEFOREDELETEORINSERTORUPDATEOR TRUNCATE ON rem1 FOREACH STATEMENT EXECUTE PROCEDURE trigger_func(); CREATETRIGGER trig_stmt_after AFTER DELETEORINSERTORUPDATEOR TRUNCATE ON rem1 FOREACH STATEMENT EXECUTE PROCEDURE trigger_func();
CREATEORREPLACE FUNCTION trigger_data() RETURNS trigger
LANGUAGE plpgsql AS $$
declare
oldnew text[];
relid text;
argstr text;
begin
relid := TG_relid::regclass;
argstr := ''; for i in0 .. TG_nargs - 1loop if i > 0then
argstr := argstr || ', ';
end if;
argstr := argstr || TG_argv[i];
end loop;
RAISE NOTICE '%(%) % % % ON %',
tg_name, argstr, TG_when, TG_level, TG_OP, relid;
oldnew := '{}'::text[]; if TG_OP != 'INSERT'then
oldnew := array_append(oldnew, format('OLD: %s', OLD));
end if;
if TG_OP != 'DELETE'then
oldnew := array_append(oldnew, format('NEW: %s', NEW));
end if;
RAISE NOTICE '%', array_to_string(oldnew, ',');
if TG_OP = 'DELETE'then return OLD; else return NEW;
end if;
end;
$$;
CREATETRIGGER trig_row_after
AFTER INSERTORUPDATEORDELETEON rem1 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo');
deletefrom rem1; insertinto rem1 values(1,'insert'); update rem1 set f2 = 'update'where f1 = 1; update rem1 set f2 = f2 || f2;
truncate rem1;
-- cleanup DROPTRIGGER trig_row_before ON rem1; DROPTRIGGER trig_row_after ON rem1; DROPTRIGGER trig_stmt_before ON rem1; DROPTRIGGER trig_stmt_after ON rem1;
DELETEfrom rem1;
-- Test multiple AFTER ROW triggers on a foreign table CREATETRIGGER trig_row_after1
AFTER INSERTORUPDATEORDELETEON rem1 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo');
CREATETRIGGER trig_row_after2
AFTER INSERTORUPDATEORDELETEON rem1 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo');
insertinto rem1 values(1,'insert'); update rem1 set f2 = 'update'where f1 = 1; update rem1 set f2 = f2 || f2; deletefrom rem1;
-- cleanup DROPTRIGGER trig_row_after1 ON rem1; DROPTRIGGER trig_row_after2 ON rem1;
CREATETRIGGER trig_row_after_delete
AFTER DELETEON rem1 FOREACH ROW WHEN (OLD.f2 like'%update%')
EXECUTE PROCEDURE trigger_data(23,'skidoo');
-- Trigger is fired for f1=2, not for f1=1 DELETEFROM rem1;
-- cleanup DROPTRIGGER trig_row_before_insupd ON rem1; DROPTRIGGER trig_row_after_insupd ON rem1; DROPTRIGGER trig_row_before_delete ON rem1; DROPTRIGGER trig_row_after_delete ON rem1;
-- Test various RETURN statements in BEFORE triggers.
CREATE FUNCTION trig_row_before_insupdate() RETURNS TRIGGERAS $$
BEGIN
NEW.f2 := NEW.f2 || ' triggered !'; RETURN NEW;
END
$$ language plpgsql;
-- The new values should have 'triggered' appended INSERTINTO rem1 values(1, 'insert'); SELECT * from loc1; INSERTINTO rem1 values(2, 'insert') RETURNING f2; SELECT * from loc1; UPDATE rem1 set f2 = ''; SELECT * from loc1; UPDATE rem1 set f2 = 'skidoo' RETURNING f2; SELECT * from loc1;
EXPLAIN (verbose, costs off) UPDATE rem1 set f1 = 10; -- all columns should be transmitted UPDATE rem1 set f1 = 10; SELECT * from loc1;
DELETEFROM rem1;
-- Add a second trigger, to check that the changes are propagated correctly -- from trigger to trigger CREATETRIGGER trig_row_before_insupd2 BEFOREINSERTORUPDATEON rem1 FOREACH ROW EXECUTE PROCEDURE trig_row_before_insupdate();
INSERTINTO rem1 values(1, 'insert'); SELECT * from loc1; INSERTINTO rem1 values(2, 'insert') RETURNING f2; SELECT * from loc1; UPDATE rem1 set f2 = ''; SELECT * from loc1; UPDATE rem1 set f2 = 'skidoo' RETURNING f2; SELECT * from loc1;
DROPTRIGGER trig_row_before_insupd ON rem1; DROPTRIGGER trig_row_before_insupd2 ON rem1;
DELETEfrom rem1;
INSERTINTO rem1 VALUES (1, 'test');
-- Test with a trigger returning NULL CREATE FUNCTION trig_null() RETURNS TRIGGERAS $$
BEGIN RETURNNULL;
END
$$ language plpgsql;
-- Nothing should have changed. INSERTINTO rem1 VALUES (2, 'test2');
SELECT * from loc1;
UPDATE rem1 SET f2 = 'test2';
SELECT * from loc1;
DELETEfrom rem1;
SELECT * from loc1;
DROPTRIGGER trig_null ON rem1; DELETEfrom rem1;
-- Test a combination of local and remote triggers CREATETRIGGER trig_row_before BEFOREINSERTORUPDATEORDELETEON rem1 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo');
CREATETRIGGER trig_row_after
AFTER INSERTORUPDATEORDELETEON rem1 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo');
INSERTINTO rem1(f2) VALUES ('test'); UPDATE rem1 SET f2 = 'testo';
-- Test returning a system attribute INSERTINTO rem1(f2) VALUES ('test') RETURNING ctid;
-- cleanup DROPTRIGGER trig_row_before ON rem1; DROPTRIGGER trig_row_after ON rem1; DROPTRIGGER trig_local_before ON loc1;
-- Test direct foreign table modification functionality EXPLAIN (verbose, costs off) DELETEFROM rem1; -- can be pushed down EXPLAIN (verbose, costs off) DELETEFROM rem1 WHEREfalse; -- currently can't be pushed down
-- Test with statement-level triggers CREATETRIGGER trig_stmt_before BEFOREDELETEORINSERTORUPDATEON rem1 FOREACH STATEMENT EXECUTE PROCEDURE trigger_func(); EXPLAIN (verbose, costs off) UPDATE rem1 set f2 = ''; -- can be pushed down EXPLAIN (verbose, costs off) DELETEFROM rem1; -- can be pushed down DROPTRIGGER trig_stmt_before ON rem1;
CREATETRIGGER trig_stmt_after
AFTER DELETEORINSERTORUPDATEON rem1 FOREACH STATEMENT EXECUTE PROCEDURE trigger_func(); EXPLAIN (verbose, costs off) UPDATE rem1 set f2 = ''; -- can be pushed down EXPLAIN (verbose, costs off) DELETEFROM rem1; -- can be pushed down DROPTRIGGER trig_stmt_after ON rem1;
-- Test with row-level ON INSERT triggers CREATETRIGGER trig_row_before_insert BEFOREINSERTON rem1 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); EXPLAIN (verbose, costs off) UPDATE rem1 set f2 = ''; -- can be pushed down EXPLAIN (verbose, costs off) DELETEFROM rem1; -- can be pushed down DROPTRIGGER trig_row_before_insert ON rem1;
CREATETRIGGER trig_row_after_insert
AFTER INSERTON rem1 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); EXPLAIN (verbose, costs off) UPDATE rem1 set f2 = ''; -- can be pushed down EXPLAIN (verbose, costs off) DELETEFROM rem1; -- can be pushed down DROPTRIGGER trig_row_after_insert ON rem1;
-- Test with row-level ON UPDATE triggers CREATETRIGGER trig_row_before_update BEFOREUPDATEON rem1 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); EXPLAIN (verbose, costs off) UPDATE rem1 set f2 = ''; -- can't be pushed down EXPLAIN (verbose, costs off) DELETEFROM rem1; -- can be pushed down DROPTRIGGER trig_row_before_update ON rem1;
CREATETRIGGER trig_row_after_update
AFTER UPDATEON rem1 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); EXPLAIN (verbose, costs off) UPDATE rem1 set f2 = ''; -- can't be pushed down EXPLAIN (verbose, costs off) DELETEFROM rem1; -- can be pushed down DROPTRIGGER trig_row_after_update ON rem1;
-- Test with row-level ON DELETE triggers CREATETRIGGER trig_row_before_delete BEFOREDELETEON rem1 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); EXPLAIN (verbose, costs off) UPDATE rem1 set f2 = ''; -- can be pushed down EXPLAIN (verbose, costs off) DELETEFROM rem1; -- can't be pushed down DROPTRIGGER trig_row_before_delete ON rem1;
CREATETRIGGER trig_row_after_delete
AFTER DELETEON rem1 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); EXPLAIN (verbose, costs off) UPDATE rem1 set f2 = ''; -- can be pushed down EXPLAIN (verbose, costs off) DELETEFROM rem1; -- can't be pushed down DROPTRIGGER trig_row_after_delete ON rem1;
-- We are allowed to create transition-table triggers on both kinds of -- inheritance even if they contain foreign tables as children, but currently -- collecting transition tuples from such foreign tables is not supported.
CREATETABLE local_tbl (a text, b int); CREATEFOREIGNTABLE foreign_tbl (a text, b int)
SERVER loopback OPTIONS (table_name 'local_tbl');
INSERTINTO foreign_tbl VALUES ('AAA', 42);
-- Test case for partition hierarchy CREATETABLE parent_tbl (a text, b int) PARTITION BY LIST (a); ALTERTABLE parent_tbl ATTACH PARTITION foreign_tbl FORVALUESIN ('AAA');
CREATETRIGGER parent_tbl_insert_trig
AFTER INSERTON parent_tbl REFERENCING NEW TABLEAS new_table FOREACH STATEMENT EXECUTE PROCEDURE trigger_func(); CREATETRIGGER parent_tbl_update_trig
AFTER UPDATEON parent_tbl REFERENCING OLD TABLEAS old_table NEW TABLEAS new_table FOREACH STATEMENT EXECUTE PROCEDURE trigger_func(); CREATETRIGGER parent_tbl_delete_trig
AFTER DELETEON parent_tbl REFERENCING OLD TABLEAS old_table FOREACH STATEMENT EXECUTE PROCEDURE trigger_func();
INSERTINTO parent_tbl VALUES ('AAA', 42);
COPY parent_tbl (a, b) FROM stdin;
AAA 42
\.
ALTER SERVER loopback OPTIONS (ADD batch_size '10');
INSERTINTO parent_tbl VALUES ('AAA', 42);
COPY parent_tbl (a, b) FROM stdin;
AAA 42
\.
ALTER SERVER loopback OPTIONS (DROP batch_size);
EXPLAIN (VERBOSE, COSTS OFF) UPDATE parent_tbl SET b = b + 1; UPDATE parent_tbl SET b = b + 1;
-- =================================================================== -- test inheritance features -- ===================================================================
CREATETABLE a (aa TEXT); CREATETABLE loct (aa TEXT, bb TEXT); ALTERTABLE a SET (autovacuum_enabled = 'false'); ALTERTABLE loct SET (autovacuum_enabled = 'false'); CREATEFOREIGNTABLE b (bb TEXT) INHERITS (a)
SERVER loopback OPTIONS (table_name 'loct');
altertable foo set (autovacuum_enabled = 'false'); altertable bar set (autovacuum_enabled = 'false');
insertinto foo values(1,1); insertinto foo values(3,3); insertinto foo2 values(2,2,2); insertinto foo2 values(4,4,4); insertinto bar values(1,11); insertinto bar values(2,22); insertinto bar values(6,66); insertinto bar2 values(3,33,33); insertinto bar2 values(4,44,44); insertinto bar2 values(7,77,77);
explain (verbose, costs off) select * from bar where f1 in (select f1 from foo) forupdate; select * from bar where f1 in (select f1 from foo) forupdate;
explain (verbose, costs off) select * from bar where f1 in (select f1 from foo) for share; select * from bar where f1 in (select f1 from foo) for share;
-- Now check SELECT FOR UPDATE/SHARE with an inherited source table, -- where the parent is itself a foreign table createtable loct4 (f1 int, f2 int, f3 int); createforeigntable foo2child (f3 int) inherits (foo2)
server loopback options (table_name 'loct4');
explain (verbose, costs off) select * from bar where f1 in (select f1 from foo2) for share; select * from bar where f1 in (select f1 from foo2) for share;
dropforeigntable foo2child;
-- And with a local child relation of the foreign table parent createtable foo2child (f3 int) inherits (foo2);
explain (verbose, costs off) select * from bar where f1 in (select f1 from foo2) for share; select * from bar where f1 in (select f1 from foo2) for share;
droptable foo2child;
-- Check UPDATE with inherited target and an inherited source table explain (verbose, costs off) update bar set f2 = f2 + 100where f1 in (select f1 from foo); update bar set f2 = f2 + 100where f1 in (select f1 from foo);
select tableoid::regclass, * from bar orderby1,2;
-- Check UPDATE with inherited target and an appendrel subquery explain (verbose, costs off) update bar set f2 = f2 + 100 from
( select f1 from foo unionallselect f1+3from foo ) ss where bar.f1 = ss.f1; update bar set f2 = f2 + 100 from
( select f1 from foo unionallselect f1+3from foo ) ss where bar.f1 = ss.f1;
select tableoid::regclass, * from bar orderby1,2;
-- Test forcing the remote server to produce sorted data for a merge join, -- but the foreign table is an inheritance child.
truncate table loct1;
truncate table only foo;
\set num_rows_foo 2000 insertinto loct1 select generate_series(0, :num_rows_foo, 2), generate_series(0, :num_rows_foo, 2), generate_series(0, :num_rows_foo, 2); insertinto foo select generate_series(1, :num_rows_foo, 2), generate_series(1, :num_rows_foo, 2); SET enable_hashjoin tofalse; SET enable_nestloop tofalse; alterforeigntable foo2 options (use_remote_estimate 'true'); createindex i_loct1_f1 on loct1(f1); createindex i_foo_f1 on foo(f1); analyze foo; analyze loct1; -- inner join; expressions in the clauses appear in the equivalence class list explain (verbose, costs off) select foo.f1, loct1.f1 from foo join loct1 on (foo.f1 = loct1.f1) orderby foo.f2 offset 10limit10; select foo.f1, loct1.f1 from foo join loct1 on (foo.f1 = loct1.f1) orderby foo.f2 offset 10limit10; -- outer join; expressions in the clauses do not appear in equivalence class -- list but no output change as compared to the previous query explain (verbose, costs off) select foo.f1, loct1.f1 from foo leftjoin loct1 on (foo.f1 = loct1.f1) orderby foo.f2 offset 10limit10; select foo.f1, loct1.f1 from foo leftjoin loct1 on (foo.f1 = loct1.f1) orderby foo.f2 offset 10limit10;
RESET enable_hashjoin;
RESET enable_nestloop;
-- Test that WHERE CURRENT OF is not supported
begin; declare c cursorforselect * from bar where f1 = 7; fetchfrom c; update bar set f2 = nullwhere current of c;
rollback;
explain (verbose, costs off) deletefrom foo where f1 < 5 returning *; deletefrom foo where f1 < 5 returning *; explain (verbose, costs off) update bar set f2 = f2 + 100 returning *; update bar set f2 = f2 + 100 returning *;
-- Test that UPDATE/DELETE with inherited target works with row-level triggers CREATETRIGGER trig_row_before BEFOREUPDATEORDELETEON bar2 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo');
CREATETRIGGER trig_row_after
AFTER UPDATEORDELETEON bar2 FOREACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo');
explain (verbose, costs off) update bar set f2 = f2 + 100; update bar set f2 = f2 + 100;
explain (verbose, costs off) deletefrom bar where f2 < 400; deletefrom bar where f2 < 400;
-- Test pushing down UPDATE/DELETE joins to the remote server createtable parent (a int, b text); createtable loct1 (a int, b text); createtable loct2 (a int, b text); createforeigntable remt1 (a int, b text)
server loopback options (table_name 'loct1'); createforeigntable remt2 (a int, b text)
server loopback options (table_name 'loct2'); alterforeigntable remt1 inherit parent;
explain (verbose, costs off) update parent set b = parent.b || remt2.b from remt2 where parent.a = remt2.a returning *; update parent set b = parent.b || remt2.b from remt2 where parent.a = remt2.a returning *; explain (verbose, costs off) deletefrom parent using remt2 where parent.a = remt2.a returning parent; deletefrom parent using remt2 where parent.a = remt2.a returning parent;
-- =================================================================== -- test tuple routing for foreign-table partitions -- ===================================================================
-- Test insert tuple routing createtable itrtest (a int, b text) partition by list (a); createtable loct1 (a intcheck (a in (1)), b text); createforeigntable remp1 (a intcheck (a in (1)), b text) server loopback options (table_name 'loct1'); createtable loct2 (a intcheck (a in (2)), b text); createforeigntable remp2 (b text, a intcheck (a in (2))) server loopback options (table_name 'loct2'); altertable itrtest attach partition remp1 forvaluesin (1); altertable itrtest attach partition remp2 forvaluesin (2);
select tableoid::regclass, * FROM itrtest; select tableoid::regclass, * FROM remp1; select tableoid::regclass, * FROM remp2;
deletefrom itrtest;
-- MERGE ought to fail cleanly
merge into itrtest using (select1, 'foo') as source on (true) when matched then do nothing;
createuniqueindex loct1_idx on loct1 (a);
-- DO NOTHING without an inference specification is supported insertinto itrtest values (1, 'foo') on conflict do nothing returning *; insertinto itrtest values (1, 'foo') on conflict do nothing returning *;
-- But other cases are not supported insertinto itrtest values (1, 'bar') on conflict (a) do nothing; insertinto itrtest values (1, 'bar') on conflict (a) do updateset b = excluded.b;
select tableoid::regclass, * FROM itrtest;
deletefrom itrtest;
dropindex loct1_idx;
-- Test that remote triggers work with insert tuple routing create function br_insert_trigfunc() returns triggeras $$
begin
new.b := new.b || ' triggered !'; return new;
end
$$ language plpgsql; createtrigger loct1_br_insert_trigger beforeinserton loct1 foreach row execute procedure br_insert_trigfunc(); createtrigger loct2_br_insert_trigger beforeinserton loct2 foreach row execute procedure br_insert_trigfunc();
-- The new values are concatenated with ' triggered !' insertinto itrtest values (1, 'foo') returning *; insertinto itrtest values (2, 'qux') returning *; insertinto itrtest values (1, 'test1'), (2, 'test2') returning *; with result as (insertinto itrtest values (1, 'test1'), (2, 'test2') returning *) select * from result;
droptrigger loct1_br_insert_trigger on loct1; droptrigger loct2_br_insert_trigger on loct2;
-- Test update tuple routing createtable utrtest (a int, b text) partition by list (a); createtable loct (a intcheck (a in (1)), b text); createforeigntable remp (a intcheck (a in (1)), b text) server loopback options (table_name 'loct'); createtable locp (a intcheck (a in (2)), b text); altertable utrtest attach partition remp forvaluesin (1); altertable utrtest attach partition locp forvaluesin (2);
select tableoid::regclass, * FROM utrtest; select tableoid::regclass, * FROM remp; select tableoid::regclass, * FROM locp;
-- It's not allowed to move a row from a partition that is foreign to another update utrtest set a = 2where b = 'foo' returning *;
-- But the reverse is allowed update utrtest set a = 1where b = 'qux' returning *;
select tableoid::regclass, * FROM utrtest; select tableoid::regclass, * FROM remp; select tableoid::regclass, * FROM locp;
-- The executor should not let unexercised FDWs shut down update utrtest set a = 1where b = 'foo';
-- Test that remote triggers work with update tuple routing createtrigger loct_br_insert_trigger beforeinserton loct foreach row execute procedure br_insert_trigfunc();
-- Check case where the foreign partition is a subplan target rel explain (verbose, costs off) update utrtest set a = 1where a = 1or a = 2 returning *; -- The new values are concatenated with ' triggered !' update utrtest set a = 1where a = 1or a = 2 returning *;
-- Check case where the foreign partition isn't a subplan target rel explain (verbose, costs off) update utrtest set a = 1where a = 2 returning *; -- The new values are concatenated with ' triggered !' update utrtest set a = 1where a = 2 returning *;
droptrigger loct_br_insert_trigger on loct;
-- We can move rows to a foreign partition that has been updated already, -- but can't move rows to a foreign partition that hasn't been updated yet
-- Test the former case: -- with a direct modification plan explain (verbose, costs off) update utrtest set a = 1 returning *; update utrtest set a = 1 returning *;
-- with a non-direct modification plan explain (verbose, costs off) update utrtest set a = 1from (values (1), (2)) s(x) where a = s.x returning *; update utrtest set a = 1from (values (1), (2)) s(x) where a = s.x returning *;
-- Change the definition of utrtest so that the foreign partition get updated -- after the local partition deletefrom utrtest; altertable utrtest detach partition remp; dropforeigntable remp; altertable loct dropconstraint loct_a_check; altertable loct addcheck (a in (3)); createforeigntable remp (a intcheck (a in (3)), b text) server loopback options (table_name 'loct'); altertable utrtest attach partition remp forvaluesin (3); insertinto utrtest values (2, 'qux'); insertinto utrtest values (3, 'xyzzy');
-- Test the latter case: -- with a direct modification plan explain (verbose, costs off) update utrtest set a = 3 returning *; update utrtest set a = 3 returning *; -- ERROR
-- with a non-direct modification plan explain (verbose, costs off) update utrtest set a = 3from (values (2), (3)) s(x) where a = s.x returning *; update utrtest set a = 3from (values (2), (3)) s(x) where a = s.x returning *; -- ERROR
droptable utrtest; droptable loct;
-- Test copy tuple routing createtable ctrtest (a int, b text) partition by list (a); createtable loct1 (a intcheck (a in (1)), b text); createforeigntable remp1 (a intcheck (a in (1)), b text) server loopback options (table_name 'loct1'); createtable loct2 (a intcheck (a in (2)), b text); createforeigntable remp2 (b text, a intcheck (a in (2))) server loopback options (table_name 'loct2'); altertable ctrtest attach partition remp1 forvaluesin (1); altertable ctrtest attach partition remp2 forvaluesin (2);
copy ctrtest from stdin; 1 foo 2 qux
\.
select tableoid::regclass, * FROM ctrtest; select tableoid::regclass, * FROM remp1; select tableoid::regclass, * FROM remp2;
-- Copying into foreign partitions directly should work as well
copy remp1 from stdin; 1 bar
\.
select tableoid::regclass, * FROM remp1;
deletefrom ctrtest;
-- Test copy tuple routing with the batch_size option enabled alter server loopback options (add batch_size '2');
copy ctrtest from stdin; 1 foo 1 bar 2 baz 2 qux 1 test1 2 test2
\.
select tableoid::regclass, * FROM ctrtest; select tableoid::regclass, * FROM remp1; select tableoid::regclass, * FROM remp2;
-- =================================================================== -- test COPY FROM -- ===================================================================
-- check constraint is enforced on the remote side, not locally
copy rem2 from stdin; 1 foo 2 bar
\.
copy rem2 from stdin; -- ERROR
-1 xyzzy
\. select * from rem2;
-- Nothing happens
copy rem2 from stdin; 1 foo 2 bar
\. select * from rem2;
droptrigger trig_null on loc2;
deletefrom rem2;
-- Test a combination of local and remote triggers createtrigger rem2_trig_row_before beforeinserton rem2 foreach row execute procedure trigger_data(23,'skidoo'); createtrigger rem2_trig_row_after after inserton rem2 foreach row execute procedure trigger_data(23,'skidoo'); createtrigger loc2_trig_row_before_insert beforeinserton loc2 foreach row execute procedure trig_row_before_insupdate();
copy rem2 from stdin; 1 foo 2 bar
\. select * from rem2;
droptrigger rem2_trig_row_before on rem2; droptrigger rem2_trig_row_after on rem2; droptrigger loc2_trig_row_before_insert on loc2;
deletefrom rem2;
-- test COPY FROM with foreign table created in the same transaction createtable loc3 (f1 int, f2 text);
begin; createforeigntable rem3 (f1 int, f2 text)
server loopback options(table_name 'loc3');
copy rem3 from stdin; 1 foo 2 bar
\. commit; select * from rem3; dropforeigntable rem3; droptable loc3;
-- Test COPY FROM with the batch_size option enabled alter server loopback options (add batch_size '2');
-- Test basic functionality
copy rem2 from stdin; 1 foo 2 bar 3 baz
\. select * from rem2;
-- check constraint is enforced on the remote side, not locally
copy rem2 from stdin; 1 foo 2 bar 3 baz
\.
copy rem2 from stdin; -- ERROR
-1 xyzzy
\. select * from rem2;
-- Nothing happens
copy rem2 from stdin; 1 foo 2 bar 3 baz
\. select * from rem2;
droptrigger trig_null on loc2;
deletefrom rem2;
-- Check with zero-column foreign table; batch insert will be disabled altertable loc2 dropcolumn f1; altertable loc2 dropcolumn f2; altertable rem2 dropcolumn f1; altertable rem2 dropcolumn f2;
copy rem2 from stdin;
\. select * from rem2;
deletefrom rem2;
alter server loopback options (drop batch_size);
-- =================================================================== -- test for TRUNCATE -- =================================================================== CREATETABLE tru_rtable0 (id intprimarykey); CREATEFOREIGNTABLE tru_ftable (id int)
SERVER loopback OPTIONS (table_name 'tru_rtable0'); INSERTINTO tru_rtable0 (SELECT x FROM generate_series(1,10) x);
CREATETABLE tru_ptable (id int) PARTITION BY HASH(id); CREATETABLE tru_ptable__p0 PARTITION OF tru_ptable FORVALUESWITH (MODULUS 2, REMAINDER 0); CREATETABLE tru_rtable1 (id intprimarykey); CREATEFOREIGNTABLE tru_ftable__p1 PARTITION OF tru_ptable FORVALUESWITH (MODULUS 2, REMAINDER 1)
SERVER loopback OPTIONS (table_name 'tru_rtable1'); INSERTINTO tru_ptable (SELECT x FROM generate_series(11,20) x);
CREATETABLE tru_pk_table(id intprimarykey); CREATETABLE tru_fk_table(fkey intreferences tru_pk_table(id)); INSERTINTO tru_pk_table (SELECT x FROM generate_series(1,10) x); INSERTINTO tru_fk_table (SELECT x % 10 + 1FROM generate_series(5,25) x); CREATEFOREIGNTABLE tru_pk_ftable (id int)
SERVER loopback OPTIONS (table_name 'tru_pk_table');
CREATETABLE tru_rtable_parent (id int); CREATETABLE tru_rtable_child (id int); CREATEFOREIGNTABLE tru_ftable_parent (id int)
SERVER loopback OPTIONS (table_name 'tru_rtable_parent'); CREATEFOREIGNTABLE tru_ftable_child () INHERITS (tru_ftable_parent)
SERVER loopback OPTIONS (table_name 'tru_rtable_child'); INSERTINTO tru_rtable_parent (SELECT x FROM generate_series(1,8) x); INSERTINTO tru_rtable_child (SELECT x FROM generate_series(10, 18) x);
-- normal truncate SELECT sum(id) FROM tru_ftable; -- 55
TRUNCATE tru_ftable; SELECT count(*) FROM tru_rtable0; -- 0 SELECT count(*) FROM tru_ftable; -- 0
-- partitioned table with both local and foreign tables as partitions SELECT sum(id) FROM tru_ptable; -- 155
TRUNCATE tru_ptable; SELECT count(*) FROM tru_ptable; -- 0 SELECT count(*) FROM tru_ptable__p0; -- 0 SELECT count(*) FROM tru_ftable__p1; -- 0 SELECT count(*) FROM tru_rtable1; -- 0
-- 'CASCADE' option SELECT sum(id) FROM tru_pk_ftable; -- 55
TRUNCATE tru_pk_ftable; -- failed by FK reference
TRUNCATE tru_pk_ftable CASCADE; SELECT count(*) FROM tru_pk_ftable; -- 0 SELECT count(*) FROM tru_fk_table; -- also truncated,0
-- truncate two tables at a command INSERTINTO tru_ftable (SELECT x FROM generate_series(1,8) x); INSERTINTO tru_pk_ftable (SELECT x FROM generate_series(3,10) x); SELECT count(*) from tru_ftable; -- 8 SELECT count(*) from tru_pk_ftable; -- 8
TRUNCATE tru_ftable, tru_pk_ftable CASCADE; SELECT count(*) from tru_ftable; -- 0 SELECT count(*) from tru_pk_ftable; -- 0
-- truncate with ONLY clause -- Since ONLY is specified, the table tru_ftable_child that inherits -- tru_ftable_parent locally is not truncated.
TRUNCATE ONLY tru_ftable_parent; SELECT sum(id) FROM tru_ftable_parent; -- 126
TRUNCATE tru_ftable_parent; SELECT count(*) FROM tru_ftable_parent; -- 0
-- in case when remote table has inherited children CREATETABLE tru_rtable0_child () INHERITS (tru_rtable0); INSERTINTO tru_rtable0 (SELECT x FROM generate_series(5,9) x); INSERTINTO tru_rtable0_child (SELECT x FROM generate_series(10,14) x); SELECT sum(id) FROM tru_ftable; -- 95
-- Both parent and child tables in the foreign server are truncated -- even though ONLY is specified because ONLY has no effect -- when truncating a foreign table.
TRUNCATE ONLY tru_ftable; SELECT count(*) FROM tru_ftable; -- 0
INSERTINTO tru_rtable0 (SELECT x FROM generate_series(21,25) x); INSERTINTO tru_rtable0_child (SELECT x FROM generate_series(26,30) x); SELECT sum(id) FROM tru_ftable; -- 255
TRUNCATE tru_ftable; -- truncate both of parent and child SELECT count(*) FROM tru_ftable; -- 0
-- =================================================================== -- test IMPORT FOREIGN SCHEMA -- ===================================================================
CREATESCHEMA import_source; CREATETABLE import_source.t1 (c1 int, c2 varcharNOTNULL); CREATETABLE import_source.t2 (c1 intdefault42, c2 varcharNULL, c3 text collate"POSIX"); CREATE TYPE typ1 AS (m1 int, m2 varchar); CREATETABLE import_source.t3 (c1 timestamptz default now(), c2 typ1); CREATETABLE import_source."x 4" (c1 float8, "C 2" text, c3 varchar(42)); CREATETABLE import_source."x 5" (c1 float8); ALTERTABLE import_source."x 5"DROPCOLUMN c1; CREATETABLE import_source."x 6" (c1 int, c2 int generated always as (c1 * 2) stored); CREATETABLE import_source.t4 (c1 int) PARTITION BY RANGE (c1); CREATETABLE import_source.t4_part PARTITION OF import_source.t4 FORVALUESFROM (1) TO (100); CREATETABLE import_source.t4_part2 PARTITION OF import_source.t4 FORVALUESFROM (100) TO (200);
CREATESCHEMA import_dest1;
IMPORT FOREIGNSCHEMA import_source FROM SERVER loopback INTO import_dest1;
\det+ import_dest1.*
\d import_dest1.*
-- Options CREATESCHEMA import_dest2;
IMPORT FOREIGNSCHEMA import_source FROM SERVER loopback INTO import_dest2
OPTIONS (import_default 'true');
\det+ import_dest2.*
\d import_dest2.* CREATESCHEMA import_dest3;
IMPORT FOREIGNSCHEMA import_source FROM SERVER loopback INTO import_dest3
OPTIONS (import_collate 'false', import_generated 'false', import_not_null 'false');
\det+ import_dest3.*
\d import_dest3.*
-- Check LIMIT TO and EXCEPT CREATESCHEMA import_dest4;
IMPORT FOREIGNSCHEMA import_source LIMITTO (t1, nonesuch, t4_part) FROM SERVER loopback INTO import_dest4;
\det+ import_dest4.*
IMPORT FOREIGNSCHEMA import_source EXCEPT (t1, "x 4", nonesuch, t4_part) FROM SERVER loopback INTO import_dest4;
\det+ import_dest4.*
-- Assorted error cases
IMPORT FOREIGNSCHEMA import_source FROM SERVER loopback INTO import_dest4;
IMPORT FOREIGNSCHEMA nonesuch FROM SERVER loopback INTO import_dest4;
IMPORT FOREIGNSCHEMA nonesuch FROM SERVER loopback INTO notthere;
IMPORT FOREIGNSCHEMA nonesuch FROM SERVER nowhere INTO notthere;
-- Check case of a type present only on the remote server. -- We can fake this by dropping the type locally in our transaction. CREATE TYPE "Colors"AS ENUM ('red', 'green', 'blue'); CREATETABLE import_source.t5 (c1 int, c2 text collate"C", "Col""Colors");
CREATESCHEMA import_dest5;
BEGIN; DROP TYPE "Colors"CASCADE;
IMPORT FOREIGNSCHEMA import_source LIMITTO (t5) FROM SERVER loopback INTO import_dest5; -- ERROR
ROLLBACK;
BEGIN;
CREATE SERVER fetch101 FOREIGN DATA WRAPPER postgres_fdw OPTIONS( fetch_size '101' );
SELECT count(*) FROM pg_foreign_server WHERE srvname = 'fetch101' AND srvoptions @> array['fetch_size=101'];
ALTER SERVER fetch101 OPTIONS( SET fetch_size '202' );
SELECT count(*) FROM pg_foreign_server WHERE srvname = 'fetch101' AND srvoptions @> array['fetch_size=101'];
SELECT count(*) FROM pg_foreign_server WHERE srvname = 'fetch101' AND srvoptions @> array['fetch_size=202'];
CREATEFOREIGNTABLE table30000 ( x int ) SERVER fetch101 OPTIONS ( fetch_size '30000' );
SELECT COUNT(*) FROM pg_foreign_table WHERE ftrelid = 'table30000'::regclass AND ftoptions @> array['fetch_size=30000'];
ALTERFOREIGNTABLE table30000 OPTIONS ( SET fetch_size '60000');
SELECT COUNT(*) FROM pg_foreign_table WHERE ftrelid = 'table30000'::regclass AND ftoptions @> array['fetch_size=30000'];
SELECT COUNT(*) FROM pg_foreign_table WHERE ftrelid = 'table30000'::regclass AND ftoptions @> array['fetch_size=60000'];
ROLLBACK;
-- =================================================================== -- test partitionwise joins -- =================================================================== SET enable_partitionwise_join=on;
CREATETABLE fprt1 (a int, b int, c varchar) PARTITION BY RANGE(a); CREATETABLE fprt1_p1 (LIKE fprt1); CREATETABLE fprt1_p2 (LIKE fprt1); ALTERTABLE fprt1_p1 SET (autovacuum_enabled = 'false'); ALTERTABLE fprt1_p2 SET (autovacuum_enabled = 'false'); INSERTINTO fprt1_p1 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(0, 249, 2) i; INSERTINTO fprt1_p2 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(250, 499, 2) i; CREATEFOREIGNTABLE ftprt1_p1 PARTITION OF fprt1 FORVALUESFROM (0) TO (250)
SERVER loopback OPTIONS (table_name 'fprt1_p1', use_remote_estimate 'true'); CREATEFOREIGNTABLE ftprt1_p2 PARTITION OF fprt1 FORVALUESFROM (250) TO (500)
SERVER loopback OPTIONS (TABLE_NAME 'fprt1_p2'); ANALYZE fprt1; ANALYZE fprt1_p1; ANALYZE fprt1_p2;
CREATETABLE fprt2 (a int, b int, c varchar) PARTITION BY RANGE(b); CREATETABLE fprt2_p1 (LIKE fprt2); CREATETABLE fprt2_p2 (LIKE fprt2); ALTERTABLE fprt2_p1 SET (autovacuum_enabled = 'false'); ALTERTABLE fprt2_p2 SET (autovacuum_enabled = 'false'); INSERTINTO fprt2_p1 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(0, 249, 3) i; INSERTINTO fprt2_p2 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(250, 499, 3) i; CREATEFOREIGNTABLE ftprt2_p1 (b int, c varchar, a int)
SERVER loopback OPTIONS (table_name 'fprt2_p1', use_remote_estimate 'true'); ALTERTABLE fprt2 ATTACH PARTITION ftprt2_p1 FORVALUESFROM (0) TO (250); CREATEFOREIGNTABLE ftprt2_p2 PARTITION OF fprt2 FORVALUESFROM (250) TO (500)
SERVER loopback OPTIONS (table_name 'fprt2_p2', use_remote_estimate 'true'); ANALYZE fprt2; ANALYZE fprt2_p1; ANALYZE fprt2_p2;
-- inner join three tables EXPLAIN (COSTS OFF) SELECT t1.a,t2.b,t3.c FROM fprt1 t1 INNERJOIN fprt2 t2 ON (t1.a = t2.b) INNERJOIN fprt1 t3 ON (t2.b = t3.a) WHERE t1.a % 25 =0ORDERBY1,2,3; SELECT t1.a,t2.b,t3.c FROM fprt1 t1 INNERJOIN fprt2 t2 ON (t1.a = t2.b) INNERJOIN fprt1 t3 ON (t2.b = t3.a) WHERE t1.a % 25 =0ORDERBY1,2,3;
-- left outer join + nullable clause EXPLAIN (VERBOSE, COSTS OFF) SELECT t1.a,t2.b,t2.c FROM fprt1 t1 LEFTJOIN (SELECT * FROM fprt2 WHERE a < 10) t2 ON (t1.a = t2.b and t1.b = t2.a) WHERE t1.a < 10ORDERBY1,2,3; SELECT t1.a,t2.b,t2.c FROM fprt1 t1 LEFTJOIN (SELECT * FROM fprt2 WHERE a < 10) t2 ON (t1.a = t2.b and t1.b = t2.a) WHERE t1.a < 10ORDERBY1,2,3;
-- with whole-row reference; partitionwise join does not apply EXPLAIN (COSTS OFF) SELECT t1.wr, t2.wr FROM (SELECT t1 wr, a FROM fprt1 t1 WHERE t1.a % 25 = 0) t1 FULL JOIN (SELECT t2 wr, b FROM fprt2 t2 WHERE t2.b % 25 = 0) t2 ON (t1.a = t2.b) ORDERBY1,2; SELECT t1.wr, t2.wr FROM (SELECT t1 wr, a FROM fprt1 t1 WHERE t1.a % 25 = 0) t1 FULL JOIN (SELECT t2 wr, b FROM fprt2 t2 WHERE t2.b % 25 = 0) t2 ON (t1.a = t2.b) ORDERBY1,2;
-- join with lateral reference EXPLAIN (COSTS OFF) SELECT t1.a,t1.b FROM fprt1 t1, LATERAL (SELECT t2.a, t2.b FROM fprt2 t2 WHERE t1.a = t2.b AND t1.b = t2.a) q WHERE t1.a%25 = 0ORDERBY1,2; SELECT t1.a,t1.b FROM fprt1 t1, LATERAL (SELECT t2.a, t2.b FROM fprt2 t2 WHERE t1.a = t2.b AND t1.b = t2.a) q WHERE t1.a%25 = 0ORDERBY1,2;
-- with PHVs, partitionwise join selected but no join pushdown EXPLAIN (COSTS OFF) SELECT t1.a, t1.phv, t2.b, t2.phv FROM (SELECT't1_phv' phv, * FROM fprt1 WHERE a % 25 = 0) t1 FULL JOIN (SELECT't2_phv' phv, * FROM fprt2 WHERE b % 25 = 0) t2 ON (t1.a = t2.b) ORDERBY t1.a, t2.b; SELECT t1.a, t1.phv, t2.b, t2.phv FROM (SELECT't1_phv' phv, * FROM fprt1 WHERE a % 25 = 0) t1 FULL JOIN (SELECT't2_phv' phv, * FROM fprt2 WHERE b % 25 = 0) t2 ON (t1.a = t2.b) ORDERBY t1.a, t2.b;
-- test FOR UPDATE; partitionwise join does not apply EXPLAIN (COSTS OFF) SELECT t1.a, t2.b FROM fprt1 t1 INNERJOIN fprt2 t2 ON (t1.a = t2.b) WHERE t1.a % 25 = 0ORDERBY1,2FORUPDATE OF t1; SELECT t1.a, t2.b FROM fprt1 t1 INNERJOIN fprt2 t2 ON (t1.a = t2.b) WHERE t1.a % 25 = 0ORDERBY1,2FORUPDATE OF t1;
RESET enable_partitionwise_join;
-- =================================================================== -- test partitionwise aggregates -- ===================================================================
CREATETABLE pagg_tab (a int, b int, c text) PARTITION BY RANGE(a);
INSERTINTO pagg_tab_p1 SELECT i % 30, i % 50, to_char(i/30, 'FM0000') FROM generate_series(1, 3000) i WHERE (i % 30) < 10; INSERTINTO pagg_tab_p2 SELECT i % 30, i % 50, to_char(i/30, 'FM0000') FROM generate_series(1, 3000) i WHERE (i % 30) < 20and (i % 30) >= 10; INSERTINTO pagg_tab_p3 SELECT i % 30, i % 50, to_char(i/30, 'FM0000') FROM generate_series(1, 3000) i WHERE (i % 30) < 30and (i % 30) >= 20;
-- Create foreign partitions CREATEFOREIGNTABLE fpagg_tab_p1 PARTITION OF pagg_tab FORVALUESFROM (0) TO (10) SERVER loopback OPTIONS (table_name 'pagg_tab_p1'); CREATEFOREIGNTABLE fpagg_tab_p2 PARTITION OF pagg_tab FORVALUESFROM (10) TO (20) SERVER loopback OPTIONS (table_name 'pagg_tab_p2'); CREATEFOREIGNTABLE fpagg_tab_p3 PARTITION OF pagg_tab FORVALUESFROM (20) TO (30) SERVER loopback OPTIONS (table_name 'pagg_tab_p3');
-- When GROUP BY clause matches with PARTITION KEY. -- Plan with partitionwise aggregates is disabled SET enable_partitionwise_aggregate TOfalse; EXPLAIN (COSTS OFF) SELECT a, sum(b), min(b), count(*) FROM pagg_tab GROUPBY a HAVING avg(b) < 22ORDERBY1;
-- Plan with partitionwise aggregates is enabled SET enable_partitionwise_aggregate TOtrue; EXPLAIN (COSTS OFF) SELECT a, sum(b), min(b), count(*) FROM pagg_tab GROUPBY a HAVING avg(b) < 22ORDERBY1; SELECT a, sum(b), min(b), count(*) FROM pagg_tab GROUPBY a HAVING avg(b) < 22ORDERBY1;
-- Check with whole-row reference -- Should have all the columns in the target list for the given relation EXPLAIN (VERBOSE, COSTS OFF) SELECT a, count(t1) FROM pagg_tab t1 GROUPBY a HAVING avg(b) < 22ORDERBY1; SELECT a, count(t1) FROM pagg_tab t1 GROUPBY a HAVING avg(b) < 22ORDERBY1;
-- When GROUP BY clause does not match with PARTITION KEY. EXPLAIN (COSTS OFF) SELECT b, avg(a), max(a), count(*) FROM pagg_tab GROUPBY b HAVING sum(a) < 700ORDERBY1;
-- =================================================================== -- access rights and superuser -- ===================================================================
-- Non-superuser cannot create a FDW without a password in the connstr CREATE ROLE regress_nosuper NOSUPERUSER;
GRANTUSAGEONFOREIGN DATA WRAPPER postgres_fdw TO regress_nosuper;
SET ROLE regress_nosuper;
SHOW is_superuser;
-- This will be OK, we can create the FDW
DO $d$
BEGIN
EXECUTE $$CREATE SERVER loopback_nopw FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (dbname '$$||current_database()||$$',
port '$$||current_setting('port')||$$'
)$$;
END;
$d$;
-- But creation of user mappings for non-superusers should fail CREATE USER MAPPING FOR public SERVER loopback_nopw; CREATE USER MAPPING FORCURRENT_USER SERVER loopback_nopw;
-- If we add a password to the connstr it'll fail, because we don't allow passwords -- in connstrs only in user mappings.
ALTER SERVER loopback_nopw OPTIONS (ADD password 'dummypw');
-- If we add a password for our user mapping instead, we should get a different -- error because the password wasn't actually *used* when we run with trust auth. -- -- This won't work with installcheck, but neither will most of the FDW checks.
ALTER USER MAPPING FORCURRENT_USER SERVER loopback_nopw OPTIONS (ADD password 'dummypw');
SELECT1FROM ft1_nopw LIMIT1;
-- Unpriv user cannot make the mapping passwordless ALTER USER MAPPING FORCURRENT_USER SERVER loopback_nopw OPTIONS (ADD password_required 'false');
SELECT1FROM ft1_nopw LIMIT1;
RESET ROLE;
-- But the superuser can ALTER USER MAPPING FOR regress_nosuper SERVER loopback_nopw OPTIONS (ADD password_required 'false');
SET ROLE regress_nosuper;
-- Should finally work now SELECT1FROM ft1_nopw LIMIT1;
-- unpriv user also cannot set sslcert / sslkey on the user mapping -- first set password_required so we see the right error messages ALTER USER MAPPING FORCURRENT_USER SERVER loopback_nopw OPTIONS (SET password_required 'true'); ALTER USER MAPPING FORCURRENT_USER SERVER loopback_nopw OPTIONS (ADD sslcert 'foo.crt'); ALTER USER MAPPING FORCURRENT_USER SERVER loopback_nopw OPTIONS (ADD sslkey 'foo.key');
-- We're done with the role named after a specific user and need to check the -- changes to the public mapping. DROP USER MAPPING FORCURRENT_USER SERVER loopback_nopw;
-- This will fail again as it'll resolve the user mapping for public, which -- lacks password_required=false SELECT1FROM ft1_nopw LIMIT1;
RESET ROLE;
-- The user mapping for public is passwordless and lacks the password_required=false -- mapping option, but will work because the current user is a superuser. SELECT1FROM ft1_nopw LIMIT1;
-- cleanup DROP USER MAPPING FOR public SERVER loopback_nopw; DROP OWNED BY regress_nosuper; DROP ROLE regress_nosuper;
-- Clean-up
RESET enable_partitionwise_aggregate;
-- Two-phase transactions are not supported.
BEGIN; SELECT count(*) FROM ft1; -- error here
PREPARE TRANSACTION 'fdw_tpc';
ROLLBACK;
-- =================================================================== -- reestablish new connection -- ===================================================================
-- Change application_name of remote connection to special one -- so that we can easily terminate the connection later. ALTER SERVER loopback OPTIONS (application_name 'fdw_retry_check');
-- Make sure we have a remote connection. SELECT1FROM ft1 LIMIT1;
-- Terminate the remote connection and wait for the termination to complete. -- (If a cache flush happens, the remote connection might have already been -- dropped; so code this step in a way that doesn't fail if no connection.)
DO $$ BEGIN
PERFORM pg_terminate_backend(pid, 180000) FROM pg_stat_activity WHERE application_name = 'fdw_retry_check';
END $$;
-- This query should detect the broken connection when starting new remote -- transaction, reestablish new connection, and then succeed.
BEGIN; SELECT1FROM ft1 LIMIT1;
-- If we detect the broken connection when starting a new remote -- subtransaction, we should fail instead of establishing a new connection. -- Terminate the remote connection and wait for the termination to complete.
DO $$ BEGIN
PERFORM pg_terminate_backend(pid, 180000) FROM pg_stat_activity WHERE application_name = 'fdw_retry_check';
END $$;
SAVEPOINT s; -- The text of the error might vary across platforms, so only show SQLSTATE.
\set VERBOSITY sqlstate SELECT1FROM ft1 LIMIT1; -- should fail
\set VERBOSITY default COMMIT;
-- ============================================================================= -- test connection invalidation cases and postgres_fdw_get_connections function -- ============================================================================= -- Let's ensure to close all the existing cached connections. SELECT1FROM postgres_fdw_disconnect_all(); -- No cached connections, so no records should be output. SELECT server_name FROM postgres_fdw_get_connections() ORDERBY1; -- This test case is for closing the connection in pgfdw_xact_callback
BEGIN; -- Connection xact depth becomes 1 i.e. the connection is in midst of the xact. SELECT1FROM ft1 LIMIT1; SELECT1FROM ft7 LIMIT1; -- List all the existing cached connections. loopback and loopback3 should be -- output. SELECT server_name FROM postgres_fdw_get_connections() ORDERBY1; -- Connections are not closed at the end of the alter and drop statements. -- That's because the connections are in midst of this xact, -- they are just marked as invalid in pgfdw_inval_callback. ALTER SERVER loopback OPTIONS (ADD use_remote_estimate 'off'); DROP SERVER loopback3 CASCADE; -- List all the existing cached connections. loopback and loopback3 -- should be output as invalid connections. Also the server name and user name -- for loopback3 should be NULL because both server and user mapping were -- dropped. In this test, the PIDs of remote backends can be gathered from -- pg_stat_activity, and remote_backend_pid should match one of those PIDs. SELECT server_name, user_name = CURRENT_USERas"user_name = CURRENT_USER",
valid, used_in_xact, closed,
remote_backend_pid = ANY(SELECT pid FROM pg_stat_activity WHERE backend_type = 'client backend'AND pid <> pg_backend_pid()) as remote_backend_pid FROM postgres_fdw_get_connections() ORDERBY1; -- The invalid connections get closed in pgfdw_xact_callback during commit. COMMIT; -- All cached connections were closed while committing above xact, so no -- records should be output. SELECT server_name FROM postgres_fdw_get_connections() ORDERBY1;
-- ======================================================================= -- test postgres_fdw_disconnect and postgres_fdw_disconnect_all functions -- =======================================================================
BEGIN; -- Ensure to cache loopback connection. SELECT1FROM ft1 LIMIT1; -- Ensure to cache loopback2 connection. SELECT1FROM ft6 LIMIT1; -- List all the existing cached connections. loopback and loopback2 should be -- output. SELECT server_name FROM postgres_fdw_get_connections() ORDERBY1; -- Issue a warning and return false as loopback connection is still in use and -- can not be closed. SELECT postgres_fdw_disconnect('loopback'); -- List all the existing cached connections. loopback and loopback2 should be -- output. SELECT server_name FROM postgres_fdw_get_connections() ORDERBY1; -- Return false as connections are still in use, warnings are issued. -- But disable warnings temporarily because the order of them is not stable. SET client_min_messages = 'ERROR'; SELECT postgres_fdw_disconnect_all();
RESET client_min_messages; COMMIT; -- Ensure that loopback2 connection is closed. SELECT1FROM postgres_fdw_disconnect('loopback2'); SELECT server_name FROM postgres_fdw_get_connections() WHERE server_name = 'loopback2'; -- Return false as loopback2 connection is closed already. SELECT postgres_fdw_disconnect('loopback2'); -- Return an error as there is no foreign server with given name. SELECT postgres_fdw_disconnect('unknownserver'); -- Let's ensure to close all the existing cached connections. SELECT1FROM postgres_fdw_disconnect_all(); -- No cached connections, so no records should be output. SELECT server_name FROM postgres_fdw_get_connections() ORDERBY1;
-- ============================================================================= -- test case for having multiple cached connections for a foreign server -- ============================================================================= CREATE ROLE regress_multi_conn_user1 SUPERUSER; CREATE ROLE regress_multi_conn_user2 SUPERUSER; CREATE USER MAPPING FOR regress_multi_conn_user1 SERVER loopback; CREATE USER MAPPING FOR regress_multi_conn_user2 SERVER loopback;
BEGIN; -- Will cache loopback connection with user mapping for regress_multi_conn_user1 SET ROLE regress_multi_conn_user1; SELECT1FROM ft1 LIMIT1;
RESET ROLE;
-- Will cache loopback connection with user mapping for regress_multi_conn_user2 SET ROLE regress_multi_conn_user2; SELECT1FROM ft1 LIMIT1;
RESET ROLE;
-- Should output two connections for loopback server SELECT server_name FROM postgres_fdw_get_connections() ORDERBY1; COMMIT; -- Let's ensure to close all the existing cached connections. SELECT1FROM postgres_fdw_disconnect_all(); -- No cached connections, so no records should be output. SELECT server_name FROM postgres_fdw_get_connections() ORDERBY1;
-- Clean up DROP USER MAPPING FOR regress_multi_conn_user1 SERVER loopback; DROP USER MAPPING FOR regress_multi_conn_user2 SERVER loopback; DROP ROLE regress_multi_conn_user1; DROP ROLE regress_multi_conn_user2;
-- =================================================================== -- Test foreign server level option keep_connections -- =================================================================== -- By default, the connections associated with foreign server are cached i.e. -- keep_connections option is on. Set it to off. ALTER SERVER loopback OPTIONS (keep_connections 'off'); -- connection to loopback server is closed at the end of xact -- as keep_connections was set to off. SELECT1FROM ft1 LIMIT1; -- No cached connections, so no records should be output. SELECT server_name FROM postgres_fdw_get_connections() ORDERBY1; ALTER SERVER loopback OPTIONS (SET keep_connections 'on');
CREATETABLE batch_table_p2
PARTITION OF batch_table FORVALUESWITH (MODULUS 3, REMAINDER 2);
INSERTINTO batch_table SELECT * FROM generate_series(1, 66) i; SELECT COUNT(*) FROM batch_table;
-- Clean up DROPTABLE batch_table; DROPTABLE batch_table_p0; DROPTABLE batch_table_p1;
-- Check that batched mode also works for some inserts made during -- cross-partition updates CREATETABLE batch_cp_upd_test (a int) PARTITION BY LIST (a); CREATETABLE batch_cp_upd_test1 (LIKE batch_cp_upd_test); CREATEFOREIGNTABLE batch_cp_upd_test1_f
PARTITION OF batch_cp_upd_test FORVALUESIN (1)
SERVER loopback
OPTIONS (table_name 'batch_cp_upd_test1', batch_size '10'); CREATETABLE batch_cp_upd_test2 PARTITION OF batch_cp_upd_test FORVALUESIN (2); CREATETABLE batch_cp_upd_test3 (LIKE batch_cp_upd_test); CREATEFOREIGNTABLE batch_cp_upd_test3_f
PARTITION OF batch_cp_upd_test FORVALUESIN (3)
SERVER loopback
OPTIONS (table_name 'batch_cp_upd_test3', batch_size '1');
-- Create statement triggers on remote tables that "log" any INSERTs -- performed on them. CREATETABLE cmdlog (cmd text); CREATE FUNCTION log_stmt() RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN INSERTINTO public.cmdlog VALUES (TG_OP || ' on ' || TG_RELNAME); RETURNNULL; END;
$$; CREATETRIGGER stmt_trig AFTER INSERTON batch_cp_upd_test1 FOREACH STATEMENT EXECUTE FUNCTION log_stmt(); CREATETRIGGER stmt_trig AFTER INSERTON batch_cp_upd_test3 FOREACH STATEMENT EXECUTE FUNCTION log_stmt();
-- This update moves rows from the local partition 'batch_cp_upd_test2' to the -- foreign partition 'batch_cp_upd_test1', one that has insert batching -- enabled, so a single INSERT for both rows. INSERTINTO batch_cp_upd_test VALUES (2), (2); UPDATE batch_cp_upd_test t SET a = 1FROM (VALUES (1), (2)) s(a) WHERE t.a = s.a AND s.a = 2;
-- This one moves rows from the local partition 'batch_cp_upd_test2' to the -- foreign partition 'batch_cp_upd_test2', one that has insert batching -- disabled, so separate INSERTs for the two rows. INSERTINTO batch_cp_upd_test VALUES (2), (2); UPDATE batch_cp_upd_test t SET a = 3FROM (VALUES (1), (2)) s(a) WHERE t.a = s.a AND s.a = 2;
SELECT tableoid::regclass, * FROM batch_cp_upd_test ORDERBY1;
-- Should see 1 INSERT on batch_cp_upd_test1 and 2 on batch_cp_upd_test3 as -- described above. SELECT * FROM cmdlog ORDERBY1;
-- Clean up DROPTABLE batch_cp_upd_test; DROPTABLE batch_cp_upd_test1; DROPTABLE batch_cp_upd_test3; DROPTABLE cmdlog; DROP FUNCTION log_stmt();
-- Use partitioning ALTER SERVER loopback OPTIONS (ADD batch_size '10');
CREATETABLE batch_table ( x int, field1 text, field2 text) PARTITION BY HASH (x);
INSERTINTO batch_table SELECT i, 'test'||i, 'test'|| i FROM generate_series(1, 50) i; SELECT COUNT(*) FROM batch_table; SELECT * FROM batch_table ORDERBY x;
-- Clean up DROPTABLE batch_table; DROPTABLE batch_table_p0; DROPTABLE batch_table_p1;
ALTER SERVER loopback OPTIONS (DROP batch_size);
-- Test that pending inserts are handled properly when needed CREATETABLE batch_table (a text, b int); CREATEFOREIGNTABLE ftable (a text, b int)
SERVER loopback
OPTIONS (table_name 'batch_table', batch_size '2'); CREATETABLE ltable (a text, b int); CREATE FUNCTION ftable_rowcount_trigf() RETURNS trigger LANGUAGE plpgsql AS
$$
begin
raise notice '%: there are % rows in ftable',
TG_NAME, (SELECT count(*) FROM ftable); if TG_OP = 'DELETE'then return OLD; else return NEW;
end if;
end;
$$; CREATETRIGGER ftable_rowcount_trigger BEFOREINSERTORUPDATEORDELETEON ltable FOREACH ROW EXECUTE PROCEDURE ftable_rowcount_trigf();
WITH t AS ( INSERTINTO ltable VALUES ('AAA', 42), ('BBB', 42) RETURNING *
) INSERTINTO ftable SELECT * FROM t;
SELECT * FROM ltable; SELECT * FROM ftable; DELETEFROM ftable;
WITH t AS ( UPDATE ltable SET b = b + 100 RETURNING *
) INSERTINTO ftable SELECT * FROM t;
SELECT * FROM ltable; SELECT * FROM ftable; DELETEFROM ftable;
WITH t AS ( DELETEFROM ltable RETURNING *
) INSERTINTO ftable SELECT * FROM t;
SELECT * FROM ltable; SELECT * FROM ftable; DELETEFROM ftable;
-- Clean up DROPFOREIGNTABLE ftable; DROPTABLE batch_table; DROPTRIGGER ftable_rowcount_trigger ON ltable; DROPTABLE ltable;
CREATETABLE parent (a text, b int) PARTITION BY LIST (a); CREATETABLE batch_table (a text, b int); CREATEFOREIGNTABLE ftable
PARTITION OF parent FORVALUESIN ('AAA')
SERVER loopback
OPTIONS (table_name 'batch_table', batch_size '2'); CREATETABLE ltable
PARTITION OF parent FORVALUESIN ('BBB'); CREATETRIGGER ftable_rowcount_trigger BEFOREINSERTON ltable FOREACH ROW EXECUTE PROCEDURE ftable_rowcount_trigf();
-- Clean up DROPFOREIGNTABLE ftable; DROPTABLE batch_table; DROPTRIGGER ftable_rowcount_trigger ON ltable; DROPTABLE ltable; DROPTABLE parent; DROP FUNCTION ftable_rowcount_trigf;
-- =================================================================== -- test asynchronous execution -- ===================================================================
ALTER SERVER loopback OPTIONS (DROP extensions); ALTER SERVER loopback OPTIONS (ADD async_capable 'true'); ALTER SERVER loopback2 OPTIONS (ADD async_capable 'true');
CREATETABLE async_pt (a int, b int, c text) PARTITION BY RANGE (a); CREATETABLE base_tbl1 (a int, b int, c text); CREATETABLE base_tbl2 (a int, b int, c text); CREATEFOREIGNTABLE async_p1 PARTITION OF async_pt FORVALUESFROM (1000) TO (2000)
SERVER loopback OPTIONS (table_name 'base_tbl1'); CREATEFOREIGNTABLE async_p2 PARTITION OF async_pt FORVALUESFROM (2000) TO (3000)
SERVER loopback2 OPTIONS (table_name 'base_tbl2'); INSERTINTO async_p1 SELECT1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i; INSERTINTO async_p2 SELECT2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i; ANALYZE async_pt;
-- simple queries CREATETABLE result_tbl (a int, b int, c text);
EXPLAIN (VERBOSE, COSTS OFF) INSERTINTO result_tbl SELECT * FROM async_pt WHERE b % 100 = 0; INSERTINTO result_tbl SELECT * FROM async_pt WHERE b % 100 = 0;
SELECT * FROM result_tbl ORDERBY a; DELETEFROM result_tbl;
EXPLAIN (VERBOSE, COSTS OFF) INSERTINTO result_tbl SELECT * FROM async_pt WHERE b === 505; INSERTINTO result_tbl SELECT * FROM async_pt WHERE b === 505;
SELECT * FROM result_tbl ORDERBY a; DELETEFROM result_tbl;
EXPLAIN (VERBOSE, COSTS OFF) INSERTINTO result_tbl SELECT a, b, 'AAA' || c FROM async_pt WHERE b === 505; INSERTINTO result_tbl SELECT a, b, 'AAA' || c FROM async_pt WHERE b === 505;
SELECT * FROM result_tbl ORDERBY a; DELETEFROM result_tbl;
-- Test error handling, if accessing one of the foreign partitions errors out CREATEFOREIGNTABLE async_p_broken PARTITION OF async_pt FORVALUESFROM (10000) TO (10001)
SERVER loopback OPTIONS (table_name 'non_existent_table'); SELECT * FROM async_pt; DROPFOREIGNTABLE async_p_broken;
-- Check case where multiple partitions use the same connection CREATETABLE base_tbl3 (a int, b int, c text); CREATEFOREIGNTABLE async_p3 PARTITION OF async_pt FORVALUESFROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3'); INSERTINTO async_p3 SELECT3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i; ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF) INSERTINTO result_tbl SELECT * FROM async_pt WHERE b === 505; INSERTINTO result_tbl SELECT * FROM async_pt WHERE b === 505;
SELECT * FROM result_tbl ORDERBY a; DELETEFROM result_tbl;
DROPFOREIGNTABLE async_p3; DROPTABLE base_tbl3;
-- Check case where the partitioned table has local/remote partitions CREATETABLE async_p3 PARTITION OF async_pt FORVALUESFROM (3000) TO (4000); INSERTINTO async_p3 SELECT3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i; ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF) INSERTINTO result_tbl SELECT * FROM async_pt WHERE b === 505; INSERTINTO result_tbl SELECT * FROM async_pt WHERE b === 505;
SELECT * FROM result_tbl ORDERBY a; DELETEFROM result_tbl;
-- partitionwise joins SET enable_partitionwise_join TOtrue;
-- UNION queries SET enable_sort TO off; SET enable_incremental_sort TO off; -- Adjust fdw_startup_cost so that we get an unordered path in the Append. ALTER SERVER loopback2 OPTIONS (ADD fdw_startup_cost '0.00');
EXPLAIN (VERBOSE, COSTS OFF) INSERTINTO result_tbl
(SELECT a, b, 'AAA' || c FROM async_p1 ORDERBY a LIMIT10) UNION
(SELECT a, b, 'AAA' || c FROM async_p2 WHERE b < 10); INSERTINTO result_tbl
(SELECT a, b, 'AAA' || c FROM async_p1 ORDERBY a LIMIT10) UNION
(SELECT a, b, 'AAA' || c FROM async_p2 WHERE b < 10);
SELECT * FROM result_tbl ORDERBY a; DELETEFROM result_tbl;
EXPLAIN (VERBOSE, COSTS OFF) INSERTINTO result_tbl
(SELECT a, b, 'AAA' || c FROM async_p1 ORDERBY a LIMIT10) UNIONALL
(SELECT a, b, 'AAA' || c FROM async_p2 WHERE b < 10); INSERTINTO result_tbl
(SELECT a, b, 'AAA' || c FROM async_p1 ORDERBY a LIMIT10) UNIONALL
(SELECT a, b, 'AAA' || c FROM async_p2 WHERE b < 10);
SELECT * FROM result_tbl ORDERBY a; DELETEFROM result_tbl;
RESET enable_incremental_sort;
RESET enable_sort; ALTER SERVER loopback2 OPTIONS (DROP fdw_startup_cost);
-- Disable async execution if we use gating Result nodes for pseudoconstant -- quals EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM async_pt WHERECURRENT_USER = SESSION_USER;
EXPLAIN (VERBOSE, COSTS OFF)
(SELECT * FROM async_p1 WHERECURRENT_USER = SESSION_USER) UNIONALL
(SELECT * FROM async_p2 WHERECURRENT_USER = SESSION_USER);
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ((SELECT * FROM async_p1 WHERE b < 10) UNIONALL (SELECT * FROM async_p2 WHERE b < 10)) s WHERECURRENT_USER = SESSION_USER;
-- Test that pending requests are processed properly SET enable_mergejoin TOfalse; SET enable_hashjoin TOfalse;
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM async_pt t1, async_p2 t2 WHERE t1.a = t2.a AND t1.b === 505; SELECT * FROM async_pt t1, async_p2 t2 WHERE t1.a = t2.a AND t1.b === 505;
CREATETABLE local_tbl (a int, b int, c text); INSERTINTO local_tbl VALUES (1505, 505, 'foo'); ANALYZE local_tbl;
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM local_tbl t1 LEFTJOIN (SELECT *, (SELECT count(*) FROM async_pt WHERE a < 3000) FROM async_pt WHERE a < 3000) t2 ON t1.a = t2.a; EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF, BUFFERS OFF) SELECT * FROM local_tbl t1 LEFTJOIN (SELECT *, (SELECT count(*) FROM async_pt WHERE a < 3000) FROM async_pt WHERE a < 3000) t2 ON t1.a = t2.a; SELECT * FROM local_tbl t1 LEFTJOIN (SELECT *, (SELECT count(*) FROM async_pt WHERE a < 3000) FROM async_pt WHERE a < 3000) t2 ON t1.a = t2.a;
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM async_pt t1 WHERE t1.b === 505LIMIT1; EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF, BUFFERS OFF) SELECT * FROM async_pt t1 WHERE t1.b === 505LIMIT1; SELECT * FROM async_pt t1 WHERE t1.b === 505LIMIT1;
-- Check with foreign modify CREATETABLE base_tbl3 (a int, b int, c text); CREATEFOREIGNTABLE remote_tbl (a int, b int, c text)
SERVER loopback OPTIONS (table_name 'base_tbl3'); INSERTINTO remote_tbl VALUES (2505, 505, 'bar');
CREATETABLE base_tbl4 (a int, b int, c text); CREATEFOREIGNTABLE insert_tbl (a int, b int, c text)
SERVER loopback OPTIONS (table_name 'base_tbl4');
EXPLAIN (VERBOSE, COSTS OFF) INSERTINTO insert_tbl (SELECT * FROM local_tbl UNIONALLSELECT * FROM remote_tbl); INSERTINTO insert_tbl (SELECT * FROM local_tbl UNIONALLSELECT * FROM remote_tbl);
SELECT * FROM insert_tbl ORDERBY a;
-- Check with direct modify EXPLAIN (VERBOSE, COSTS OFF) WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *) INSERTINTO join_tbl SELECT * FROM async_pt LEFTJOIN t ON (async_pt.a = t.a AND async_pt.b = t.b) WHERE async_pt.b === 505; WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *) INSERTINTO join_tbl SELECT * FROM async_pt LEFTJOIN t ON (async_pt.a = t.a AND async_pt.b = t.b) WHERE async_pt.b === 505;
SELECT * FROM join_tbl ORDERBY a1; DELETEFROM join_tbl;
-- Test that UPDATE/DELETE with inherited target works with async_capable enabled EXPLAIN (VERBOSE, COSTS OFF) UPDATE async_pt SET c = c || c WHERE b = 0 RETURNING *; UPDATE async_pt SET c = c || c WHERE b = 0 RETURNING *; EXPLAIN (VERBOSE, COSTS OFF) DELETEFROM async_pt WHERE b = 0 RETURNING *; DELETEFROM async_pt WHERE b = 0 RETURNING *;
-- Check EXPLAIN ANALYZE for a query that scans empty partitions asynchronously DELETEFROM async_p1; DELETEFROM async_p2; DELETEFROM async_p3;
-- Test that an asynchronous fetch is processed before restarting the scan in -- ReScanForeignScan CREATETABLE base_tbl (a int, b int); INSERTINTO base_tbl VALUES (1, 11), (2, 22), (3, 33); CREATEFOREIGNTABLE foreign_tbl (b int)
SERVER loopback OPTIONS (table_name 'base_tbl'); CREATEFOREIGNTABLE foreign_tbl2 () INHERITS (foreign_tbl)
SERVER loopback OPTIONS (table_name 'base_tbl');
EXPLAIN (VERBOSE, COSTS OFF) SELECT a FROM base_tbl WHERE (a, random() > 0) IN (SELECT a, random() > 0FROM foreign_tbl); SELECT a FROM base_tbl WHERE (a, random() > 0) IN (SELECT a, random() > 0FROM foreign_tbl);
-- Clean up DROPFOREIGNTABLE foreign_tbl CASCADE; DROPTABLE base_tbl;
ALTER SERVER loopback OPTIONS (DROP async_capable); ALTER SERVER loopback2 OPTIONS (DROP async_capable);
-- =================================================================== -- test invalid server, foreign table and foreign data wrapper options -- =================================================================== -- Invalid fdw_startup_cost option CREATE SERVER inv_scst FOREIGN DATA WRAPPER postgres_fdw
OPTIONS(fdw_startup_cost '100$%$#$#'); -- Invalid fdw_tuple_cost option CREATE SERVER inv_scst FOREIGN DATA WRAPPER postgres_fdw
OPTIONS(fdw_tuple_cost '100$%$#$#'); -- Invalid fetch_size option CREATEFOREIGNTABLE inv_fsz (c1 int )
SERVER loopback OPTIONS (fetch_size '100$%$#$#'); -- Invalid batch_size option CREATEFOREIGNTABLE inv_bsz (c1 int )
SERVER loopback OPTIONS (batch_size '100$%$#$#');
-- No option is allowed to be specified at foreign data wrapper level ALTERFOREIGN DATA WRAPPER postgres_fdw OPTIONS (nonexistent 'fdw');
-- =================================================================== -- test postgres_fdw.application_name GUC -- =================================================================== -- To avoid race conditions in checking the remote session's application_name, -- use this view to make the remote session itself read its application_name. CREATE VIEW my_application_name AS SELECT application_name FROM pg_stat_activity WHERE pid = pg_backend_pid();
-- Specify escape sequences in application_name option of a server -- object so as to test that they are replaced with status information -- expectedly. Note that we are also relying on ALTER SERVER to force -- the remote session to be restarted with its new application name. -- -- Since pg_stat_activity.application_name may be truncated to less than -- NAMEDATALEN characters, note that substring() needs to be used -- at the condition of test query to make sure that the string consisting -- of database name and process ID is also less than that. ALTER SERVER loopback2 OPTIONS (application_name 'fdw_%d%p'); SELECT count(*) FROM remote_application_name WHERE application_name =
substring('fdw_' || current_database() || pg_backend_pid() for
current_setting('max_identifier_length')::int);
-- postgres_fdw.application_name overrides application_name option -- of a server object if both settings are present. ALTER SERVER loopback2 OPTIONS (SET application_name 'fdw_wrong'); SET postgres_fdw.application_name TO'fdw_%a%u%%'; SELECT count(*) FROM remote_application_name WHERE application_name =
substring('fdw_' || current_setting('application_name') || CURRENT_USER || '%'for current_setting('max_identifier_length')::int);
RESET postgres_fdw.application_name;
-- Test %c (session ID) and %C (cluster name) escape sequences. ALTER SERVER loopback2 OPTIONS (SET application_name 'fdw_%C%c'); SELECT count(*) FROM remote_application_name WHERE application_name =
substring('fdw_' || current_setting('cluster_name') ||
to_hex(trunc(EXTRACT(EPOCH FROM (SELECT backend_start FROM
pg_stat_get_activity(pg_backend_pid()))))::integer) || '.' ||
to_hex(pg_backend_pid()) for current_setting('max_identifier_length')::int);
-- Clean up. DROPFOREIGNTABLE remote_application_name; DROP VIEW my_application_name;
-- =================================================================== -- test parallel commit and parallel abort -- =================================================================== ALTER SERVER loopback OPTIONS (ADD parallel_commit 'true'); ALTER SERVER loopback OPTIONS (ADD parallel_abort 'true'); ALTER SERVER loopback2 OPTIONS (ADD parallel_commit 'true'); ALTER SERVER loopback2 OPTIONS (ADD parallel_abort 'true');
-- This tests executing DEALLOCATE ALL against foreign servers in parallel -- during pre-commit
BEGIN;
SAVEPOINT s; INSERTINTO prem1 VALUES (103, 'baz'); INSERTINTO prem2 VALUES (203, 'qux');
ROLLBACK TO SAVEPOINT s; RELEASE SAVEPOINT s; INSERTINTO prem1 VALUES (104, 'bazbaz'); INSERTINTO prem2 VALUES (204, 'quxqux'); COMMIT; SELECT * FROM prem1; SELECT * FROM prem2;
BEGIN; INSERTINTO prem1 VALUES (105, 'test1'); INSERTINTO prem2 VALUES (205, 'test2');
ABORT; SELECT * FROM prem1; SELECT * FROM prem2;
-- This tests executing DEALLOCATE ALL against foreign servers in parallel -- during post-abort
BEGIN;
SAVEPOINT s; INSERTINTO prem1 VALUES (105, 'test1'); INSERTINTO prem2 VALUES (205, 'test2');
ROLLBACK TO SAVEPOINT s; RELEASE SAVEPOINT s; INSERTINTO prem1 VALUES (105, 'test1'); INSERTINTO prem2 VALUES (205, 'test2');
ABORT; SELECT * FROM prem1; SELECT * FROM prem2;
ALTER SERVER loopback OPTIONS (DROP parallel_commit); ALTER SERVER loopback OPTIONS (DROP parallel_abort); ALTER SERVER loopback2 OPTIONS (DROP parallel_commit); ALTER SERVER loopback2 OPTIONS (DROP parallel_abort);
-- =================================================================== -- test for ANALYZE sampling -- ===================================================================
CREATETABLE analyze_table (id int, a text, b bigint);
CREATEFOREIGNTABLE analyze_ftable (id int, a text, b bigint)
SERVER loopback OPTIONS (table_name 'analyze_table');
INSERTINTO analyze_table (SELECT x FROM generate_series(1,1000) x); ANALYZE analyze_table;
SET default_statistics_target = 10; ANALYZE analyze_table;
ALTER SERVER loopback OPTIONS (analyze_sampling 'invalid');
ALTER SERVER loopback OPTIONS (analyze_sampling 'auto'); ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'system'); ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'bernoulli'); ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'random'); ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'off'); ANALYZE analyze_ftable;
-- =================================================================== -- test for postgres_fdw_get_connections function with check_conn = true -- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections SET debug_discard_caches TO'0';
-- The text of the error might vary across platforms, so only show SQLSTATE.
\set VERBOSITY sqlstate
SELECT1FROM postgres_fdw_disconnect_all(); ALTER SERVER loopback OPTIONS (SET application_name 'fdw_conn_check'); SELECT1FROM ft1 LIMIT1;
-- Since the remote server is still connected, "closed" should be FALSE, -- or NULL if the connection status check is not available. -- In this test, the remote backend handling this connection should have -- application_name set to "fdw_conn_check", so remote_backend_pid should -- match the PID from the pg_stat_activity entry with that application_name. SELECT server_name, CASEWHEN closed ISNOTtrueTHENfalseELSEtrue END AS closed,
remote_backend_pid = (SELECT pid FROM pg_stat_activity WHERE application_name = 'fdw_conn_check') AS remote_backend_pid FROM postgres_fdw_get_connections(true);
-- After terminating the remote backend, since the connection is closed, -- "closed" should be TRUE, or NULL if the connection status check -- is not available. Despite the termination, remote_backend_pid should -- still show the non-zero PID of the terminated remote backend.
DO $$ BEGIN
PERFORM pg_terminate_backend(pid, 180000) FROM pg_stat_activity WHERE application_name = 'fdw_conn_check';
END $$; SELECT server_name, CASEWHEN closed ISNOTfalseTHENtrueELSEfalse END AS closed,
remote_backend_pid <> 0AS remote_backend_pid FROM postgres_fdw_get_connections(true);
-- Clean up
\set VERBOSITY default
RESET debug_discard_caches;
-- =================================================================== -- test cleanup of failed connections on abort -- ===================================================================
CREATE VIEW my_backend_pid (pid) ASSELECT pg_backend_pid(); CREATEFOREIGNTABLE remote_backend_pid (pid int)
SERVER loopback OPTIONS (table_name 'my_backend_pid'); CREATE FUNCTION wait_for_backend_termination(int) RETURNS void AS $$
BEGIN WHILE (SELECT count(*) FROM pg_stat_activity WHERE pid = $1) > 0 LOOP
PERFORM pg_stat_clear_snapshot();
END LOOP;
END
$$ LANGUAGE plpgsql;
SET client_min_messages = 'ERROR';
BEGIN; DECLARE c CURSORFORSELECT * FROM ft1 ORDERBY c1;
SAVEPOINT s; SELECT pid AS remote_pid FROM remote_backend_pid \gset SELECT pg_terminate_backend(:remote_pid); SELECT wait_for_backend_termination(:remote_pid);
ROLLBACK TO SAVEPOINT s; SELECT pid FROM remote_backend_pid;
ROLLBACK TO SAVEPOINT s; RELEASE SAVEPOINT s; FETCH c;
ABORT;
BEGIN; DECLARE c CURSORFORSELECT * FROM ft1 ORDERBY c1; FETCH c;
SAVEPOINT s; SELECT pid AS remote_pid FROM remote_backend_pid \gset SELECT pg_terminate_backend(:remote_pid); SELECT wait_for_backend_termination(:remote_pid);
ROLLBACK TO SAVEPOINT s; SELECT pid FROM remote_backend_pid;
ROLLBACK TO SAVEPOINT s; RELEASE SAVEPOINT s;
CLOSE c;
ABORT;
RESET client_min_messages;
DROP FUNCTION wait_for_backend_termination(int); DROPFOREIGNTABLE remote_backend_pid; DROP VIEW my_backend_pid;
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.158 Sekunden
(vorverarbeitet am 2026-08-08)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.