pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
[PATCH 2/6] silence compiler warning
36+ messages / 11 participants
[nested] [flat]

Commits from this thread:
  2026-08-19 9716f88ddf  Fix compilation warning in 0ee83dd4a994
  2026-08-19 0ee83dd4a9  postgres_fdw: push down FUNCTION RTE into foreign joins
* [PATCH 2/6] silence compiler warning
@ 2019-11-28 22:08 Alvaro Herrera <alvherre@alvh.no-ip.org>
  0 siblings, 0 replies; 36+ messages in thread

From: Alvaro Herrera @ 2019-11-28 22:08 UTC (permalink / raw)

---
 src/backend/parser/parse_coerce.c | 2 ++
 1 file changed, 2 insertions(+)

inline patch 1: src/backend/parser/parse_coerce.c (+2/-0 lines) download inline-1.patchdiff --git a/src/backend/parser/parse_coerce.c b/src/backend/parser/parse_coerce.c index 49c75dc12d..b43b2dc612 100644 --- a/src/backend/parser/parse_coerce.c +++ b/src/backend/parser/parse_coerce.c @@ -1592,6 +1592,8 @@ check_generic_type_consistency(const Oid *actual_arg_types, return false; } } + else + range_typelem = InvalidOid; /* keep compiler quiet */ /* Get the element type based on the multirange type, if we have one */ if (OidIsValid(multirange_typeid)) -- 2.20.1
--+QahgC5+KEYLbs62 Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="0003-Be-less-verbose-on-variable-names.patch" ^ permalink raw reply [nested|flat] 36+ messages in thread

* Function scan FDW pushdown
@ 2021-05-20 17:43 Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2021-06-15 13:15 ` Re: Function scan FDW pushdown Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2021-05-20 17:43 UTC (permalink / raw)
  To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi.

The attached patch allows pushing joins with function RTEs to PostgreSQL 
data sources.
This makes executing queries like this

create foreign table f_pgbench_accounts (aid int, bid int, abalance int, 
filler char(84)) SERVER local_srv OPTIONS (table_name 
'pgbench_accounts');
select * from f_pgbench_accounts join unnest(array[1,2,3]) ON unnest = 
aid;

more efficient.

with patch:

# explain analyze select * from f_pgbench_accounts join 
unnest(array[1,2,3,4,5,6]) ON unnest = aid;
                                            QUERY PLAN
------------------------------------------------------------------------------------------------
  Foreign Scan  (cost=100.00..116.95 rows=7 width=356) (actual 
time=2.282..2.287 rows=6 loops=1)
    Relations: (f_pgbench_accounts) INNER JOIN (FUNCTION RTE unnest)
  Planning Time: 0.487 ms
  Execution Time: 3.336 ms

without patch:

# explain analyze select * from f_pgbench_accounts join 
unnest(array[1,2,3,4,5,6]) ON unnest = aid;
                                                               QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------
  Hash Join  (cost=100.14..158.76 rows=7 width=356) (actual 
time=2.263..1268.607 rows=6 loops=1)
    Hash Cond: (f_pgbench_accounts.aid = unnest.unnest)
    ->  Foreign Scan on f_pgbench_accounts  (cost=100.00..157.74 rows=217 
width=352) (actual time=2.190..1205.938 rows=100000 loops=1)
    ->  Hash  (cost=0.06..0.06 rows=6 width=4) (actual time=0.041..0.043 
rows=6 loops=1)
          Buckets: 1024  Batches: 1  Memory Usage: 9kB
          ->  Function Scan on unnest  (cost=0.00..0.06 rows=6 width=4) 
(actual time=0.025..0.028 rows=6 loops=1)
  Planning Time: 0.389 ms
  Execution Time: 1269.627 ms

So far I don't know how to visualize actual function expression used in 
function RTE, as in postgresExplainForeignScan() es->rtable comes from  
queryDesc->plannedstmt->rtable, and rte->functions is already 0.

-- 
Best regards,
Alexander Pyhalov,
Postgres Professional

Attachments:

0001-Function-scan-FDW-pushdown.patch (text/x-diff, 26.8K) download From 6b5ea4c62a1fcd3dad586d4f461cb142834ac266 Mon Sep 17 00:00:00 2001 From: Alexander Pyhalov <a.pyhalov@postgrespro.ru> Date: Mon, 17 May 2021 19:19:31 +0300 Subject: [PATCH] Function scan FDW pushdown --- contrib/postgres_fdw/deparse.c | 82 ++++-- .../postgres_fdw/expected/postgres_fdw.out | 123 ++++++++ contrib/postgres_fdw/postgres_fdw.c | 273 ++++++++++++++++-- contrib/postgres_fdw/sql/postgres_fdw.sql | 60 ++++ src/backend/optimizer/util/relnode.c | 58 +++- 5 files changed, 547 insertions(+), 49 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 31919fda8c6..292ba52ea14 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -1613,13 +1613,36 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, { RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); - /* - * Core code already has some lock on each rel being planned, so we - * can use NoLock here. - */ - Relation rel = table_open(rte->relid, NoLock); + Assert(rte->rtekind == RTE_RELATION || rte->rtekind == RTE_FUNCTION); + if (rte->rtekind == RTE_RELATION) + { + /* + * Core code already has some lock on each rel being planned, so + * we can use NoLock here. + */ + Relation rel = table_open(rte->relid, NoLock); - deparseRelation(buf, rel); + deparseRelation(buf, rel); + + table_close(rel, NoLock); + } + else if (rte->rtekind == RTE_FUNCTION) + { + RangeTblFunction *rtfunc; + deparse_expr_cxt context; + + Assert(list_length(rte->functions) == 1); + + rtfunc = (RangeTblFunction *) linitial(rte->functions); + + context.root = root; + context.foreignrel = foreignrel; + context.scanrel = foreignrel; + context.buf = buf; + context.params_list = params_list; + + deparseExpr((Expr *) rtfunc->funcexpr, &context); + } /* * Add a unique alias to avoid any conflict in relation names due to @@ -1628,8 +1651,6 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, */ if (use_alias) appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, foreignrel->relid); - - table_close(rel, NoLock); } } @@ -2309,29 +2330,40 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, * If it's a column of a foreign table, and it has the column_name FDW * option, use that value. */ - options = GetForeignColumnOptions(rte->relid, varattno); - foreach(lc, options) + if (rte->rtekind == RTE_RELATION) { - DefElem *def = (DefElem *) lfirst(lc); - - if (strcmp(def->defname, "column_name") == 0) + options = GetForeignColumnOptions(rte->relid, varattno); + foreach(lc, options) { - colname = defGetString(def); - break; + DefElem *def = (DefElem *) lfirst(lc); + + if (strcmp(def->defname, "column_name") == 0) + { + colname = defGetString(def); + break; + } } - } - /* - * If it's a column of a regular table or it doesn't have column_name - * FDW option, use attribute name. - */ - if (colname == NULL) - colname = get_attname(rte->relid, varattno, false); + /* + * If it's a column of a regular table or it doesn't have + * column_name FDW option, use attribute name. + */ + if (colname == NULL) + colname = get_attname(rte->relid, varattno, false); - if (qualify_col) - ADD_REL_QUALIFIER(buf, varno); + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); - appendStringInfoString(buf, quote_identifier(colname)); + appendStringInfoString(buf, quote_identifier(colname)); + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * If it's a column of a function rte, use not column name, but + * RTE alias + */ + appendStringInfo((buf), "%s%d", REL_ALIAS_PREFIX, (varno)); + } } } diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index 7df30010f25..da3abd453c2 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -10231,3 +10231,126 @@ DROP TABLE result_tbl; DROP TABLE join_tbl; ALTER SERVER loopback OPTIONS (DROP async_capable); ALTER SERVER loopback2 OPTIONS (DROP async_capable); +-- =================================================================== +-- test function scan pushdown +-- =================================================================== +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl'); +ALTER FOREIGN TABLE remote_tbl OPTIONS (use_remote_estimate 'true'); +CREATE TABLE base_tbl1 (c int, d text); +CREATE FOREIGN TABLE remote_tbl1 (c int, d text) + SERVER loopback OPTIONS (table_name 'base_tbl1'); +ALTER FOREIGN TABLE remote_tbl1 OPTIONS (use_remote_estimate 'true'); +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO remote_tbl1 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE base_tbl; +ANALYZE base_tbl1; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, n.n + Relations: (public.remote_tbl r) INNER JOIN (FUNCTION RTE n) + Remote SQL: SELECT r1.a, r1.b, r2 FROM (public.base_tbl r1 INNER JOIN unnest('{2,3,4}'::integer[]) r2 ON (((r1.a = r2)))) +(4 rows) + +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n +ORDER BY r.a; + a | b | n +---+---+--- + 2 | 4 | 2 + 3 | 6 | 3 + 4 | 8 | 4 +(3 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: n.n, r.a, r.b + Relations: (FUNCTION RTE n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT r1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) r1 INNER JOIN public.base_tbl r2 ON (((r1 = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n +ORDER BY r.a; + n | a | b +---+---+--- + 2 | 2 | 4 + 3 | 3 | 6 + 4 | 4 | 8 +(3 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a; + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, r1.c, r1.d, n.n + Relations: ((public.remote_tbl r) INNER JOIN (public.remote_tbl1 r1)) INNER JOIN (FUNCTION RTE n) + Remote SQL: SELECT r1.a, r1.b, r2.c, r2.d, r3 FROM ((public.base_tbl r1 INNER JOIN public.base_tbl1 r2 ON (((r1.a = r2.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 ON (((r1.a = r3)))) +(4 rows) + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = r1.c AND r1.c = n +ORDER BY r.a; + a | b | c | d | n +---+---+---+-------+--- + 3 | 6 | 3 | text3 | 3 + 4 | 8 | 4 | text4 | 4 +(2 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*,n from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: r.a, r.b, n.n + Relations: ((public.remote_tbl r) INNER JOIN (public.remote_tbl1 r1)) INNER JOIN (FUNCTION RTE n) + Remote SQL: SELECT r1.a, r1.b, r3 FROM ((public.base_tbl r1 INNER JOIN public.base_tbl1 r2 ON (((r1.a = r2.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 ON (((r1.a = r3)) AND ((r3 > 3)))) +(4 rows) + +SELECT * from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + a | b | c | d | n +---+---+---+-------+--- + 4 | 8 | 4 | text4 | 4 +(1 row) + +-- Test that local functions are not pushed down +CREATE OR REPLACE FUNCTION f(INTEGER) +RETURNS SETOF INTEGER +LANGUAGE sql AS 'select generate_series(1,$1);' IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, f(10) n +WHERE r.a = n; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: r.a, r.b, (generate_series(1, 10)) + Hash Cond: (r.a = (generate_series(1, 10))) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a, b FROM public.base_tbl + -> Hash + Output: (generate_series(1, 10)) + -> ProjectSet + Output: generate_series(1, 10) + -> Result +(11 rows) + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a AND n > 3; + a | b | c | d | n +---+---+---+-------+--- + 4 | 8 | 4 | text4 | 4 +(1 row) + +DROP FUNCTION f(INTEGER); +DROP TABLE base_tbl, base_tbl1; +DROP FOREIGN TABLE remote_tbl, remote_tbl1; diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index c48a421e88b..cf2db2379ed 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -547,6 +547,11 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_i); static int get_batch_size_option(Relation rel); +static bool is_nonrel_relinfo_ok(PlannerInfo *root, RelOptInfo *foreignrel); +static void initialize_nonrel_fpinfo(PlannerInfo *root, + RelOptInfo *baserel, + PgFdwRelationInfo *existing_fpinfo); + /* * Foreign-data wrapper handler function: return a struct with pointers @@ -787,6 +792,142 @@ postgresGetForeignRelSize(PlannerInfo *root, fpinfo->relation_index = baserel->relid; } +/* + * initialize_nonrel_fpinfo + * Initialize fpinfo for non-refering tables queries + */ +static void +initialize_nonrel_fpinfo(PlannerInfo *root, + RelOptInfo *baserel, + PgFdwRelationInfo *existing_fpinfo) +{ + PgFdwRelationInfo *fpinfo; + ListCell *lc; + + Assert(existing_fpinfo); + + /* + * We use PgFdwRelationInfo to pass various information to subsequent + * functions. + */ + fpinfo = (PgFdwRelationInfo *) palloc0(sizeof(PgFdwRelationInfo)); + baserel->fdw_private = (void *) fpinfo; + + /* Base foreign tables need to be pushed down always. */ + fpinfo->pushdown_safe = true; + + /* We don't have any table, related to query */ + fpinfo->table = NULL; + fpinfo->server = GetForeignServer(existing_fpinfo->server->serverid); + + /* + * Extract user-settable option values. Note that per-table settings of + * use_remote_estimate, fetch_size and async_capable override per-server + * settings of them, respectively. + */ + merge_fdw_options(fpinfo, existing_fpinfo, NULL); + + /* + * If the table or the server is configured to use remote estimates, + * identify which user to do remote access as during planning. This + * should match what ExecCheckRTEPerms() does. If we fail due to lack of + * permissions, the query would have failed at runtime anyway. + */ + fpinfo->user = existing_fpinfo->user; + + /* + * Identify which baserestrictinfo clauses can be sent to the remote + * server and which can't. + */ + classifyConditions(root, baserel, baserel->baserestrictinfo, + &fpinfo->remote_conds, &fpinfo->local_conds); + + /* + * Identify which attributes will need to be retrieved from the remote + * server. These include all attrs needed for joins or final output, plus + * all attrs used in the local_conds. (Note: if we end up using a + * parameterized scan, it's possible that some of the join clauses will be + * sent to the remote and thus we wouldn't really need to retrieve the + * columns used in them. Doesn't seem worth detecting that case though.) + */ + fpinfo->attrs_used = NULL; + pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid, + &fpinfo->attrs_used); + foreach(lc, fpinfo->local_conds) + { + RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc); + + pull_varattnos((Node *) rinfo->clause, baserel->relid, + &fpinfo->attrs_used); + } + + /* + * Compute the selectivity and cost of the local_conds, so we don't have + * to do it over again for each path. The best we can do for these + * conditions is to estimate selectivity on the basis of local statistics. + */ + fpinfo->local_conds_sel = clauselist_selectivity(root, + fpinfo->local_conds, + baserel->relid, + JOIN_INNER, + NULL); + + cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root); + + /* + * Set # of retrieved rows and cached relation costs to some negative + * value, so that we can detect when they are set to some sensible values, + * during one (usually the first) of the calls to estimate_path_cost_size. + */ + fpinfo->retrieved_rows = -1; + fpinfo->rel_startup_cost = -1; + fpinfo->rel_total_cost = -1; + + /* + * Don't try to execute anything on remote server for non-relation-based + * query + */ + fpinfo->use_remote_estimate = false; + + /* + * If the foreign table has never been ANALYZEd, it will have reltuples < + * 0, meaning "unknown". We can't do much if we're not allowed to consult + * the remote server, but we can use a hack similar to plancat.c's + * treatment of empty relations: use a minimum size estimate of 10 pages, + * and divide by the column-datatype-based width estimate to get the + * corresponding number of tuples. + */ + if (baserel->tuples < 0) + { + baserel->pages = 10; + baserel->tuples = + (10 * BLCKSZ) / (baserel->reltarget->width + + MAXALIGN(SizeofHeapTupleHeader)); + } + + /* Estimate baserel size as best we can with local statistics. */ + set_baserel_size_estimates(root, baserel); + + /* Fill in basically-bogus cost estimates for use later. */ + estimate_path_cost_size(root, baserel, NIL, NIL, NULL, + &fpinfo->rows, &fpinfo->width, + &fpinfo->startup_cost, &fpinfo->total_cost); + + /* + * fpinfo->relation_name gets the numeric rangetable index of the foreign + * table RTE. (If this query gets EXPLAIN'd, we'll convert that to a + * human-readable string at that time.) + */ + fpinfo->relation_name = psprintf("%u", baserel->relid); + + /* No outer and inner relations. */ + fpinfo->make_outerrel_subquery = false; + fpinfo->make_innerrel_subquery = false; + fpinfo->lower_subquery_rels = NULL; + /* Set the relation index. */ + fpinfo->relation_index = baserel->relid; +} + /* * get_useful_ecs_for_relation * Determine which EquivalenceClasses might be involved in useful @@ -1470,15 +1611,25 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckRTEPerms() does. In case of a join or aggregate, use the - * lowest-numbered member RTE as a representative; we would get the same - * result from any. + * ExecCheckRTEPerms() does. In case of a join or aggregate, scan RTEs + * until RTE_RELATION is found. We would get the same result from any. */ if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte && rte->rtekind == RTE_RELATION) + break; + } + Assert(rte && rte->rtekind == RTE_RELATION); + } userid = rte->checkAsUser ? rte->checkAsUser : GetUserId(); /* Get info about foreign table. */ @@ -2795,21 +2946,57 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_relids)); rte = rt_fetch(rti, es->rtable); - Assert(rte->rtekind == RTE_RELATION); /* This logic should agree with explain.c's ExplainTargetRel */ - relname = get_rel_name(rte->relid); - if (es->verbose) + if (rte->rtekind == RTE_RELATION) { - char *namespace; - - namespace = get_namespace_name(get_rel_namespace(rte->relid)); - appendStringInfo(relations, "%s.%s", - quote_identifier(namespace), - quote_identifier(relname)); + relname = get_rel_name(rte->relid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name(get_rel_namespace(rte->relid)); + appendStringInfo(relations, "%s.%s", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfoString(relations, + quote_identifier(relname)); + } + else if (rte->rtekind == RTE_FUNCTION) + { + appendStringInfoString(relations, "FUNCTION RTE"); +#if 0 + + /* + * TODO: rte->functions is always 0, how should we proceed + * here ? + */ + if (list_length(rte->functions) == 1) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) linitial(rte->functions); + + if (IsA(rtfunc->funcexpr, FuncExpr)) + { + FuncExpr *funcexpr = (FuncExpr *) rtfunc->funcexpr; + Oid funcid = funcexpr->funcid; + + relname = get_func_name(funcid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name(get_func_namespace(funcid)); + appendStringInfo(relations, "%s.%s()", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfo(relations, "%s()", quote_identifier(relname)); + } + } +#endif } - else - appendStringInfoString(relations, - quote_identifier(relname)); refname = (char *) list_nth(es->rtable_names, rti - 1); if (refname == NULL) refname = rte->eref->aliasname; @@ -5405,6 +5592,27 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid) return commands; } +/* + * Determine if foreignrel, not backed by foreign + * table, is fine to push down. + */ +static bool +is_nonrel_relinfo_ok(PlannerInfo *root, RelOptInfo *foreignrel) +{ + RangeTblEntry *rte; + RangeTblFunction *rtfunc; + + rte = planner_rt_fetch(foreignrel->relid, root); + + /* For now only this RTE type can come without fpinfo */ + Assert(rte && rte->rtekind == RTE_FUNCTION); + Assert(list_length(rte->functions) == 1); + + rtfunc = (RangeTblFunction *) linitial(rte->functions); + + return is_foreign_expr(root, foreignrel, (Expr *) rtfunc->funcexpr); +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -5430,13 +5638,37 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, jointype != JOIN_RIGHT && jointype != JOIN_FULL) return false; + fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + + if (!fpinfo_o && !fpinfo_i) + return false; + + if (!fpinfo_o) + { + + initialize_nonrel_fpinfo(root, outerrel, fpinfo_i); + + if (!is_nonrel_relinfo_ok(root, outerrel)) + return false; + + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + } + if (!fpinfo_i) + { + initialize_nonrel_fpinfo(root, innerrel, fpinfo_o); + + if (!is_nonrel_relinfo_ok(root, innerrel)) + return false; + + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + } + /* * If either of the joining relations is marked as unsafe to pushdown, the * join can not be pushed down. */ - fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; if (!fpinfo_o || !fpinfo_o->pushdown_safe || !fpinfo_i || !fpinfo_i->pushdown_safe) return false; @@ -5578,6 +5810,7 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, case JOIN_RIGHT: fpinfo->joinclauses = list_concat(fpinfo->joinclauses, fpinfo_o->remote_conds); + fpinfo->remote_conds = list_concat(fpinfo->remote_conds, fpinfo_i->remote_conds); break; diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 78379bdea5b..da25c535dd5 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -3262,3 +3262,63 @@ DROP TABLE join_tbl; ALTER SERVER loopback OPTIONS (DROP async_capable); ALTER SERVER loopback2 OPTIONS (DROP async_capable); + +-- =================================================================== +-- test function scan pushdown +-- =================================================================== +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl'); +ALTER FOREIGN TABLE remote_tbl OPTIONS (use_remote_estimate 'true'); +CREATE TABLE base_tbl1 (c int, d text); +CREATE FOREIGN TABLE remote_tbl1 (c int, d text) + SERVER loopback OPTIONS (table_name 'base_tbl1'); +ALTER FOREIGN TABLE remote_tbl1 OPTIONS (use_remote_estimate 'true'); + +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO remote_tbl1 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE base_tbl; +ANALYZE base_tbl1; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n; + +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n; + +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a; + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = r1.c AND r1.c = n +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*,n from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + +SELECT * from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + +-- Test that local functions are not pushed down +CREATE OR REPLACE FUNCTION f(INTEGER) +RETURNS SETOF INTEGER +LANGUAGE sql AS 'select generate_series(1,$1);' IMMUTABLE; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, f(10) n +WHERE r.a = n; + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a AND n > 3; + +DROP FUNCTION f(INTEGER); +DROP TABLE base_tbl, base_tbl1; +DROP FOREIGN TABLE remote_tbl, remote_tbl1; diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index e105a4d5f1d..80f29482ef8 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -22,12 +22,14 @@ #include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" +#include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/plancat.h" #include "optimizer/restrictinfo.h" #include "optimizer/tlist.h" +#include "parser/parsetree.h" #include "utils/hsearch.h" #include "utils/lsyscache.h" @@ -53,7 +55,8 @@ static List *subbuild_joinrel_restrictlist(RelOptInfo *joinrel, static List *subbuild_joinrel_joinlist(RelOptInfo *joinrel, List *joininfo_list, List *new_joininfo); -static void set_foreign_rel_properties(RelOptInfo *joinrel, +static void set_foreign_rel_properties(PlannerInfo *root, + RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel); static void add_join_rel(PlannerInfo *root, RelOptInfo *joinrel); static void build_joinrel_partition_info(RelOptInfo *joinrel, @@ -498,7 +501,7 @@ find_join_rel(PlannerInfo *root, Relids relids) * */ static void -set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, +set_foreign_rel_properties(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel) { if (OidIsValid(outer_rel->serverid) && @@ -528,6 +531,53 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if ((OidIsValid(outer_rel->serverid) && + inner_rel->serverid == InvalidOid) || + (OidIsValid(inner_rel->serverid) && + outer_rel->serverid == InvalidOid)) + { + RelOptInfo *foreign_rel; + RelOptInfo *local_rel; + RangeTblEntry *rte; + + foreign_rel = OidIsValid(outer_rel->serverid) ? outer_rel : inner_rel; + local_rel = OidIsValid(outer_rel->serverid) ? inner_rel : outer_rel; + rte = planner_rt_fetch(local_rel->relid, root); + + if (!rte) + return; + + switch (rte->rtekind) + { + case RTE_FUNCTION: + { + ListCell *lc; + + /* For now support only one function */ + if (list_length(rte->functions) > 1) + return; + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (contain_var_clause(rtfunc->funcexpr) || + contain_mutable_functions(rtfunc->funcexpr) || + contain_subplans(rtfunc->funcexpr)) + return; + } + break; + } + default: + /* Avoid pushing unsupported RelOptInfo */ + return; + } + + joinrel->serverid = foreign_rel->serverid; + joinrel->userid = foreign_rel->userid; + joinrel->useridiscurrent = foreign_rel->useridiscurrent; + joinrel->fdwroutine = foreign_rel->fdwroutine; + } } /* @@ -674,7 +724,7 @@ build_join_rel(PlannerInfo *root, joinrel->nullable_partexprs = NULL; /* Compute information relevant to the foreign relations. */ - set_foreign_rel_properties(joinrel, outer_rel, inner_rel); + set_foreign_rel_properties(root, joinrel, outer_rel, inner_rel); /* * Create a new tlist containing just the vars that need to be output from @@ -855,7 +905,7 @@ build_child_join_rel(PlannerInfo *root, RelOptInfo *outer_rel, inner_rel->top_parent_relids); /* Compute information relevant to foreign relations. */ - set_foreign_rel_properties(joinrel, outer_rel, inner_rel); + set_foreign_rel_properties(root, joinrel, outer_rel, inner_rel); /* Compute information needed for mapping Vars to the child rel */ appinfos = find_appinfos_by_relids(root, joinrel->relids, &nappinfos); -- 2.25.1
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2021-05-20 17:43 Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2021-06-15 13:15 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
  2021-10-04 07:42   ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  0 siblings, 1 reply; 36+ messages in thread

From: Ashutosh Bapat @ 2021-06-15 13:15 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Alexander,

On Thu, May 20, 2021 at 11:13 PM Alexander Pyhalov
<a.pyhalov@postgrespro.ru> wrote:
>
> Hi.
>
> The attached patch allows pushing joins with function RTEs to PostgreSQL
> data sources.
> This makes executing queries like this
>
> create foreign table f_pgbench_accounts (aid int, bid int, abalance int,
> filler char(84)) SERVER local_srv OPTIONS (table_name
> 'pgbench_accounts');
> select * from f_pgbench_accounts join unnest(array[1,2,3]) ON unnest =
> aid;
>

It will be good to provide some practical examples where this is useful.



> more efficient.
>
> with patch:
>
>
> So far I don't know how to visualize actual function expression used in
> function RTE, as in postgresExplainForeignScan() es->rtable comes from
> queryDesc->plannedstmt->rtable, and rte->functions is already 0.

The actual function expression will be part of the Remote SQL of
ForeignScan node so no need to visualize it separately.

The patch will have problems when there are multiple foreign tables
all on different servers or use different FDWs. In such a case the
function scan's RelOptInfo will get the fpinfo based on the first
foreign table the function scan is paired with during join planning.
But that may not be the best foreign table to join. We should be able
to plan all the possible joins. Current infra to add one fpinfo per
RelOptInfo won't help there. We need something better.

The patch targets only postgres FDW, how do you see this working with
other FDWs?

If we come up with the right approach we could use it for 1. pushing
down queries with IN () clause 2. joining a small local table with a
large foreign table by sending the local table rows down to the
foreign server.

-- 
Best Wishes,
Ashutosh Bapat





^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2021-05-20 17:43 Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2021-06-15 13:15 ` Re: Function scan FDW pushdown Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
@ 2021-10-04 07:42   ` Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2024-11-05 16:11     ` Re: Function scan FDW pushdown g.kashkin@postgrespro.ru
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2021-10-04 07:42 UTC (permalink / raw)
  To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Ashutosh Bapat писал 2021-06-15 16:15:
> Hi Alexander,

Hi.

The current version of the patch is based on asymetric partition-wise 
join.
Currently it is applied after 
v19-0001-Asymmetric-partitionwise-join.patch from
on 
https://www.postgresql.org/message-id/792d60f4-37bc-e6ad-68ca-c2af5cbb2d9b@postgrespro.ru 
.

>> So far I don't know how to visualize actual function expression used 
>> in
>> function RTE, as in postgresExplainForeignScan() es->rtable comes from
>> queryDesc->plannedstmt->rtable, and rte->functions is already 0.
> 
> The actual function expression will be part of the Remote SQL of
> ForeignScan node so no need to visualize it separately.

We still need to create tuple description for functions in 
get_tupdesc_for_join_scan_tuples(),
so I had to remove setting newrte->functions to NIL in 
add_rte_to_flat_rtable().
With rte->functions in place, there's no issues for explain.

> 
> The patch will have problems when there are multiple foreign tables
> all on different servers or use different FDWs. In such a case the
> function scan's RelOptInfo will get the fpinfo based on the first
> foreign table the function scan is paired with during join planning.
> But that may not be the best foreign table to join. We should be able
> to plan all the possible joins. Current infra to add one fpinfo per
> RelOptInfo won't help there. We need something better.

I suppose attached version of the patch is more mature.

> 
> The patch targets only postgres FDW, how do you see this working with
> other FDWs?

Not now. We introduce necessary APIs for other FDWs, but implementing 
TryShippableJoinPaths()
doesn't seem straightforward.

> 
> If we come up with the right approach we could use it for 1. pushing
> down queries with IN () clause 2. joining a small local table with a
> large foreign table by sending the local table rows down to the
> foreign server.


-- 
Best regards,
Alexander Pyhalov,
Postgres Professional

Attachments:

1-0001-Push-join-with-function-scan-to-remote-server.patch (text/x-diff, 103.6K) download From d997c313daf0031b812d3fca59d338be1a4f2196 Mon Sep 17 00:00:00 2001 From: Alexander Pyhalov <a.pyhalov@postgrespro.ru> Date: Mon, 17 May 2021 19:19:31 +0300 Subject: [PATCH] Push join with function scan to remote server --- contrib/postgres_fdw/deparse.c | 199 ++- .../postgres_fdw/expected/postgres_fdw.out | 1095 +++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 497 +++++++- contrib/postgres_fdw/postgres_fdw.h | 6 + contrib/postgres_fdw/sql/postgres_fdw.sql | 336 +++++ src/backend/optimizer/path/joinpath.c | 11 + src/backend/optimizer/plan/setrefs.c | 1 - src/backend/optimizer/util/relnode.c | 2 + src/include/foreign/fdwapi.h | 1 + 9 files changed, 2035 insertions(+), 113 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index d98bd666818..7f08575ef60 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -151,6 +151,7 @@ static void deparseConst(Const *node, deparse_expr_cxt *context, int showtype); static void deparseParam(Param *node, deparse_expr_cxt *context); static void deparseSubscriptingRef(SubscriptingRef *node, deparse_expr_cxt *context); static void deparseFuncExpr(FuncExpr *node, deparse_expr_cxt *context); +static void deparseFuncColnames(StringInfo buf, int varno, RangeTblEntry *rte, bool qualify_col); static void deparseOpExpr(OpExpr *node, deparse_expr_cxt *context); static void deparseOperatorName(StringInfo buf, Form_pg_operator opform); static void deparseDistinctExpr(DistinctExpr *node, deparse_expr_cxt *context); @@ -1740,13 +1741,54 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, { RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); - /* - * Core code already has some lock on each rel being planned, so we - * can use NoLock here. - */ - Relation rel = table_open(rte->relid, NoLock); + Assert(rte->rtekind == RTE_RELATION || rte->rtekind == RTE_FUNCTION); + if (rte->rtekind == RTE_RELATION) + { + /* + * Core code already has some lock on each rel being planned, so + * we can use NoLock here. + */ + Relation rel = table_open(rte->relid, NoLock); - deparseRelation(buf, rel); + deparseRelation(buf, rel); + + table_close(rel, NoLock); + } + else if (rte->rtekind == RTE_FUNCTION) + { + RangeTblFunction *rtfunc; + deparse_expr_cxt context; + ListCell *lc; + bool first = true; + int n; + + n = list_length(rte->functions); + Assert(n >= 1); + + if (n > 1) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + if (!first) + appendStringInfoString(buf, ", "); + else + first = false; + + rtfunc = (RangeTblFunction *) lfirst(lc); + + context.root = root; + context.foreignrel = foreignrel; + context.scanrel = foreignrel; + context.buf = buf; + context.params_list = params_list; + + deparseExpr((Expr *) rtfunc->funcexpr, &context); + } + + if (n > 1) + appendStringInfoString(buf, ")"); + } /* * Add a unique alias to avoid any conflict in relation names due to @@ -1754,9 +1796,43 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, * join. */ if (use_alias) + { appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, foreignrel->relid); + if (rte->rtekind == RTE_FUNCTION) + { + appendStringInfo(buf, " ("); + deparseFuncColnames(buf, 0, rte, false); + appendStringInfo(buf, ") "); + } + } + } +} - table_close(rel, NoLock); +/* + * Deparse function columns alias list + */ +static void +deparseFuncColnames(StringInfo buf, int varno, RangeTblEntry *rte, bool qualify_col) +{ + bool first = true; + ListCell *lc; + + Assert(rte); + Assert(rte->rtekind == RTE_FUNCTION); + Assert(rte->eref); + + foreach(lc, rte->eref->colnames) + { + char *colname = strVal(lfirst(lc)); + + if (colname[0] == '\0') + continue; + if (!first) + appendStringInfoString(buf, ","); + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); + appendStringInfoString(buf, quote_identifier(colname)); + first = false; } } @@ -2057,7 +2133,7 @@ deparseDirectUpdateSql(StringInfo buf, PlannerInfo *root, appendStringInfoString(buf, "UPDATE "); deparseRelation(buf, rel); - if (foreignrel->reloptkind == RELOPT_JOINREL) + if (IS_JOIN_REL(foreignrel)) appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex); appendStringInfoString(buf, " SET "); @@ -2084,7 +2160,7 @@ deparseDirectUpdateSql(StringInfo buf, PlannerInfo *root, reset_transmission_modes(nestlevel); - if (foreignrel->reloptkind == RELOPT_JOINREL) + if (IS_JOIN_REL(foreignrel)) { List *ignore_conds = NIL; @@ -2100,7 +2176,7 @@ deparseDirectUpdateSql(StringInfo buf, PlannerInfo *root, appendConditions(remote_conds, &context); } - if (foreignrel->reloptkind == RELOPT_JOINREL) + if (IS_JOIN_REL(foreignrel)) deparseExplicitTargetList(returningList, true, retrieved_attrs, &context); else @@ -2164,10 +2240,10 @@ deparseDirectDeleteSql(StringInfo buf, PlannerInfo *root, appendStringInfoString(buf, "DELETE FROM "); deparseRelation(buf, rel); - if (foreignrel->reloptkind == RELOPT_JOINREL) + if (IS_JOIN_REL(foreignrel)) appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex); - if (foreignrel->reloptkind == RELOPT_JOINREL) + if (IS_JOIN_REL(foreignrel)) { List *ignore_conds = NIL; @@ -2183,7 +2259,7 @@ deparseDirectDeleteSql(StringInfo buf, PlannerInfo *root, appendConditions(remote_conds, &context); } - if (foreignrel->reloptkind == RELOPT_JOINREL) + if (IS_JOIN_REL(foreignrel)) deparseExplicitTargetList(returningList, true, retrieved_attrs, &context); else @@ -2407,23 +2483,6 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, /* Required only to be passed down to deparseTargetList(). */ List *retrieved_attrs; - /* - * The lock on the relation will be held by upper callers, so it's - * fine to open it with no lock here. - */ - rel = table_open(rte->relid, NoLock); - - /* - * The local name of the foreign table can not be recognized by the - * foreign server and the table it references on foreign server might - * have different column ordering or different columns than those - * declared locally. Hence we have to deparse whole-row reference as - * ROW(columns referenced locally). Construct this by deparsing a - * "whole row" attribute. - */ - attrs_used = bms_add_member(NULL, - 0 - FirstLowInvalidHeapAttributeNumber); - /* * In case the whole-row reference is under an outer join then it has * to go NULL whenever the rest of the row goes NULL. Deparsing a join @@ -2438,16 +2497,43 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, } appendStringInfoString(buf, "ROW("); - deparseTargetList(buf, rte, varno, rel, false, attrs_used, qualify_col, - &retrieved_attrs); + if (rte->rtekind == RTE_RELATION) + { + /* + * The local name of the foreign table can not be recognized by + * the foreign server and the table it references on foreign + * server might have different column ordering or different + * columns than those declared locally. Hence we have to deparse + * whole-row reference as ROW(columns referenced locally). + * Construct this by deparsing a "whole row" attribute. + */ + attrs_used = bms_add_member(NULL, + 0 - FirstLowInvalidHeapAttributeNumber); + + /* + * The lock on the relation will be held by upper callers, so it's + * fine to open it with no lock here. + */ + rel = table_open(rte->relid, NoLock); + deparseTargetList(buf, rte, varno, rel, false, attrs_used, qualify_col, + &retrieved_attrs); + table_close(rel, NoLock); + bms_free(attrs_used); + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * Function call is translated as-is, function returns the same + * columns in the same order as on local server + */ + deparseFuncColnames(buf, varno, rte, qualify_col); + } appendStringInfoChar(buf, ')'); /* Complete the CASE WHEN statement started above. */ if (qualify_col) appendStringInfoString(buf, " END"); - table_close(rel, NoLock); - bms_free(attrs_used); } else { @@ -2462,29 +2548,40 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, * If it's a column of a foreign table, and it has the column_name FDW * option, use that value. */ - options = GetForeignColumnOptions(rte->relid, varattno); - foreach(lc, options) + if (rte->rtekind == RTE_RELATION) { - DefElem *def = (DefElem *) lfirst(lc); - - if (strcmp(def->defname, "column_name") == 0) + options = GetForeignColumnOptions(rte->relid, varattno); + foreach(lc, options) { - colname = defGetString(def); - break; + DefElem *def = (DefElem *) lfirst(lc); + + if (strcmp(def->defname, "column_name") == 0) + { + colname = defGetString(def); + break; + } } - } - /* - * If it's a column of a regular table or it doesn't have column_name - * FDW option, use attribute name. - */ - if (colname == NULL) - colname = get_attname(rte->relid, varattno, false); + /* + * If it's a column of a regular table or it doesn't have + * column_name FDW option, use attribute name. + */ + if (colname == NULL) + colname = get_attname(rte->relid, varattno, false); - if (qualify_col) - ADD_REL_QUALIFIER(buf, varno); + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); - appendStringInfoString(buf, quote_identifier(colname)); + appendStringInfoString(buf, quote_identifier(colname)); + } + else if (rte->rtekind == RTE_FUNCTION) + { + colname = get_rte_attribute_name(rte, varattno); + + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); + appendStringInfoString(buf, quote_identifier(colname)); + } } } diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index c7b7db80650..bc896914fd1 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -10761,3 +10761,1098 @@ ERROR: invalid value for integer option "fetch_size": 100$%$#$# CREATE FOREIGN TABLE inv_bsz (c1 int ) SERVER loopback OPTIONS (batch_size '100$%$#$#'); ERROR: invalid value for integer option "batch_size": 100$%$#$# +-- =================================================================== +-- test function scan pushdown +-- =================================================================== +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl'); +ALTER FOREIGN TABLE remote_tbl OPTIONS (use_remote_estimate 'true'); +CREATE TABLE base_tbl1 (c int, d text); +CREATE FOREIGN TABLE remote_tbl1 (c int, d text) + SERVER loopback OPTIONS (table_name 'base_tbl1'); +ALTER FOREIGN TABLE remote_tbl1 OPTIONS (use_remote_estimate 'true'); +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO remote_tbl1 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE base_tbl; +ANALYZE base_tbl1; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, n.n + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r2.n FROM (public.base_tbl r1 INNER JOIN unnest('{2,3,4}'::integer[]) r2 (n) ON (((r1.a = r2.n)))) +(4 rows) + +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n +ORDER BY r.a; + a | b | n +---+---+--- + 2 | 4 | 2 + 3 | 6 | 3 + 4 | 8 | 4 +(3 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: n.n, r.a, r.b + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.n, r2.a, r2.b FROM (public.base_tbl r2 INNER JOIN unnest('{2,3,4}'::integer[]) r1 (n) ON (((r1.n = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n +ORDER BY r.a; + n | a | b +---+---+--- + 2 | 2 | 4 + 3 | 3 | 6 + 4 | 4 | 8 +(3 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: r.a, r.b, r1.c, r1.d, n.n + Relations: ((public.remote_tbl r) INNER JOIN (public.remote_tbl1 r1)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r2.c, r2.d, r3.n FROM ((public.base_tbl r1 INNER JOIN public.base_tbl1 r2 ON (((r1.a = r2.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r1.a = r3.n)))) +(4 rows) + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a +ORDER BY r.a; + a | b | c | d | n +---+---+---+-------+--- + 3 | 6 | 3 | text3 | 3 + 4 | 8 | 4 | text4 | 4 +(2 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*,n from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, n.n + Relations: ((public.remote_tbl r) INNER JOIN (public.remote_tbl1 r1)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r3.n FROM ((public.base_tbl r1 INNER JOIN public.base_tbl1 r2 ON (((r1.a = r2.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r1.a = r3.n)) AND ((r3.n > 3)))) +(4 rows) + +SELECT * from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + a | b | c | d | n +---+---+---+-------+--- + 4 | 8 | 4 | text4 | 4 +(1 row) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*, t.n from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), json_each_text('{"a":"text1", "c":"text4"}')) t (n, k, txt) +WHERE r.c = t.n AND r.d = t.txt; + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.c, r.d, t.n + Relations: (public.remote_tbl1 r) INNER JOIN (ROWS FROM(pg_catalog.unnest(), pg_catalog.json_each_text()) t) + Remote SQL: SELECT r1.c, r1.d, r2.n FROM (public.base_tbl1 r1 INNER JOIN ROWS FROM (unnest('{3,4}'::integer[]), json_each_text('{"a":"text1", "c":"text4"}'::json)) r2 (n,k,txt) ON (((r1.c = r2.n)) AND ((r1.d = r2.txt)))) +(4 rows) + +SELECT r.*, t.txt from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), json_each_text('{"a":"text1", "c":"text4"}')) t (n, k, txt) +WHERE r.c = t.n AND r.d = t.txt; + c | d | txt +---+-------+------- + 4 | text4 | text4 +(1 row) + +-- complex types +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx); + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, t.bx + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() t) + Remote SQL: SELECT r1.a, r1.b, r2.bx FROM (public.base_tbl r1 INNER JOIN unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) ON (((r1.a = area(r2.bx))))) +(4 rows) + +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx) +ORDER BY r.a; + a | b | bx +----+----+--------------- + 24 | 48 | (2,3),(-2,-3) +(1 row) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl1 r1 JOIN json_each_text('{"a":"text1", "b":2, "c":"text14"}') ON d = value; + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r1.c, r1.d, json_each_text.key, json_each_text.value + Relations: (public.remote_tbl1 r1) INNER JOIN (pg_catalog.json_each_text()) + Remote SQL: SELECT r1.c, r1.d, r2.key, r2.value FROM (public.base_tbl1 r1 INNER JOIN json_each_text('{"a":"text1", "b":2, "c":"text14"}'::json) r2 (key,value) ON (((r1.d = r2.value)))) +(4 rows) + +SELECT * FROM remote_tbl1 r1 JOIN json_each_text('{"a":"text1", "b":2, "c":"text14"}') ON d = value +ORDER BY r1.c; + c | d | key | value +----+--------+-----+-------- + 1 | text1 | a | text1 + 14 | text14 | c | text14 +(2 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl1 r1 JOIN json_each_text('{"a":"text1", "b":2, "c":"text14"}') AS t(u,v) ON d = v; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r1.c, r1.d, t.u, t.v + Relations: (public.remote_tbl1 r1) INNER JOIN (pg_catalog.json_each_text() t) + Remote SQL: SELECT r1.c, r1.d, r2.u, r2.v FROM (public.base_tbl1 r1 INNER JOIN json_each_text('{"a":"text1", "b":2, "c":"text14"}'::json) r2 (u,v) ON (((r1.d = r2.v)))) +(4 rows) + +SELECT * FROM remote_tbl1 r1 JOIN json_each_text('{"a":"text1", "b":2, "c":"text14"}') AS t(u,v) ON d = v +ORDER BY r1.c; + c | d | u | v +----+--------+---+-------- + 1 | text1 | a | text1 + 14 | text14 | c | text14 +(2 rows) + +-- DML +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + -> Foreign Update + Remote SQL: UPDATE public.base_tbl r1 SET b = 5 FROM unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) WHERE ((r1.a = area(r2.bx))) RETURNING r1.a, r1.b +(4 rows) + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + a | b +----+--- + 24 | 5 +(1 row) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + Remote SQL: UPDATE public.base_tbl SET b = $2 WHERE ctid = $1 RETURNING a, b + -> Foreign Scan + Output: CASE WHEN (random() >= '0'::double precision) THEN 5 ELSE 0 END, r.ctid, r.*, t.* + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() t) + Remote SQL: SELECT r1.ctid, CASE WHEN (r1.*)::text IS NOT NULL THEN ROW(r1.a, r1.b) END, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2.bx) END FROM (public.base_tbl r1 INNER JOIN unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) ON (((r1.a = area(r2.bx))))) FOR UPDATE OF r1 + -> Hash Join + Output: r.ctid, r.*, t.* + Hash Cond: ((r.a)::double precision = area(t.bx)) + -> Foreign Scan on public.remote_tbl r + Output: r.ctid, r.*, r.a + Remote SQL: SELECT a, b, ctid FROM public.base_tbl FOR UPDATE + -> Hash + Output: t.*, t.bx + -> Function Scan on pg_catalog.unnest t + Output: t.*, t.bx + Function Call: unnest('{(2,3),(-2,-3)}'::box[]) +(18 rows) + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + a | b +----+--- + 24 | 5 +(1 row) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Update on public.remote_tbl r + Output: r.a, r.b + -> Foreign Update + Remote SQL: UPDATE public.base_tbl r1 SET b = 5 FROM ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) WHERE ((r1.a >= r2.l)) AND ((r1.a <= area(r2.bx))) RETURNING r1.a, r1.b +(4 rows) + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + a | b +----+--- + 10 | 5 + 11 | 5 + 12 | 5 + 13 | 5 + 14 | 5 + 15 | 5 + 16 | 5 + 17 | 5 + 18 | 5 + 19 | 5 + 20 | 5 + 21 | 5 + 22 | 5 + 23 | 5 + 25 | 5 + 26 | 5 + 27 | 5 + 28 | 5 + 24 | 5 +(19 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + Remote SQL: UPDATE public.base_tbl SET b = $2 WHERE ctid = $1 RETURNING a, b + -> Foreign Scan + Output: CASE WHEN (random() >= '0'::double precision) THEN 5 ELSE 0 END, r.ctid, r.*, t.* + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM(pg_catalog.unnest(), pg_catalog.unnest()) t) + Remote SQL: SELECT r1.ctid, CASE WHEN (r1.*)::text IS NOT NULL THEN ROW(r1.a, r1.b) END, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2.l,r2.bx) END FROM (public.base_tbl r1 INNER JOIN ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) ON (((r1.a >= r2.l)) AND ((r1.a <= area(r2.bx))))) FOR UPDATE OF r1 + -> Nested Loop + Output: r.ctid, r.*, t.* + Join Filter: ((r.a >= t.l) AND ((r.a)::double precision <= area(t.bx))) + -> Foreign Scan on public.remote_tbl r + Output: r.ctid, r.*, r.a + Remote SQL: SELECT a, b, ctid FROM public.base_tbl FOR UPDATE + -> Function Scan on t + Output: t.*, t.l, t.bx + Function Call: unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[]) +(16 rows) + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + a | b +----+--- + 10 | 5 + 11 | 5 + 12 | 5 + 13 | 5 + 14 | 5 + 15 | 5 + 16 | 5 + 17 | 5 + 18 | 5 + 19 | 5 + 20 | 5 + 21 | 5 + 22 | 5 + 23 | 5 + 25 | 5 + 26 | 5 + 27 | 5 + 28 | 5 + 24 | 5 +(19 rows) + +-- Test that local functions are not pushed down +CREATE OR REPLACE FUNCTION f(INTEGER) +RETURNS SETOF INTEGER +LANGUAGE sql AS 'select generate_series(1,$1);' IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, f(10) n +WHERE r.a = n; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: r.a, r.b, (generate_series(1, 10)) + Hash Cond: (r.a = (generate_series(1, 10))) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a, b FROM public.base_tbl + -> Hash + Output: (generate_series(1, 10)) + -> ProjectSet + Output: generate_series(1, 10) + -> Result +(11 rows) + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a AND n > 3; + a | b | c | d | n +---+---+---+-------+--- + 4 | 8 | 4 | text4 | 4 +(1 row) + +-- Test joins with append relations +SET enable_partitionwise_join=on; +-- Partitioned tables and function scan pushdown +CREATE TABLE distr1(a int, b int) PARTITION BY HASH(a); +CREATE TABLE distr1_part_1 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 4, REMAINDER 0); +CREATE TABLE distr1_base_2 (a int, b int); +CREATE FOREIGN TABLE distr1_part_2 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 4, REMAINDER 1) + SERVER loopback OPTIONS (table_name 'distr1_base_2', use_remote_estimate 'true'); +CREATE TABLE distr1_base_3 (a int, b int); +CREATE FOREIGN TABLE distr1_part_3 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 4, REMAINDER 2) + SERVER loopback2 OPTIONS (table_name 'distr1_base_3', use_remote_estimate 'true'); +CREATE TABLE distr1_base_4 (a int, b int); +CREATE FOREIGN TABLE distr1_part_4 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 4, REMAINDER 3) + SERVER loopback OPTIONS (table_name 'distr1_base_4', use_remote_estimate 'true'); +CREATE TABLE distr2(c int, d text) PARTITION BY HASH(c); +CREATE TABLE distr2_part_1 PARTITION OF distr2 FOR VALUES WITH (MODULUS 4, REMAINDER 0); +CREATE TABLE distr2_base_2 (c int, d text); +CREATE FOREIGN TABLE distr2_part_2 PARTITION OF distr2 FOR VALUES WITH ( MODULUS 4, REMAINDER 1) + SERVER loopback OPTIONS (table_name 'distr2_base_2', use_remote_estimate 'true'); +CREATE TABLE distr2_base_3 (c int, d text); +CREATE FOREIGN TABLE distr2_part_3 PARTITION OF distr2 FOR VALUES WITH ( MODULUS 4, REMAINDER 2) + SERVER loopback2 OPTIONS (table_name 'distr2_base_3', use_remote_estimate 'true'); +CREATE TABLE distr2_base_4 (c int, d text); +CREATE FOREIGN TABLE distr2_part_4 PARTITION OF distr2 FOR VALUES WITH ( MODULUS 4, REMAINDER 3) + SERVER loopback OPTIONS (table_name 'distr2_base_4', use_remote_estimate 'true'); +INSERT INTO distr1 SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO distr2 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE distr1; +ANALYZE distr1_part_1; +ANALYZE distr1_base_2; +ANALYZE distr1_base_3; +ANALYZE distr1_base_4; +ANALYZE distr2; +ANALYZE distr2_base_2; +ANALYZE distr2_base_3; +ANALYZE distr2_base_4; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM distr1 d, unnest(array[2,3,4,5]) n WHERE d.a = n; + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------- + Append + -> Hash Join + Output: d_1.a, d_1.b, n.n + Hash Cond: (d_1.a = n.n) + -> Seq Scan on public.distr1_part_1 d_1 + Output: d_1.a, d_1.b + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4,5}'::integer[]) + -> Foreign Scan + Output: d_2.a, d_2.b, n.n + Relations: (public.distr1_part_2 d_2) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r4.a, r4.b, r2.n FROM (public.distr1_base_2 r4 INNER JOIN unnest('{2,3,4,5}'::integer[]) r2 (n) ON (((r4.a = r2.n)))) + -> Foreign Scan + Output: d_3.a, d_3.b, n.n + Relations: (public.distr1_part_3 d_3) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r5.a, r5.b, r2.n FROM (public.distr1_base_3 r5 INNER JOIN unnest('{2,3,4,5}'::integer[]) r2 (n) ON (((r5.a = r2.n)))) + -> Foreign Scan + Output: d_4.a, d_4.b, n.n + Relations: (public.distr1_part_4 d_4) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r6.a, r6.b, r2.n FROM (public.distr1_base_4 r6 INNER JOIN unnest('{2,3,4,5}'::integer[]) r2 (n) ON (((r6.a = r2.n)))) +(23 rows) + +SELECT * FROM distr1 d, unnest(array[2,3,4,5]) n WHERE d.a = n +ORDER BY d.a; + a | b | n +---+----+--- + 2 | 4 | 2 + 3 | 6 | 3 + 4 | 8 | 4 + 5 | 10 | 5 +(4 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4,5]) n, distr1 d WHERE d.a = n; + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------- + Append + -> Hash Join + Output: n.n, d_1.a, d_1.b + Hash Cond: (d_1.a = n.n) + -> Seq Scan on public.distr1_part_1 d_1 + Output: d_1.a, d_1.b + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4,5}'::integer[]) + -> Foreign Scan + Output: n.n, d_2.a, d_2.b + Relations: (public.distr1_part_2 d_2) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.n, r4.a, r4.b FROM (public.distr1_base_2 r4 INNER JOIN unnest('{2,3,4,5}'::integer[]) r1 (n) ON (((r1.n = r4.a)))) + -> Foreign Scan + Output: n.n, d_3.a, d_3.b + Relations: (public.distr1_part_3 d_3) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.n, r5.a, r5.b FROM (public.distr1_base_3 r5 INNER JOIN unnest('{2,3,4,5}'::integer[]) r1 (n) ON (((r1.n = r5.a)))) + -> Foreign Scan + Output: n.n, d_4.a, d_4.b + Relations: (public.distr1_part_4 d_4) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.n, r6.a, r6.b FROM (public.distr1_base_4 r6 INNER JOIN unnest('{2,3,4,5}'::integer[]) r1 (n) ON (((r1.n = r6.a)))) +(23 rows) + +SELECT * FROM unnest(array[2,3,4,5]) n, distr1 d WHERE d.a = n +ORDER BY d.a; + n | a | b +---+---+---- + 2 | 2 | 4 + 3 | 3 | 6 + 4 | 4 | 8 + 5 | 5 | 10 +(4 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM distr1 d1, distr2 d2, unnest(array[3,4]) n +WHERE d1.a = n AND d2.c = d1.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Append + -> Hash Join + Output: d1_1.a, d1_1.b, d2_1.c, d2_1.d, n.n + Hash Cond: (d1_1.a = n.n) + -> Hash Join + Output: d1_1.a, d1_1.b, d2_1.c, d2_1.d + Hash Cond: (d1_1.a = d2_1.c) + -> Seq Scan on public.distr1_part_1 d1_1 + Output: d1_1.a, d1_1.b + -> Hash + Output: d2_1.c, d2_1.d + -> Seq Scan on public.distr2_part_1 d2_1 + Output: d2_1.c, d2_1.d + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{3,4}'::integer[]) + -> Foreign Scan + Output: d1_2.a, d1_2.b, d2_2.c, d2_2.d, n.n + Relations: ((public.distr1_part_2 d1_2) INNER JOIN (public.distr2_part_2 d2_2)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r5.a, r5.b, r9.c, r9.d, r3.n FROM ((public.distr1_base_2 r5 INNER JOIN public.distr2_base_2 r9 ON (((r5.a = r9.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r5.a = r3.n)))) + -> Foreign Scan + Output: d1_3.a, d1_3.b, d2_3.c, d2_3.d, n.n + Relations: ((public.distr1_part_3 d1_3) INNER JOIN (public.distr2_part_3 d2_3)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r6.a, r6.b, r10.c, r10.d, r3.n FROM ((public.distr1_base_3 r6 INNER JOIN public.distr2_base_3 r10 ON (((r6.a = r10.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r6.a = r3.n)))) + -> Foreign Scan + Output: d1_4.a, d1_4.b, d2_4.c, d2_4.d, n.n + Relations: ((public.distr1_part_4 d1_4) INNER JOIN (public.distr2_part_4 d2_4)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r7.a, r7.b, r11.c, r11.d, r3.n FROM ((public.distr1_base_4 r7 INNER JOIN public.distr2_base_4 r11 ON (((r7.a = r11.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r7.a = r3.n)))) +(30 rows) + +SELECT * FROM distr1 d1, distr2 d2, unnest(array[3,4]) n +WHERE d1.a = n AND d2.c = d1.a +ORDER BY d1.a; + a | b | c | d | n +---+---+---+-------+--- + 3 | 6 | 3 | text3 | 3 + 4 | 8 | 4 | text4 | 4 +(2 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * from distr1 d1, distr2 d2, unnest(array[3,4]) n +WHERE d1.a = n AND d2.c = d1.a and n > 3; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Append + -> Hash Join + Output: d1_1.a, d1_1.b, d2_1.c, d2_1.d, n.n + Hash Cond: (d1_1.a = n.n) + -> Hash Join + Output: d1_1.a, d1_1.b, d2_1.c, d2_1.d + Hash Cond: (d1_1.a = d2_1.c) + -> Seq Scan on public.distr1_part_1 d1_1 + Output: d1_1.a, d1_1.b + -> Hash + Output: d2_1.c, d2_1.d + -> Seq Scan on public.distr2_part_1 d2_1 + Output: d2_1.c, d2_1.d + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{3,4}'::integer[]) + Filter: (n.n > 3) + -> Foreign Scan + Output: d1_2.a, d1_2.b, d2_2.c, d2_2.d, n.n + Relations: ((public.distr1_part_2 d1_2) INNER JOIN (public.distr2_part_2 d2_2)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r5.a, r5.b, r9.c, r9.d, r3.n FROM ((public.distr1_base_2 r5 INNER JOIN public.distr2_base_2 r9 ON (((r5.a = r9.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r5.a = r3.n)) AND ((r3.n > 3)))) + -> Foreign Scan + Output: d1_3.a, d1_3.b, d2_3.c, d2_3.d, n.n + Relations: ((public.distr1_part_3 d1_3) INNER JOIN (public.distr2_part_3 d2_3)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r6.a, r6.b, r10.c, r10.d, r3.n FROM ((public.distr1_base_3 r6 INNER JOIN public.distr2_base_3 r10 ON (((r6.a = r10.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r6.a = r3.n)) AND ((r3.n > 3)))) + -> Foreign Scan + Output: d1_4.a, d1_4.b, d2_4.c, d2_4.d, n.n + Relations: ((public.distr1_part_4 d1_4) INNER JOIN (public.distr2_part_4 d2_4)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r7.a, r7.b, r11.c, r11.d, r3.n FROM ((public.distr1_base_4 r7 INNER JOIN public.distr2_base_4 r11 ON (((r7.a = r11.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r7.a = r3.n)) AND ((r3.n > 3)))) +(31 rows) + +SELECT * from distr1 d1, distr2 d2, unnest(array[3,4]) n +WHERE d1.a = n AND d2.c = d1.a and n > 3 +ORDER BY d1.a; + a | b | c | d | n +---+---+---+-------+--- + 4 | 8 | 4 | text4 | 4 +(1 row) + +-- Direct update with returning +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE distr1 d1 SET b=t.l FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.distr1 d1 + Output: d1_1.a, d1_1.b + Update on public.distr1_part_1 d1_1 + Foreign Update on public.distr1_part_2 d1_2 + Foreign Update on public.distr1_part_3 d1_3 + Foreign Update on public.distr1_part_4 d1_4 + -> Result + Output: t.l, t.*, d1.tableoid, d1.ctid, (NULL::record) + -> Append + -> Nested Loop + Output: d1_1.tableoid, d1_1.ctid, NULL::record, t.l, t.* + Join Filter: ((d1_1.a >= t.l) AND ((d1_1.a)::double precision <= area(t.bx))) + -> Function Scan on t + Output: t.l, t.*, t.bx + Function Call: unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[]) + -> Materialize + Output: d1_1.a, d1_1.tableoid, d1_1.ctid, NULL::record + -> Seq Scan on public.distr1_part_1 d1_1 + Output: d1_1.a, d1_1.tableoid, d1_1.ctid, NULL::record + -> Foreign Update + Remote SQL: UPDATE public.distr1_base_2 r4 SET b = r2.l FROM ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) WHERE ((r4.a >= r2.l)) AND ((r4.a <= area(r2.bx))) RETURNING CASE WHEN (r4.*)::text IS NOT NULL THEN 17254 END, r4.a, r4.b + -> Foreign Update + Remote SQL: UPDATE public.distr1_base_3 r5 SET b = r2.l FROM ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) WHERE ((r5.a >= r2.l)) AND ((r5.a <= area(r2.bx))) RETURNING CASE WHEN (r5.*)::text IS NOT NULL THEN 17260 END, r5.a, r5.b + -> Foreign Update + Remote SQL: UPDATE public.distr1_base_4 r6 SET b = r2.l FROM ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) WHERE ((r6.a >= r2.l)) AND ((r6.a <= area(r2.bx))) RETURNING CASE WHEN (r6.*)::text IS NOT NULL THEN 17266 END, r6.a, r6.b +(25 rows) + +UPDATE distr1 d1 SET b=t.l FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b; + a | b +----+---- + 12 | 10 + 14 | 10 + 16 | 10 + 17 | 10 + 26 | 10 + 28 | 10 + 11 | 10 + 19 | 10 + 20 | 10 + 21 | 10 + 13 | 10 + 18 | 10 + 23 | 10 + 25 | 10 + 27 | 10 + 10 | 10 + 15 | 10 + 22 | 10 + 24 | 10 +(19 rows) + +-- Direct update with returning tableoid +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE distr1 d1 SET b=t.l FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b,tableoid; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.distr1 d1 + Output: d1_1.a, d1_1.b, d1_1.tableoid + Update on public.distr1_part_1 d1_1 + Foreign Update on public.distr1_part_2 d1_2 + Foreign Update on public.distr1_part_3 d1_3 + Foreign Update on public.distr1_part_4 d1_4 + -> Result + Output: t.l, t.*, d1.tableoid, d1.ctid, (NULL::record) + -> Append + -> Nested Loop + Output: d1_1.tableoid, d1_1.ctid, NULL::record, t.l, t.* + Join Filter: ((d1_1.a >= t.l) AND ((d1_1.a)::double precision <= area(t.bx))) + -> Function Scan on t + Output: t.l, t.*, t.bx + Function Call: unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[]) + -> Materialize + Output: d1_1.a, d1_1.tableoid, d1_1.ctid, NULL::record + -> Seq Scan on public.distr1_part_1 d1_1 + Output: d1_1.a, d1_1.tableoid, d1_1.ctid, NULL::record + -> Foreign Update + Remote SQL: UPDATE public.distr1_base_2 r4 SET b = r2.l FROM ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) WHERE ((r4.a >= r2.l)) AND ((r4.a <= area(r2.bx))) RETURNING CASE WHEN (r4.*)::text IS NOT NULL THEN 17254 END, r4.a, r4.b + -> Foreign Update + Remote SQL: UPDATE public.distr1_base_3 r5 SET b = r2.l FROM ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) WHERE ((r5.a >= r2.l)) AND ((r5.a <= area(r2.bx))) RETURNING CASE WHEN (r5.*)::text IS NOT NULL THEN 17260 END, r5.a, r5.b + -> Foreign Update + Remote SQL: UPDATE public.distr1_base_4 r6 SET b = r2.l FROM ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) WHERE ((r6.a >= r2.l)) AND ((r6.a <= area(r2.bx))) RETURNING CASE WHEN (r6.*)::text IS NOT NULL THEN 17266 END, r6.a, r6.b +(25 rows) + +UPDATE distr1 d1 SET b=t.l FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b,tableoid; + a | b | tableoid +----+----+---------- + 12 | 10 | 17248 + 14 | 10 | 17248 + 16 | 10 | 17248 + 17 | 10 | 17248 + 26 | 10 | 17248 + 28 | 10 | 17248 + 11 | 10 | 17254 + 19 | 10 | 17254 + 20 | 10 | 17254 + 21 | 10 | 17254 + 13 | 10 | 17260 + 18 | 10 | 17260 + 23 | 10 | 17260 + 25 | 10 | 17260 + 27 | 10 | 17260 + 10 | 10 | 17266 + 15 | 10 | 17266 + 22 | 10 | 17266 + 24 | 10 | 17266 +(19 rows) + +-- Indirect update with returning +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE distr1 d1 SET b=CASE WHEN random()>=0 THEN t.l ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.distr1 d1 + Output: d1_1.a, d1_1.b + Update on public.distr1_part_1 d1_1 + Foreign Update on public.distr1_part_2 d1_2 + Remote SQL: UPDATE public.distr1_base_2 SET b = $2 WHERE ctid = $1 RETURNING a, b + Foreign Update on public.distr1_part_3 d1_3 + Remote SQL: UPDATE public.distr1_base_3 SET b = $2 WHERE ctid = $1 RETURNING a, b + Foreign Update on public.distr1_part_4 d1_4 + Remote SQL: UPDATE public.distr1_base_4 SET b = $2 WHERE ctid = $1 RETURNING a, b + -> Result + Output: CASE WHEN (random() >= '0'::double precision) THEN t.l ELSE 0 END, t.*, d1.tableoid, d1.ctid, (NULL::record) + -> Append + -> Nested Loop + Output: d1_1.tableoid, d1_1.ctid, NULL::record, t.l, t.* + Join Filter: ((d1_1.a >= t.l) AND ((d1_1.a)::double precision <= area(t.bx))) + -> Function Scan on t + Output: t.l, t.*, t.bx + Function Call: unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[]) + -> Materialize + Output: d1_1.a, d1_1.tableoid, d1_1.ctid, NULL::record + -> Seq Scan on public.distr1_part_1 d1_1 + Output: d1_1.a, d1_1.tableoid, d1_1.ctid, NULL::record + -> Foreign Scan + Output: d1_2.tableoid, d1_2.ctid, d1_2.*, t.l, t.* + Relations: (public.distr1_part_2 d1_2) INNER JOIN (ROWS FROM(pg_catalog.unnest(), pg_catalog.unnest()) t) + Remote SQL: SELECT CASE WHEN (r4.*)::text IS NOT NULL THEN 17254 END, r4.ctid, CASE WHEN (r4.*)::text IS NOT NULL THEN ROW(r4.a, r4.b) END, r2.l, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2.l,r2.bx) END FROM (public.distr1_base_2 r4 INNER JOIN ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) ON (((r4.a >= r2.l)) AND ((r4.a <= area(r2.bx))))) FOR UPDATE OF r4 + -> Nested Loop + Output: d1_2.tableoid, d1_2.ctid, d1_2.*, t.l, t.* + Join Filter: ((d1_2.a >= t.l) AND ((d1_2.a)::double precision <= area(t.bx))) + -> Foreign Scan on public.distr1_part_2 d1_2 + Output: d1_2.a, d1_2.tableoid, d1_2.ctid, d1_2.* + Remote SQL: SELECT a, b, ctid FROM public.distr1_base_2 FOR UPDATE + -> Function Scan on t + Output: t.l, t.*, t.bx + Function Call: unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[]) + -> Foreign Scan + Output: d1_3.tableoid, d1_3.ctid, d1_3.*, t.l, t.* + Relations: (public.distr1_part_3 d1_3) INNER JOIN (ROWS FROM(pg_catalog.unnest(), pg_catalog.unnest()) t) + Remote SQL: SELECT CASE WHEN (r5.*)::text IS NOT NULL THEN 17260 END, r5.ctid, CASE WHEN (r5.*)::text IS NOT NULL THEN ROW(r5.a, r5.b) END, r2.l, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2.l,r2.bx) END FROM (public.distr1_base_3 r5 INNER JOIN ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) ON (((r5.a >= r2.l)) AND ((r5.a <= area(r2.bx))))) FOR UPDATE OF r5 + -> Nested Loop + Output: d1_3.tableoid, d1_3.ctid, d1_3.*, t.l, t.* + Join Filter: ((d1_3.a >= t.l) AND ((d1_3.a)::double precision <= area(t.bx))) + -> Foreign Scan on public.distr1_part_3 d1_3 + Output: d1_3.a, d1_3.tableoid, d1_3.ctid, d1_3.* + Remote SQL: SELECT a, b, ctid FROM public.distr1_base_3 FOR UPDATE + -> Function Scan on t + Output: t.l, t.*, t.bx + Function Call: unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[]) + -> Foreign Scan + Output: d1_4.tableoid, d1_4.ctid, d1_4.*, t.l, t.* + Relations: (public.distr1_part_4 d1_4) INNER JOIN (ROWS FROM(pg_catalog.unnest(), pg_catalog.unnest()) t) + Remote SQL: SELECT CASE WHEN (r6.*)::text IS NOT NULL THEN 17266 END, r6.ctid, CASE WHEN (r6.*)::text IS NOT NULL THEN ROW(r6.a, r6.b) END, r2.l, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2.l,r2.bx) END FROM (public.distr1_base_4 r6 INNER JOIN ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) ON (((r6.a >= r2.l)) AND ((r6.a <= area(r2.bx))))) FOR UPDATE OF r6 + -> Nested Loop + Output: d1_4.tableoid, d1_4.ctid, d1_4.*, t.l, t.* + Join Filter: ((d1_4.a >= t.l) AND ((d1_4.a)::double precision <= area(t.bx))) + -> Foreign Scan on public.distr1_part_4 d1_4 + Output: d1_4.a, d1_4.tableoid, d1_4.ctid, d1_4.* + Remote SQL: SELECT a, b, ctid FROM public.distr1_base_4 FOR UPDATE + -> Function Scan on t + Output: t.l, t.*, t.bx + Function Call: unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[]) +(61 rows) + +UPDATE distr1 d1 SET b=CASE WHEN random()>=0 THEN t.l ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b; + a | b +----+---- + 12 | 10 + 14 | 10 + 16 | 10 + 17 | 10 + 26 | 10 + 28 | 10 + 11 | 10 + 19 | 10 + 20 | 10 + 21 | 10 + 13 | 10 + 18 | 10 + 23 | 10 + 25 | 10 + 27 | 10 + 10 | 10 + 15 | 10 + 22 | 10 + 24 | 10 +(19 rows) + +DROP TABLE distr1, distr2, distr1_base_2, distr2_base_2, distr1_base_3, distr2_base_3, distr1_base_4, distr2_base_4; +-- Test pushdown of several function scans +CREATE TABLE distr1(a int, b int) PARTITION BY HASH(a); +CREATE TABLE distr1_part_1 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 2, REMAINDER 0); +CREATE TABLE distr1_base_2 (a int, b int); +CREATE FOREIGN TABLE distr1_part_2 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 2, REMAINDER 1) + SERVER loopback OPTIONS (table_name 'distr1_base_2', use_remote_estimate 'true'); +CREATE TABLE distr2(c int, d text) PARTITION BY HASH(c); +CREATE TABLE distr2_part_1 PARTITION OF distr2 FOR VALUES WITH (MODULUS 2, REMAINDER 0); +CREATE TABLE distr2_base_2 (c int, d text); +CREATE FOREIGN TABLE distr2_part_2 PARTITION OF distr2 FOR VALUES WITH ( MODULUS 2, REMAINDER 1) + SERVER loopback OPTIONS (table_name 'distr2_base_2', use_remote_estimate 'true'); +INSERT INTO distr1 SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO distr2 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE; +-- Make local function scan not so attractive +ALTER SERVER loopback OPTIONS (ADD fdw_tuple_cost '1000'); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * from distr1 d1, distr1 d2, unnest(array[3,4]) n, unnest(array[3,4]) g +WHERE d1.a = n AND d2.a = d1.a and g = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Append + -> Hash Join + Output: d1_1.a, d1_1.b, d2_1.a, d2_1.b, n.n, g.g + Hash Cond: (d1_1.a = g.g) + -> Hash Join + Output: d1_1.a, d1_1.b, d2_1.a, d2_1.b, n.n + Hash Cond: (d1_1.a = n.n) + -> Hash Join + Output: d1_1.a, d1_1.b, d2_1.a, d2_1.b + Hash Cond: (d1_1.a = d2_1.a) + -> Seq Scan on public.distr1_part_1 d1_1 + Output: d1_1.a, d1_1.b + -> Hash + Output: d2_1.a, d2_1.b + -> Seq Scan on public.distr1_part_1 d2_1 + Output: d2_1.a, d2_1.b + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{3,4}'::integer[]) + -> Hash + Output: g.g + -> Function Scan on pg_catalog.unnest g + Output: g.g + Function Call: unnest('{3,4}'::integer[]) + -> Foreign Scan + Output: d1_2.a, d1_2.b, d2_2.a, d2_2.b, n.n, g.g + Relations: (((public.distr1_part_2 d1_2) INNER JOIN (public.distr1_part_2 d2_2)) INNER JOIN (pg_catalog.unnest() n)) INNER JOIN (pg_catalog.unnest() g) + Remote SQL: SELECT r6.a, r6.b, r8.a, r8.b, r3.n, r4.g FROM (((public.distr1_base_2 r6 INNER JOIN public.distr1_base_2 r8 ON (((r6.a = r8.a)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r6.a = r3.n)))) INNER JOIN unnest('{3,4}'::integer[]) r4 (g) ON (((r6.a = r4.g)))) +(30 rows) + +SELECT * from distr1 d1, distr2 d2, unnest(array[3,4]) n, generate_series(1,10000) g +WHERE d1.a = n AND d2.c = d1.a and g = d1.a +ORDER BY d1.a; + a | b | c | d | n | g +---+---+---+-------+---+--- + 3 | 6 | 3 | text3 | 3 | 3 + 4 | 8 | 4 | text4 | 4 | 4 +(2 rows) + +ALTER SERVER loopback OPTIONS (DROP fdw_tuple_cost); +DROP TABLE distr1, distr2, distr1_base_2, distr2_base_2; +-- Test inheritance chain and function scan pushdown +CREATE TABLE distr1(a int, b int); +CREATE TABLE distr1_loc (a int, b int) INHERITS (distr1); +NOTICE: merging column "a" with inherited definition +NOTICE: merging column "b" with inherited definition +CREATE TABLE distr1_base (a int, b int, c text); +CREATE FOREIGN TABLE distr1_remote (a int, b int, c text) INHERITS (distr1) + SERVER loopback OPTIONS (table_name 'distr1_base', use_remote_estimate 'true'); +NOTICE: merging column "a" with inherited definition +NOTICE: merging column "b" with inherited definition +CREATE TABLE distr2(c int, d text); +CREATE TABLE distr2_loc (c int, d text) INHERITS (distr2); +NOTICE: merging column "c" with inherited definition +NOTICE: merging column "d" with inherited definition +CREATE TABLE distr2_base (c int, d text, e int); +CREATE FOREIGN TABLE distr2_remote (c int, d text, e int) INHERITS (distr2) + SERVER loopback OPTIONS (table_name 'distr2_base', use_remote_estimate 'true'); +NOTICE: merging column "c" with inherited definition +NOTICE: merging column "d" with inherited definition +INSERT INTO distr1_loc SELECT g, g*2 from generate_series(1,100) g; +INSERT INTO distr1_base SELECT g, g*2, 'text'|| g from generate_series(200,20000) g; +INSERT INTO distr2_loc SELECT g, 'text'|| g from generate_series(1,100) g; +INSERT INTO distr2_base SELECT g, 'text'|| g, g*2 from generate_series(200,20000) g; +ANALYZE distr1, distr1_loc, distr1_base; +ANALYZE distr2, distr2_loc, distr2_base; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM distr1 d, unnest(array[2,3,4,5]) n WHERE d.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------- + Append + -> Hash Join + Output: d_1.a, d_1.b, n.n + Hash Cond: (n.n = d_1.a) + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4,5}'::integer[]) + -> Hash + Output: d_1.a, d_1.b + -> Seq Scan on public.distr1 d_1 + Output: d_1.a, d_1.b + -> Hash Join + Output: d_2.a, d_2.b, n.n + Hash Cond: (d_2.a = n.n) + -> Seq Scan on public.distr1_loc d_2 + Output: d_2.a, d_2.b + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4,5}'::integer[]) + -> Foreign Scan + Output: d_3.a, d_3.b, n.n + Relations: (public.distr1_remote d_3) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r5.a, r5.b, r2.n FROM (public.distr1_base r5 INNER JOIN unnest('{2,3,4,5}'::integer[]) r2 (n) ON (((r5.a = r2.n)))) +(25 rows) + +SELECT * FROM distr1 d, unnest(array[2,3,4,5]) n WHERE d.a = n +ORDER BY d.a; + a | b | n +---+----+--- + 2 | 4 | 2 + 3 | 6 | 3 + 4 | 8 | 4 + 5 | 10 | 5 +(4 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4,5]) n, distr1 d WHERE d.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------- + Append + -> Hash Join + Output: n.n, d_1.a, d_1.b + Hash Cond: (n.n = d_1.a) + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4,5}'::integer[]) + -> Hash + Output: d_1.a, d_1.b + -> Seq Scan on public.distr1 d_1 + Output: d_1.a, d_1.b + -> Hash Join + Output: n.n, d_2.a, d_2.b + Hash Cond: (d_2.a = n.n) + -> Seq Scan on public.distr1_loc d_2 + Output: d_2.a, d_2.b + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4,5}'::integer[]) + -> Foreign Scan + Output: n.n, d_3.a, d_3.b + Relations: (public.distr1_remote d_3) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.n, r5.a, r5.b FROM (public.distr1_base r5 INNER JOIN unnest('{2,3,4,5}'::integer[]) r1 (n) ON (((r1.n = r5.a)))) +(25 rows) + +SELECT * FROM unnest(array[2,3,4,5]) n, distr1 d WHERE d.a = n +ORDER BY d.a; + n | a | b +---+---+---- + 2 | 2 | 4 + 3 | 3 | 6 + 4 | 4 | 8 + 5 | 5 | 10 +(4 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM distr1 d1, distr2 d2, unnest(array[300,400]) n +WHERE d1.a = n AND d2.c = d1.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: d1.a, d1.b, d2.c, d2.d, n.n + Hash Cond: (d2.c = d1.a) + -> Append + -> Seq Scan on public.distr2 d2_1 + Output: d2_1.c, d2_1.d + -> Seq Scan on public.distr2_loc d2_2 + Output: d2_2.c, d2_2.d + -> Foreign Scan on public.distr2_remote d2_3 + Output: d2_3.c, d2_3.d + Remote SQL: SELECT c, d FROM public.distr2_base + -> Hash + Output: d1.a, d1.b, n.n + -> Append + -> Nested Loop + Output: d1_1.a, d1_1.b, n.n + Join Filter: (d1_1.a = n.n) + -> Seq Scan on public.distr1 d1_1 + Output: d1_1.a, d1_1.b + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{300,400}'::integer[]) + -> Hash Join + Output: d1_2.a, d1_2.b, n.n + Hash Cond: (d1_2.a = n.n) + -> Seq Scan on public.distr1_loc d1_2 + Output: d1_2.a, d1_2.b + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{300,400}'::integer[]) + -> Foreign Scan + Output: d1_3.a, d1_3.b, n.n + Relations: (public.distr1_remote d1_3) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r6.a, r6.b, r3.n FROM (public.distr1_base r6 INNER JOIN unnest('{300,400}'::integer[]) r3 (n) ON (((r6.a = r3.n)))) +(36 rows) + +SELECT * FROM distr1 d1, distr2 d2, unnest(array[300,400]) n +WHERE d1.a = n AND d2.c = d1.a +ORDER BY d1.a; + a | b | c | d | n +-----+-----+-----+---------+----- + 300 | 600 | 300 | text300 | 300 + 400 | 800 | 400 | text400 | 400 +(2 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * from distr1 d1, distr2 d2, unnest(array[300,400]) n +WHERE d1.a = n AND d2.c = d1.a and n > 3; + QUERY PLAN +----------------------------------------------------------------------------------------------- + Nested Loop + Output: d1.a, d1.b, d2.c, d2.d, n.n + -> Nested Loop + Output: d1.a, d1.b, n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{300,400}'::integer[]) + Filter: (n.n > 3) + -> Append + -> Seq Scan on public.distr1 d1_1 + Output: d1_1.a, d1_1.b + Filter: (n.n = d1_1.a) + -> Seq Scan on public.distr1_loc d1_2 + Output: d1_2.a, d1_2.b + Filter: (n.n = d1_2.a) + -> Foreign Scan on public.distr1_remote d1_3 + Output: d1_3.a, d1_3.b + Remote SQL: SELECT a, b FROM public.distr1_base WHERE (($1::integer = a)) + -> Append + -> Seq Scan on public.distr2 d2_1 + Output: d2_1.c, d2_1.d + Filter: (d1.a = d2_1.c) + -> Seq Scan on public.distr2_loc d2_2 + Output: d2_2.c, d2_2.d + Filter: (d1.a = d2_2.c) + -> Foreign Scan on public.distr2_remote d2_3 + Output: d2_3.c, d2_3.d + Remote SQL: SELECT c, d FROM public.distr2_base WHERE (($1::integer = c)) +(28 rows) + +SELECT * from distr1 d1, distr2 d2, unnest(array[300,400]) n +WHERE d1.a = n AND d2.c = d1.a and n > 3 +ORDER BY d1.a; + a | b | c | d | n +-----+-----+-----+---------+----- + 300 | 600 | 300 | text300 | 300 + 400 | 800 | 400 | text400 | 400 +(2 rows) + +DROP FOREIGN TABLE distr1_remote, distr2_remote; +DROP TABLE distr1, distr1_loc, distr1_base, distr2, distr2_loc, distr2_base; +-- Test UNION and function scan pushdown +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM +(SELECT a FROM remote_tbl +UNION +SELECT c FROM remote_tbl1) u +JOIN unnest(array[3,4]) n +ON u.a = n; + QUERY PLAN +---------------------------------------------------------------- + Hash Join + Output: remote_tbl.a, n.n + Hash Cond: (remote_tbl.a = n.n) + -> HashAggregate + Output: remote_tbl.a + Group Key: remote_tbl.a + -> Append + -> Foreign Scan on public.remote_tbl + Output: remote_tbl.a + Remote SQL: SELECT a FROM public.base_tbl + -> Foreign Scan on public.remote_tbl1 + Output: remote_tbl1.c + Remote SQL: SELECT c FROM public.base_tbl1 + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{3,4}'::integer[]) +(18 rows) + +SELECT * FROM +(SELECT a FROM remote_tbl +UNION +SELECT c FROM remote_tbl1) u +JOIN unnest(array[3,4]) n +ON u.a = n +ORDER BY n; + a | n +---+--- + 3 | 3 + 4 | 4 +(2 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM +(SELECT a FROM remote_tbl +UNION ALL +SELECT c FROM remote_tbl1) u +JOIN unnest(array[3,4]) n +ON u.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------- + Append + -> Foreign Scan + Output: remote_tbl.a, n.n + Relations: (public.remote_tbl) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r6.a, r2.n FROM (public.base_tbl r6 INNER JOIN unnest('{3,4}'::integer[]) r2 (n) ON (((r6.a = r2.n)))) + -> Foreign Scan + Output: remote_tbl1.c, n.n + Relations: (public.remote_tbl1) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r7.c, r2.n FROM (public.base_tbl1 r7 INNER JOIN unnest('{3,4}'::integer[]) r2 (n) ON (((r7.c = r2.n)))) +(9 rows) + +SELECT * FROM +(SELECT a FROM remote_tbl +UNION ALL +SELECT c FROM remote_tbl1) u +JOIN unnest(array[3,4]) n +ON u.a = n +ORDER BY n; + a | n +---+--- + 3 | 3 + 3 | 3 + 4 | 4 + 4 | 4 +(4 rows) + +RESET enable_partitionwise_join; +DROP FUNCTION f(INTEGER); +DROP TABLE base_tbl, base_tbl1; +DROP FOREIGN TABLE remote_tbl, remote_tbl1; diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 76d4fea21c4..bd6e974ebdb 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -48,6 +48,7 @@ #include "utils/rel.h" #include "utils/sampling.h" #include "utils/selfuncs.h" +#include "utils/typcache.h" PG_MODULE_MAGIC; @@ -406,6 +407,14 @@ static void postgresGetForeignJoinPaths(PlannerInfo *root, RelOptInfo *innerrel, JoinType jointype, JoinPathExtraData *extra); + +static void postgresTryShippableJoinPaths(PlannerInfo *root, + RelOptInfo *joinrel, + RelOptInfo *outerrel, + RelOptInfo *innerrel, + JoinType jointype, + JoinPathExtraData *extra); + static bool postgresRecheckForeignScan(ForeignScanState *node, TupleTableSlot *slot); static void postgresGetForeignUpperPaths(PlannerInfo *root, @@ -474,7 +483,7 @@ static void store_returning_result(PgFdwModifyState *fmstate, static void finish_foreign_modify(PgFdwModifyState *fmstate); static void deallocate_query(PgFdwModifyState *fmstate); static List *build_remote_returning(Index rtindex, Relation rel, - List *returningList); + List *returningList, Var *tid); static void rebuild_fdw_scan_tlist(ForeignScan *fscan, List *tlist); static void execute_dml_stmt(ForeignScanState *node); static TupleTableSlot *get_returning_data(ForeignScanState *node); @@ -540,6 +549,12 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_i); static int get_batch_size_option(Relation rel); +static bool is_nonrel_relinfo_ok(PlannerInfo *root, RelOptInfo *foreignrel); +static void init_fpinfo(PlannerInfo *root, + RelOptInfo *baserel, + Oid foreigntableid, + PgFdwRelationInfo *existing_fpinfo); + /* * Foreign-data wrapper handler function: return a struct with pointers @@ -595,6 +610,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS) /* Support functions for join push-down */ routine->GetForeignJoinPaths = postgresGetForeignJoinPaths; + routine->TryShippableJoinPaths = postgresTryShippableJoinPaths; /* Support functions for upper relation push-down */ routine->GetForeignUpperPaths = postgresGetForeignUpperPaths; @@ -619,10 +635,31 @@ static void postgresGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid) +{ + init_fpinfo(root, baserel, foreigntableid, NULL); +} + +/* + * init_fpinfo + * + * Either initialize fpinfo based on foreign table or generate one, based on + * existing fpinfo. + * Also estimate # of rows and width of the result of the scan. + * + * We should consider the effect of all baserestrictinfo clauses here, but + * not any join clauses. + */ +static void +init_fpinfo(PlannerInfo *root, + RelOptInfo *baserel, + Oid foreigntableid, + PgFdwRelationInfo *existing_fpinfo) { PgFdwRelationInfo *fpinfo; ListCell *lc; - RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root); + + Assert(existing_fpinfo || foreigntableid != InvalidOid); + Assert(existing_fpinfo == NULL || foreigntableid == InvalidOid); /* * We use PgFdwRelationInfo to pass various information to subsequent @@ -634,39 +671,59 @@ postgresGetForeignRelSize(PlannerInfo *root, /* Base foreign tables need to be pushed down always. */ fpinfo->pushdown_safe = true; - /* Look up foreign-table catalog info. */ - fpinfo->table = GetForeignTable(foreigntableid); - fpinfo->server = GetForeignServer(fpinfo->table->serverid); - - /* - * Extract user-settable option values. Note that per-table settings of - * use_remote_estimate, fetch_size and async_capable override per-server - * settings of them, respectively. - */ - fpinfo->use_remote_estimate = false; - fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST; - fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST; - fpinfo->shippable_extensions = NIL; - fpinfo->fetch_size = 100; - fpinfo->async_capable = false; + if (existing_fpinfo) + { + /* We don't have any table, related to query */ + fpinfo->table = NULL; + fpinfo->server = existing_fpinfo->server; + } + else + { + /* Look up foreign-table catalog info. */ + fpinfo->table = GetForeignTable(foreigntableid); + fpinfo->server = GetForeignServer(fpinfo->table->serverid); + } - apply_server_options(fpinfo); - apply_table_options(fpinfo); + if (existing_fpinfo) + { + merge_fdw_options(fpinfo, existing_fpinfo, NULL); + fpinfo->user = existing_fpinfo->user; - /* - * If the table or the server is configured to use remote estimates, - * identify which user to do remote access as during planning. This - * should match what ExecCheckRTEPerms() does. If we fail due to lack of - * permissions, the query would have failed at runtime anyway. - */ - if (fpinfo->use_remote_estimate) + /* + * Don't try to execute anything on remote server for + * non-relation-based query + */ + fpinfo->use_remote_estimate = false; + } + else { + RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root); Oid userid = rte->checkAsUser ? rte->checkAsUser : GetUserId(); + /* + * Extract user-settable option values. Note that per-table settings + * of use_remote_estimate, fetch_size and async_capable override + * per-server settings of them, respectively. + */ + fpinfo->use_remote_estimate = false; + fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST; + fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST; + fpinfo->shippable_extensions = NIL; + fpinfo->fetch_size = 100; + fpinfo->async_capable = false; + fpinfo->is_generated = false; + + apply_server_options(fpinfo); + apply_table_options(fpinfo); + + /* + * If the table or the server is configured to use remote estimates, + * identify which user to do remote access as during planning. This + * should match what ExecCheckRTEPerms() does. If we fail due to lack + * of permissions, the query would have failed at runtime anyway. + */ fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid); } - else - fpinfo->user = NULL; /* * Identify which baserestrictinfo clauses can be sent to the remote @@ -778,6 +835,9 @@ postgresGetForeignRelSize(PlannerInfo *root, fpinfo->lower_subquery_rels = NULL; /* Set the relation index. */ fpinfo->relation_index = baserel->relid; + if (existing_fpinfo) + /* Mark fpinfo generated */ + fpinfo->is_generated = true; } /* @@ -1472,13 +1532,72 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION) + { + RangeTblFunction *rtfunc; + TupleDesc td; + Oid funcrettype; + int num_funcs, + attnum; + ListCell *lc, + *lctype, + *lcname; + bool functype_OK = true; + List *functypes = NIL; + + if (rte->funcordinality) + continue; + + num_funcs = list_length(rte->functions); + Assert(num_funcs >= 0); + + foreach(lc, rte->functions) + { + rtfunc = (RangeTblFunction *) lfirst(lc); + get_expr_result_type(rtfunc->funcexpr, &funcrettype, NULL); + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + { + functype_OK = false; + break; + } + functypes = lappend_oid(functypes, funcrettype); + } + if (!functype_OK) + continue; + td = CreateTemplateTupleDesc(num_funcs); + + /* + * funcrettype != RECORD, so we have only one return attribute per + * function + */ + Assert(list_length(rte->eref->colnames) == num_funcs); + attnum = 1; + forthree(lc, rte->functions, lctype, functypes, lcname, rte->eref->colnames) + { + char *colname; + + rtfunc = (RangeTblFunction *) lfirst(lc); + funcrettype = lfirst_oid(lctype); + colname = strVal(lfirst(lcname)); + + TupleDescInitEntry(td, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(td, (AttrNumber) attnum, + exprCollation(rtfunc->funcexpr)); + attnum++; + } + + assign_record_type_typmod(td); + att->atttypmod = td->tdtypmod; + } } return tupdesc; } @@ -1514,15 +1633,25 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckRTEPerms() does. In case of a join or aggregate, use the - * lowest-numbered member RTE as a representative; we would get the same - * result from any. + * ExecCheckRTEPerms() does. In case of a join or aggregate, scan RTEs + * until RTE_RELATION is found. We would get the same result from any. */ if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte && rte->rtekind == RTE_RELATION) + break; + } + Assert(rte && rte->rtekind == RTE_RELATION); + } userid = rte->checkAsUser ? rte->checkAsUser : GetUserId(); /* Get info about foreign table. */ @@ -2522,8 +2651,30 @@ postgresPlanDirectModify(PlannerInfo *root, * node below. */ if (fscan->scan.scanrelid == 0) + { + ListCell *lc; + Var *tid_var = NULL; + + /* + * We should explicitly add tableoid to returning list if it's + * requested + */ + foreach(lc, processed_tlist) + { + TargetEntry *tle = lfirst_node(TargetEntry, lc); + Var *var = (Var *) tle->expr; + + if (IsA(var, Var) && (var->varattno == TableOidAttributeNumber) && (strcmp(tle->resname, "tableoid") == 0)) + { + tid_var = var; + break; + } + + } + returningList = build_remote_returning(resultRelation, rel, - returningList); + returningList, tid_var); + } } /* @@ -2848,21 +2999,65 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_relids)); rte = rt_fetch(rti, es->rtable); - Assert(rte->rtekind == RTE_RELATION); /* This logic should agree with explain.c's ExplainTargetRel */ - relname = get_rel_name(rte->relid); - if (es->verbose) + if (rte->rtekind == RTE_RELATION) { - char *namespace; - - namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); - appendStringInfo(relations, "%s.%s", - quote_identifier(namespace), - quote_identifier(relname)); + relname = get_rel_name(rte->relid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name(get_rel_namespace(rte->relid)); + appendStringInfo(relations, "%s.%s", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfoString(relations, + quote_identifier(relname)); + } + else if (rte->rtekind == RTE_FUNCTION) + { + ListCell *lc; + int n; + bool first = true; + + + n = list_length(rte->functions); + + if (n > 1) + appendStringInfo(relations, "ROWS FROM("); + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (!first) + appendStringInfoString(relations, ", "); + else + first = false; + + if (IsA(rtfunc->funcexpr, FuncExpr)) + { + FuncExpr *funcexpr = (FuncExpr *) rtfunc->funcexpr; + Oid funcid = funcexpr->funcid; + + relname = get_func_name(funcid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name(get_func_namespace(funcid)); + appendStringInfo(relations, "%s.%s()", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfo(relations, "%s()", quote_identifier(relname)); + } + } + if (n > 1) + appendStringInfo(relations, ")"); } - else - appendStringInfoString(relations, - quote_identifier(relname)); refname = (char *) list_nth(es->rtable_names, rti - 1); if (refname == NULL) refname = rte->eref->aliasname; @@ -3201,7 +3396,7 @@ estimate_path_cost_size(PlannerInfo *root, /* Shouldn't get here unless we have LIMIT */ Assert(fpextra->has_limit); Assert(foreignrel->reloptkind == RELOPT_BASEREL || - foreignrel->reloptkind == RELOPT_JOINREL); + IS_JOIN_REL(foreignrel)); startup_cost += foreignrel->reltarget->cost.startup; run_cost += foreignrel->reltarget->cost.per_tuple * rows; } @@ -4378,7 +4573,7 @@ deallocate_query(PgFdwModifyState *fmstate) * UPDATE/DELETE .. RETURNING on a join directly */ static List * -build_remote_returning(Index rtindex, Relation rel, List *returningList) +build_remote_returning(Index rtindex, Relation rel, List *returningList, Var *tid) { bool have_wholerow = false; List *tlist = NIL; @@ -4387,6 +4582,19 @@ build_remote_returning(Index rtindex, Relation rel, List *returningList) Assert(returningList); + /* + * If tid is requested, add it to the returning list + */ + if (tid) + { + tlist = lappend(tlist, + makeTargetEntry((Expr *) tid, + list_length(tlist) + 1, + NULL, + false)); + + } + vars = pull_var_clause((Node *) returningList, PVC_INCLUDE_PLACEHOLDERS); /* @@ -4679,11 +4887,13 @@ init_returning_filter(PgFdwDirectModifyState *dmstate, if (attrno < 0) { /* - * We don't retrieve system columns other than ctid and oid. + * We don't retrieve system columns other than ctid and oid, + * but locally-generated tableoid can appear in returning + * list. */ if (attrno == SelfItemPointerAttributeNumber) dmstate->ctidAttno = i; - else + else if (attrno != TableOidAttributeNumber) Assert(false); dmstate->hasSystemCols = true; } @@ -5487,6 +5697,128 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid) return commands; } +/* + * Determine if foreignrel, not backed by foreign + * table, is fine to push down. + */ +static bool +is_nonrel_relinfo_ok(PlannerInfo *root, RelOptInfo *foreignrel) +{ + RangeTblEntry *rte; + RangeTblFunction *rtfunc; + + rte = planner_rt_fetch(foreignrel->relid, root); + + if (!rte) + return false; + + Assert(foreignrel->fdw_private); + + if (rte->rtekind == RTE_FUNCTION) + { + ListCell *lc; + + Assert(list_length(rte->functions) >= 1); + foreach(lc, rte->functions) + { + rtfunc = (RangeTblFunction *) lfirst(lc); + + if (contain_var_clause(rtfunc->funcexpr) || + contain_mutable_functions(rtfunc->funcexpr) || + contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, foreignrel, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; + } + + return false; +} + +/* + * Check if reltarget is safe enough to push down such join + */ +static bool +joinrel_target_ok(PlannerInfo *root, RelOptInfo *joinrel) +{ + List *vars; + ListCell *lc; + bool ok = true; + + Assert(joinrel->reltarget); + + /* TODO: is flag correct ? */ + vars = pull_var_clause((Node *) joinrel->reltarget->exprs, PVC_INCLUDE_PLACEHOLDERS); + + foreach(lc, vars) + { + Var *var = (Var *) lfirst(lc); + + /* + * We can't return abstract records, forbid such foreign joins, except + * cases when we can derive its type + */ + if (IsA(var, Var) && + var->vartype == RECORDOID && + var->vartypmod < 0) + { + ok = false; + + if (var->varattno == InvalidAttrNumber) + { + RangeTblEntry *rte = planner_rt_fetch(var->varno, root); + + if (rte) + { + if (rte->rtekind == RTE_RELATION) + { + Oid reltype; + + reltype = get_rel_type_id(rte->relid); + if (OidIsValid(reltype)) + ok = true; + } + else if (rte->rtekind == RTE_FUNCTION && !rte->funcordinality) + { + ListCell *lc; + int n; + + n = list_length(rte->functions); + + Assert(n >= 1); + + if (n == list_length(rte->eref->colnames)) + { + ok = true; + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc; + TupleDesc tupdesc; + Oid funcrettype; + + rtfunc = (RangeTblFunction *) lfirst(lc); + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID || funcrettype == VOIDOID) + { + ok = false; + break; + } + } + } + } + } + } + + if (!ok) + break; + } + } + return ok; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -5512,6 +5844,12 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, jointype != JOIN_RIGHT && jointype != JOIN_FULL) return false; + /* + * We can't push down join if its reltarget is not safe + */ + if (!joinrel_target_ok(root, joinrel)) + return false; + /* * If either of the joining relations is marked as unsafe to pushdown, the * join can not be pushed down. @@ -6075,6 +6413,43 @@ postgresGetForeignJoinPaths(PlannerInfo *root, /* XXX Consider parameterized paths for the join relation */ } +/* + * postgresTryShippableJoinPaths + * + * Try to add foreign join of foreign relation with shippable RTE. + */ +static void +postgresTryShippableJoinPaths(PlannerInfo *root, + RelOptInfo *joinrel, + RelOptInfo *outerrel, + RelOptInfo *innerrel, + JoinType jointype, + JoinPathExtraData *extra) +{ + PgFdwRelationInfo *fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + PgFdwRelationInfo *fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + + if (fpinfo_o == NULL) + /* Outer path is not foreign relation or foreign JOIN. */ + return; + + if (joinrel->fdwroutine != NULL || innerrel->reloptkind != RELOPT_BASEREL) + return; + + if (fpinfo_i == NULL || fpinfo_i->is_generated) + init_fpinfo(root, innerrel, InvalidOid, fpinfo_o); + + if (!is_nonrel_relinfo_ok(root, innerrel)) + return; + + joinrel->serverid = outerrel->serverid; + joinrel->userid = outerrel->userid; + joinrel->useridiscurrent = outerrel->useridiscurrent; + joinrel->fdwroutine = outerrel->fdwroutine; + + postgresGetForeignJoinPaths(root, joinrel, outerrel, innerrel, jointype, extra); +} + /* * Assess whether the aggregation, grouping and having operations can be pushed * down to the foreign server. As a side effect, save information we obtain in @@ -6505,7 +6880,7 @@ add_foreign_ordered_paths(PlannerInfo *root, RelOptInfo *input_rel, * standard_qp_callback()). */ if (input_rel->reloptkind == RELOPT_BASEREL || - input_rel->reloptkind == RELOPT_JOINREL) + IS_JOIN_REL(input_rel)) { Assert(root->query_pathkeys == root->sort_pathkeys); @@ -6656,11 +7031,11 @@ add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel, * join relation. */ Assert(input_rel->reloptkind == RELOPT_BASEREL || - input_rel->reloptkind == RELOPT_JOINREL || + IS_JOIN_REL(input_rel) || (input_rel->reloptkind == RELOPT_UPPER_REL && ifpinfo->stage == UPPERREL_ORDERED && (ifpinfo->outerrel->reloptkind == RELOPT_BASEREL || - ifpinfo->outerrel->reloptkind == RELOPT_JOINREL))); + IS_JOIN_REL(ifpinfo->outerrel)))); foreach(lc, input_rel->pathlist) { @@ -6728,7 +7103,7 @@ add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel, /* The input_rel should be a base, join, or grouping relation */ Assert(input_rel->reloptkind == RELOPT_BASEREL || - input_rel->reloptkind == RELOPT_JOINREL || + IS_JOIN_REL(input_rel) || (input_rel->reloptkind == RELOPT_UPPER_REL && ifpinfo->stage == UPPERREL_GROUP_AGG)); diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index 90b72e9ec55..0f599cdef5a 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -52,6 +52,12 @@ typedef struct PgFdwRelationInfo /* True means that the query_pathkeys is safe to push down */ bool qp_is_pushdown_safe; + /* + * True means that PgFdwRelationInfo is not extracted from catalogs, but + * generated + */ + bool is_generated; + /* Cost and selectivity of local_conds. */ QualCost local_conds_cost; Selectivity local_conds_sel; diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 38f4a7837fe..fb3469efe5a 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -3422,3 +3422,339 @@ CREATE FOREIGN TABLE inv_fsz (c1 int ) -- Invalid batch_size option CREATE FOREIGN TABLE inv_bsz (c1 int ) SERVER loopback OPTIONS (batch_size '100$%$#$#'); + +-- =================================================================== +-- test function scan pushdown +-- =================================================================== +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl'); +ALTER FOREIGN TABLE remote_tbl OPTIONS (use_remote_estimate 'true'); +CREATE TABLE base_tbl1 (c int, d text); +CREATE FOREIGN TABLE remote_tbl1 (c int, d text) + SERVER loopback OPTIONS (table_name 'base_tbl1'); +ALTER FOREIGN TABLE remote_tbl1 OPTIONS (use_remote_estimate 'true'); + +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO remote_tbl1 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE base_tbl; +ANALYZE base_tbl1; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n; + +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n; + +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a; + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*,n from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + +SELECT * from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*, t.n from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), json_each_text('{"a":"text1", "c":"text4"}')) t (n, k, txt) +WHERE r.c = t.n AND r.d = t.txt; + +SELECT r.*, t.txt from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), json_each_text('{"a":"text1", "c":"text4"}')) t (n, k, txt) +WHERE r.c = t.n AND r.d = t.txt; + +-- complex types +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx); + +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx) +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl1 r1 JOIN json_each_text('{"a":"text1", "b":2, "c":"text14"}') ON d = value; + +SELECT * FROM remote_tbl1 r1 JOIN json_each_text('{"a":"text1", "b":2, "c":"text14"}') ON d = value +ORDER BY r1.c; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl1 r1 JOIN json_each_text('{"a":"text1", "b":2, "c":"text14"}') AS t(u,v) ON d = v; + +SELECT * FROM remote_tbl1 r1 JOIN json_each_text('{"a":"text1", "b":2, "c":"text14"}') AS t(u,v) ON d = v +ORDER BY r1.c; + +-- DML +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +-- Test that local functions are not pushed down +CREATE OR REPLACE FUNCTION f(INTEGER) +RETURNS SETOF INTEGER +LANGUAGE sql AS 'select generate_series(1,$1);' IMMUTABLE; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, f(10) n +WHERE r.a = n; + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a AND n > 3; + +-- Test joins with append relations + +SET enable_partitionwise_join=on; + +-- Partitioned tables and function scan pushdown + +CREATE TABLE distr1(a int, b int) PARTITION BY HASH(a); +CREATE TABLE distr1_part_1 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 4, REMAINDER 0); +CREATE TABLE distr1_base_2 (a int, b int); +CREATE FOREIGN TABLE distr1_part_2 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 4, REMAINDER 1) + SERVER loopback OPTIONS (table_name 'distr1_base_2', use_remote_estimate 'true'); +CREATE TABLE distr1_base_3 (a int, b int); +CREATE FOREIGN TABLE distr1_part_3 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 4, REMAINDER 2) + SERVER loopback2 OPTIONS (table_name 'distr1_base_3', use_remote_estimate 'true'); +CREATE TABLE distr1_base_4 (a int, b int); +CREATE FOREIGN TABLE distr1_part_4 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 4, REMAINDER 3) + SERVER loopback OPTIONS (table_name 'distr1_base_4', use_remote_estimate 'true'); + +CREATE TABLE distr2(c int, d text) PARTITION BY HASH(c); +CREATE TABLE distr2_part_1 PARTITION OF distr2 FOR VALUES WITH (MODULUS 4, REMAINDER 0); +CREATE TABLE distr2_base_2 (c int, d text); +CREATE FOREIGN TABLE distr2_part_2 PARTITION OF distr2 FOR VALUES WITH ( MODULUS 4, REMAINDER 1) + SERVER loopback OPTIONS (table_name 'distr2_base_2', use_remote_estimate 'true'); +CREATE TABLE distr2_base_3 (c int, d text); +CREATE FOREIGN TABLE distr2_part_3 PARTITION OF distr2 FOR VALUES WITH ( MODULUS 4, REMAINDER 2) + SERVER loopback2 OPTIONS (table_name 'distr2_base_3', use_remote_estimate 'true'); +CREATE TABLE distr2_base_4 (c int, d text); +CREATE FOREIGN TABLE distr2_part_4 PARTITION OF distr2 FOR VALUES WITH ( MODULUS 4, REMAINDER 3) + SERVER loopback OPTIONS (table_name 'distr2_base_4', use_remote_estimate 'true'); + +INSERT INTO distr1 SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO distr2 SELECT g, 'text'|| g from generate_series(1,500) g; + +ANALYZE distr1; +ANALYZE distr1_part_1; +ANALYZE distr1_base_2; +ANALYZE distr1_base_3; +ANALYZE distr1_base_4; +ANALYZE distr2; +ANALYZE distr2_base_2; +ANALYZE distr2_base_3; +ANALYZE distr2_base_4; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM distr1 d, unnest(array[2,3,4,5]) n WHERE d.a = n; + +SELECT * FROM distr1 d, unnest(array[2,3,4,5]) n WHERE d.a = n +ORDER BY d.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4,5]) n, distr1 d WHERE d.a = n; + +SELECT * FROM unnest(array[2,3,4,5]) n, distr1 d WHERE d.a = n +ORDER BY d.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM distr1 d1, distr2 d2, unnest(array[3,4]) n +WHERE d1.a = n AND d2.c = d1.a; + +SELECT * FROM distr1 d1, distr2 d2, unnest(array[3,4]) n +WHERE d1.a = n AND d2.c = d1.a +ORDER BY d1.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * from distr1 d1, distr2 d2, unnest(array[3,4]) n +WHERE d1.a = n AND d2.c = d1.a and n > 3; + +SELECT * from distr1 d1, distr2 d2, unnest(array[3,4]) n +WHERE d1.a = n AND d2.c = d1.a and n > 3 +ORDER BY d1.a; + +-- Direct update with returning +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE distr1 d1 SET b=t.l FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b; + +UPDATE distr1 d1 SET b=t.l FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b; + +-- Direct update with returning tableoid +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE distr1 d1 SET b=t.l FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b,tableoid; + +UPDATE distr1 d1 SET b=t.l FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b,tableoid; + +-- Indirect update with returning +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE distr1 d1 SET b=CASE WHEN random()>=0 THEN t.l ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b; + +UPDATE distr1 d1 SET b=CASE WHEN random()>=0 THEN t.l ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE d1.a between l and area(t.bx) +RETURNING a,b; + +DROP TABLE distr1, distr2, distr1_base_2, distr2_base_2, distr1_base_3, distr2_base_3, distr1_base_4, distr2_base_4; + +-- Test pushdown of several function scans + +CREATE TABLE distr1(a int, b int) PARTITION BY HASH(a); +CREATE TABLE distr1_part_1 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 2, REMAINDER 0); +CREATE TABLE distr1_base_2 (a int, b int); +CREATE FOREIGN TABLE distr1_part_2 PARTITION OF distr1 FOR VALUES WITH ( MODULUS 2, REMAINDER 1) + SERVER loopback OPTIONS (table_name 'distr1_base_2', use_remote_estimate 'true'); + +CREATE TABLE distr2(c int, d text) PARTITION BY HASH(c); +CREATE TABLE distr2_part_1 PARTITION OF distr2 FOR VALUES WITH (MODULUS 2, REMAINDER 0); +CREATE TABLE distr2_base_2 (c int, d text); +CREATE FOREIGN TABLE distr2_part_2 PARTITION OF distr2 FOR VALUES WITH ( MODULUS 2, REMAINDER 1) + SERVER loopback OPTIONS (table_name 'distr2_base_2', use_remote_estimate 'true'); + +INSERT INTO distr1 SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO distr2 SELECT g, 'text'|| g from generate_series(1,500) g; + +ANALYZE; + +-- Make local function scan not so attractive +ALTER SERVER loopback OPTIONS (ADD fdw_tuple_cost '1000'); + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * from distr1 d1, distr1 d2, unnest(array[3,4]) n, unnest(array[3,4]) g +WHERE d1.a = n AND d2.a = d1.a and g = n; + +SELECT * from distr1 d1, distr2 d2, unnest(array[3,4]) n, generate_series(1,10000) g +WHERE d1.a = n AND d2.c = d1.a and g = d1.a +ORDER BY d1.a; + +ALTER SERVER loopback OPTIONS (DROP fdw_tuple_cost); + +DROP TABLE distr1, distr2, distr1_base_2, distr2_base_2; + +-- Test inheritance chain and function scan pushdown + +CREATE TABLE distr1(a int, b int); +CREATE TABLE distr1_loc (a int, b int) INHERITS (distr1); +CREATE TABLE distr1_base (a int, b int, c text); +CREATE FOREIGN TABLE distr1_remote (a int, b int, c text) INHERITS (distr1) + SERVER loopback OPTIONS (table_name 'distr1_base', use_remote_estimate 'true'); + +CREATE TABLE distr2(c int, d text); +CREATE TABLE distr2_loc (c int, d text) INHERITS (distr2); +CREATE TABLE distr2_base (c int, d text, e int); +CREATE FOREIGN TABLE distr2_remote (c int, d text, e int) INHERITS (distr2) + SERVER loopback OPTIONS (table_name 'distr2_base', use_remote_estimate 'true'); + +INSERT INTO distr1_loc SELECT g, g*2 from generate_series(1,100) g; +INSERT INTO distr1_base SELECT g, g*2, 'text'|| g from generate_series(200,20000) g; + +INSERT INTO distr2_loc SELECT g, 'text'|| g from generate_series(1,100) g; +INSERT INTO distr2_base SELECT g, 'text'|| g, g*2 from generate_series(200,20000) g; + +ANALYZE distr1, distr1_loc, distr1_base; +ANALYZE distr2, distr2_loc, distr2_base; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM distr1 d, unnest(array[2,3,4,5]) n WHERE d.a = n; + +SELECT * FROM distr1 d, unnest(array[2,3,4,5]) n WHERE d.a = n +ORDER BY d.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4,5]) n, distr1 d WHERE d.a = n; + +SELECT * FROM unnest(array[2,3,4,5]) n, distr1 d WHERE d.a = n +ORDER BY d.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM distr1 d1, distr2 d2, unnest(array[300,400]) n +WHERE d1.a = n AND d2.c = d1.a; + +SELECT * FROM distr1 d1, distr2 d2, unnest(array[300,400]) n +WHERE d1.a = n AND d2.c = d1.a +ORDER BY d1.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * from distr1 d1, distr2 d2, unnest(array[300,400]) n +WHERE d1.a = n AND d2.c = d1.a and n > 3; + +SELECT * from distr1 d1, distr2 d2, unnest(array[300,400]) n +WHERE d1.a = n AND d2.c = d1.a and n > 3 +ORDER BY d1.a; + +DROP FOREIGN TABLE distr1_remote, distr2_remote; +DROP TABLE distr1, distr1_loc, distr1_base, distr2, distr2_loc, distr2_base; + +-- Test UNION and function scan pushdown + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM +(SELECT a FROM remote_tbl +UNION +SELECT c FROM remote_tbl1) u +JOIN unnest(array[3,4]) n +ON u.a = n; + +SELECT * FROM +(SELECT a FROM remote_tbl +UNION +SELECT c FROM remote_tbl1) u +JOIN unnest(array[3,4]) n +ON u.a = n +ORDER BY n; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM +(SELECT a FROM remote_tbl +UNION ALL +SELECT c FROM remote_tbl1) u +JOIN unnest(array[3,4]) n +ON u.a = n; + +SELECT * FROM +(SELECT a FROM remote_tbl +UNION ALL +SELECT c FROM remote_tbl1) u +JOIN unnest(array[3,4]) n +ON u.a = n +ORDER BY n; + +RESET enable_partitionwise_join; + +DROP FUNCTION f(INTEGER); +DROP TABLE base_tbl, base_tbl1; +DROP FOREIGN TABLE remote_tbl, remote_tbl1; diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c index 32618ebbd51..c8b12c9360d 100644 --- a/src/backend/optimizer/path/joinpath.c +++ b/src/backend/optimizer/path/joinpath.c @@ -329,6 +329,17 @@ add_paths_to_joinrel(PlannerInfo *root, outerrel, innerrel, jointype, &extra); + /* + * If push down of join is not possible we can try to join foreign + * relation with shippable RTE. In this case we have a chance to push down + * this join yet. + */ + else if (outerrel->fdwroutine && + outerrel->fdwroutine->TryShippableJoinPaths) + outerrel->fdwroutine->TryShippableJoinPaths(root, joinrel, + outerrel, innerrel, + jointype, &extra); + /* * 6. Finally, give extensions a chance to manipulate the path list. */ diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c index 02529da562b..172122ed4d9 100644 --- a/src/backend/optimizer/plan/setrefs.c +++ b/src/backend/optimizer/plan/setrefs.c @@ -500,7 +500,6 @@ add_rte_to_flat_rtable(PlannerGlobal *glob, RangeTblEntry *rte) newrte->joinleftcols = NIL; newrte->joinrightcols = NIL; newrte->join_using_alias = NULL; - newrte->functions = NIL; newrte->tablefunc = NULL; newrte->values_lists = NIL; newrte->coltypes = NIL; diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index ddf0f5a8765..9675aa6b3ab 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -22,12 +22,14 @@ #include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" +#include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/plancat.h" #include "optimizer/restrictinfo.h" #include "optimizer/tlist.h" +#include "parser/parsetree.h" #include "utils/hsearch.h" #include "utils/lsyscache.h" diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h index a801cd30576..58555094da3 100644 --- a/src/include/foreign/fdwapi.h +++ b/src/include/foreign/fdwapi.h @@ -221,6 +221,7 @@ typedef struct FdwRoutine /* Functions for remote-join planning */ GetForeignJoinPaths_function GetForeignJoinPaths; + GetForeignJoinPaths_function TryShippableJoinPaths; /* Functions for remote upper-relation (post scan/join) planning */ GetForeignUpperPaths_function GetForeignUpperPaths; -- 2.25.1
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2021-05-20 17:43 Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2021-06-15 13:15 ` Re: Function scan FDW pushdown Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
  2021-10-04 07:42   ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2024-11-05 16:11     ` g.kashkin@postgrespro.ru
  2025-08-05 21:32       ` Re: Function scan FDW pushdown Álvaro Herrera <alvherre@kurilemu.de>
  0 siblings, 1 reply; 36+ messages in thread

From: g.kashkin@postgrespro.ru @ 2024-11-05 16:11 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Ashutosh Bapat <ashutosh.bapat@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Alexander Pyhalov писал(а) 2021-10-04 10:42:
> Ashutosh Bapat писал 2021-06-15 16:15:
>> Hi Alexander,
> 
> Hi.
> 
> The current version of the patch is based on asymetric partition-wise 
> join.
> Currently it is applied after 
> v19-0001-Asymmetric-partitionwise-join.patch from
> on 
> https://www.postgresql.org/message-id/792d60f4-37bc-e6ad-68ca-c2af5cbb2d9b@postgrespro.ru 
> .
> 
>>> So far I don't know how to visualize actual function expression used 
>>> in
>>> function RTE, as in postgresExplainForeignScan() es->rtable comes 
>>> from
>>> queryDesc->plannedstmt->rtable, and rte->functions is already 0.
>> 
>> The actual function expression will be part of the Remote SQL of
>> ForeignScan node so no need to visualize it separately.
> 
> We still need to create tuple description for functions in 
> get_tupdesc_for_join_scan_tuples(),
> so I had to remove setting newrte->functions to NIL in 
> add_rte_to_flat_rtable().
> With rte->functions in place, there's no issues for explain.
> 
>> 
>> The patch will have problems when there are multiple foreign tables
>> all on different servers or use different FDWs. In such a case the
>> function scan's RelOptInfo will get the fpinfo based on the first
>> foreign table the function scan is paired with during join planning.
>> But that may not be the best foreign table to join. We should be able
>> to plan all the possible joins. Current infra to add one fpinfo per
>> RelOptInfo won't help there. We need something better.
> 
> I suppose attached version of the patch is more mature.
> 
>> 
>> The patch targets only postgres FDW, how do you see this working with
>> other FDWs?
> 
> Not now. We introduce necessary APIs for other FDWs, but implementing 
> TryShippableJoinPaths()
> doesn't seem straightforward.
> 
>> 
>> If we come up with the right approach we could use it for 1. pushing
>> down queries with IN () clause 2. joining a small local table with a
>> large foreign table by sending the local table rows down to the
>> foreign server.

Hi,
This is a long-overdue follow-up to the original patch.
Note that this patch contains only the changes required for
function scan pushdown, examples and code related to asymmetric
join are dropped.

In this version, we have fixed some of the issues:
1) Functions returning records are now deparsed correctly
2) I have benchmarked this version alongside the current master
    using HammerDB and it shows a consistent ~6000 number of orders
    per minute (NOPM) compared to ~100 NOPM on local setup with
    1 virtual user and 10 warehouses

The benchmarking was concluded in the following way:
1) schema was created and filled up by buildschema on the first instance
2) foreign schema was imported on the second instance
3) functions created by buildschema (all in namespace 'public') were
    exported from the first instance and created on the second one
4) HammerDB was connected to the second instance, and the benchmark
    was run there

Note that the HammerDB service functions that were imported to the 
second
instance are not the ones being pushed down, only PostgreSQL built-ins 
are.

The issue with setting newrte->functions to NIL still persists.
I've attempted to work around it by adding the rte->functions
list to fdw_private field. I stored a copy of rte->functions for each
RTE in the order they are listed in simple_rte_array and accessed it
where the rte->functions were used in the original patch. While this
being pretty straightforward, I found out the hard way that the RTEs
are flattened and the original sequential order known at
postgresGetForeignPlan() and postgresPlanDirectModify() is altered
randomly. It prevents me from looking up the right functions list for
the RTE by its rti in postgresExplainForeignScan() and its var->varno in
get_tupdesc_for_join_scan_tuples(). I am aware that the rte->functions
will now be copied even on instances that don't utilize a FDW, but I
don't see a way to solve it. Any suggestions are welcome.

Best regards,
Gleb Kashkin,
Postgres Professional

Attachments:

0001-Push-join-with-function-scan-to-remote-server.patch (text/x-diff, 52.0K) download From a59b04e33147a075fdd4c6cef155440689850b83 Mon Sep 17 00:00:00 2001 From: Alexander Pyhalov <a.pyhalov@postgrespro.ru> Date: Mon, 17 May 2021 19:19:31 +0300 Subject: [PATCH] Push join with function scan to remote server The patch allows pushing joins with function RTEs to PostgreSQL data sources in general and postgres_fdw specifically. Co-authored-by: Gleb Kashkin <g.kashkin@postgrespro.ru> --- contrib/postgres_fdw/deparse.c | 187 ++++++-- .../postgres_fdw/expected/postgres_fdw.out | 368 +++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 423 +++++++++++++++--- contrib/postgres_fdw/postgres_fdw.h | 6 + contrib/postgres_fdw/sql/postgres_fdw.sql | 148 ++++++ src/backend/optimizer/path/joinpath.c | 11 + src/backend/optimizer/plan/setrefs.c | 1 - src/include/foreign/fdwapi.h | 1 + src/test/regress/expected/create_view.out | 6 +- 9 files changed, 1046 insertions(+), 105 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 4680d51733..17228dec47 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -153,6 +153,7 @@ static void deparseConst(Const *node, deparse_expr_cxt *context, int showtype); static void deparseParam(Param *node, deparse_expr_cxt *context); static void deparseSubscriptingRef(SubscriptingRef *node, deparse_expr_cxt *context); static void deparseFuncExpr(FuncExpr *node, deparse_expr_cxt *context); +static void deparseFuncColnames(StringInfo buf, int varno, RangeTblEntry *rte, bool qualify_col); static void deparseOpExpr(OpExpr *node, deparse_expr_cxt *context); static bool isPlainForeignVar(Expr *node, deparse_expr_cxt *context); static void deparseOperatorName(StringInfo buf, Form_pg_operator opform); @@ -1977,13 +1978,54 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, { RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); - /* - * Core code already has some lock on each rel being planned, so we - * can use NoLock here. - */ - Relation rel = table_open(rte->relid, NoLock); + Assert(rte->rtekind == RTE_RELATION || rte->rtekind == RTE_FUNCTION); + if (rte->rtekind == RTE_RELATION) + { + /* + * Core code already has some lock on each rel being planned, so + * we can use NoLock here. + */ + Relation rel = table_open(rte->relid, NoLock); - deparseRelation(buf, rel); + deparseRelation(buf, rel); + + table_close(rel, NoLock); + } + else if (rte->rtekind == RTE_FUNCTION) + { + RangeTblFunction *rtfunc; + deparse_expr_cxt context; + ListCell *lc; + bool first = true; + int n; + + n = list_length(rte->functions); + Assert(n >= 1); + + if (n > 1) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + if (!first) + appendStringInfoString(buf, ", "); + else + first = false; + + rtfunc = (RangeTblFunction *) lfirst(lc); + + context.root = root; + context.foreignrel = foreignrel; + context.scanrel = foreignrel; + context.buf = buf; + context.params_list = params_list; + + deparseExpr((Expr *) rtfunc->funcexpr, &context); + } + + if (n > 1) + appendStringInfoString(buf, ")"); + } /* * Add a unique alias to avoid any conflict in relation names due to @@ -1991,9 +2033,43 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, * join. */ if (use_alias) + { appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, foreignrel->relid); + if (rte->rtekind == RTE_FUNCTION) + { + appendStringInfo(buf, " ("); + deparseFuncColnames(buf, 0, rte, false); + appendStringInfo(buf, ") "); + } + } + } +} - table_close(rel, NoLock); +/* + * Deparse function columns alias list + */ +static void +deparseFuncColnames(StringInfo buf, int varno, RangeTblEntry *rte, bool qualify_col) +{ + bool first = true; + ListCell *lc; + + Assert(rte); + Assert(rte->rtekind == RTE_FUNCTION); + Assert(rte->eref); + + foreach(lc, rte->eref->colnames) + { + char *colname = strVal(lfirst(lc)); + + if (colname[0] == '\0') + continue; + if (!first) + appendStringInfoString(buf, ","); + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); + appendStringInfoString(buf, quote_identifier(colname)); + first = false; } } @@ -2717,23 +2793,6 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, /* Required only to be passed down to deparseTargetList(). */ List *retrieved_attrs; - /* - * The lock on the relation will be held by upper callers, so it's - * fine to open it with no lock here. - */ - rel = table_open(rte->relid, NoLock); - - /* - * The local name of the foreign table can not be recognized by the - * foreign server and the table it references on foreign server might - * have different column ordering or different columns than those - * declared locally. Hence we have to deparse whole-row reference as - * ROW(columns referenced locally). Construct this by deparsing a - * "whole row" attribute. - */ - attrs_used = bms_add_member(NULL, - 0 - FirstLowInvalidHeapAttributeNumber); - /* * In case the whole-row reference is under an outer join then it has * to go NULL whenever the rest of the row goes NULL. Deparsing a join @@ -2748,16 +2807,43 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, } appendStringInfoString(buf, "ROW("); - deparseTargetList(buf, rte, varno, rel, false, attrs_used, qualify_col, - &retrieved_attrs); + if (rte->rtekind == RTE_RELATION) + { + /* + * The local name of the foreign table can not be recognized by + * the foreign server and the table it references on foreign + * server might have different column ordering or different + * columns than those declared locally. Hence we have to deparse + * whole-row reference as ROW(columns referenced locally). + * Construct this by deparsing a "whole row" attribute. + */ + attrs_used = bms_add_member(NULL, + 0 - FirstLowInvalidHeapAttributeNumber); + + /* + * The lock on the relation will be held by upper callers, so it's + * fine to open it with no lock here. + */ + rel = table_open(rte->relid, NoLock); + deparseTargetList(buf, rte, varno, rel, false, attrs_used, qualify_col, + &retrieved_attrs); + table_close(rel, NoLock); + bms_free(attrs_used); + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * Function call is translated as-is, function returns the same + * columns in the same order as on local server + */ + deparseFuncColnames(buf, varno, rte, qualify_col); + } appendStringInfoChar(buf, ')'); /* Complete the CASE WHEN statement started above. */ if (qualify_col) appendStringInfoString(buf, " END"); - table_close(rel, NoLock); - bms_free(attrs_used); } else { @@ -2772,29 +2858,40 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, * If it's a column of a foreign table, and it has the column_name FDW * option, use that value. */ - options = GetForeignColumnOptions(rte->relid, varattno); - foreach(lc, options) + if (rte->rtekind == RTE_RELATION) { - DefElem *def = (DefElem *) lfirst(lc); - - if (strcmp(def->defname, "column_name") == 0) + options = GetForeignColumnOptions(rte->relid, varattno); + foreach(lc, options) { - colname = defGetString(def); - break; + DefElem *def = (DefElem *) lfirst(lc); + + if (strcmp(def->defname, "column_name") == 0) + { + colname = defGetString(def); + break; + } } - } - /* - * If it's a column of a regular table or it doesn't have column_name - * FDW option, use attribute name. - */ - if (colname == NULL) - colname = get_attname(rte->relid, varattno, false); + /* + * If it's a column of a regular table or it doesn't have + * column_name FDW option, use attribute name. + */ + if (colname == NULL) + colname = get_attname(rte->relid, varattno, false); - if (qualify_col) - ADD_REL_QUALIFIER(buf, varno); + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); - appendStringInfoString(buf, quote_identifier(colname)); + appendStringInfoString(buf, quote_identifier(colname)); + } + else if (rte->rtekind == RTE_FUNCTION) + { + colname = get_rte_attribute_name(rte, varattno); + + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); + appendStringInfoString(buf, quote_identifier(colname)); + } } } diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index f2bcd6aa98..686ce1ac61 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -12345,3 +12345,371 @@ SELECT CASE WHEN closed IS NOT false THEN 1 ELSE 0 END -- Clean up \set VERBOSITY default RESET debug_discard_caches; +-- =================================================================== +-- test function scan pushdown +-- =================================================================== +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl'); +ALTER FOREIGN TABLE remote_tbl OPTIONS (use_remote_estimate 'true'); +CREATE TABLE base_tbl1 (c int, d text); +CREATE FOREIGN TABLE remote_tbl1 (c int, d text) + SERVER loopback OPTIONS (table_name 'base_tbl1'); +ALTER FOREIGN TABLE remote_tbl1 OPTIONS (use_remote_estimate 'true'); +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO remote_tbl1 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE base_tbl; +ANALYZE base_tbl1; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, n.n + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r2.n FROM (public.base_tbl r1 INNER JOIN unnest('{2,3,4}'::integer[]) r2 (n) ON (((r1.a = r2.n)))) +(4 rows) + +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n +ORDER BY r.a; + a | b | n +---+---+--- + 2 | 4 | 2 + 3 | 6 | 3 + 4 | 8 | 4 +(3 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: n.n, r.a, r.b + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.n, r2.a, r2.b FROM (public.base_tbl r2 INNER JOIN unnest('{2,3,4}'::integer[]) r1 (n) ON (((r2.a = r1.n)))) +(4 rows) + +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n +ORDER BY r.a; + n | a | b +---+---+--- + 2 | 2 | 4 + 3 | 3 | 6 + 4 | 4 | 8 +(3 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: r.a, r.b, r1.c, r1.d, n.n + Relations: ((public.remote_tbl r) INNER JOIN (public.remote_tbl1 r1)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r2.c, r2.d, r3.n FROM ((public.base_tbl r1 INNER JOIN public.base_tbl1 r2 ON (((r1.a = r2.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r1.a = r3.n)))) +(4 rows) + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a +ORDER BY r.a; + a | b | c | d | n +---+---+---+-------+--- + 3 | 6 | 3 | text3 | 3 + 4 | 8 | 4 | text4 | 4 +(2 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*,n from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, n.n + Relations: ((public.remote_tbl r) INNER JOIN (public.remote_tbl1 r1)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r3.n FROM ((public.base_tbl r1 INNER JOIN public.base_tbl1 r2 ON (((r1.a = r2.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r1.a = r3.n)) AND ((r3.n > 3)))) +(4 rows) + +SELECT * from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + a | b | c | d | n +---+---+---+-------+--- + 4 | 8 | 4 | text4 | 4 +(1 row) + +CREATE OR REPLACE FUNCTION get_constant_texts() +RETURNS TABLE (text_value text) AS $$ +BEGIN + RETURN QUERY VALUES + ('text1'), + ('text4'); +END; +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION get_constant_texts(); +ALTER SERVER loopback OPTIONS (extensions 'postgres_fdw'); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*, t.n from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.c, r.d, t.n + Relations: (public.remote_tbl1 r) INNER JOIN (ROWS FROM(pg_catalog.unnest(), public.get_constant_texts()) t) + Remote SQL: SELECT r1.c, r1.d, r2.n FROM (public.base_tbl1 r1 INNER JOIN ROWS FROM (unnest('{3,4}'::integer[]), public.get_constant_texts()) r2 (n,txt) ON (((r1.c = r2.n)) AND ((r2.txt = r1.d)))) +(4 rows) + +SELECT r.*, t.txt from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + c | d | txt +---+-------+------- + 4 | text4 | text4 +(1 row) + +-- Complex types +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx); + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, t.bx + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() t) + Remote SQL: SELECT r1.a, r1.b, r2.bx FROM (public.base_tbl r1 INNER JOIN unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) ON (((r1.a = area(r2.bx))))) +(4 rows) + +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx) +ORDER BY r.a; + a | b | bx +----+----+--------------- + 24 | 48 | (2,3),(-2,-3) +(1 row) + +-- DML +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + -> Foreign Update + Remote SQL: UPDATE public.base_tbl r1 SET b = 5 FROM unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) WHERE ((r1.a = area(r2.bx))) RETURNING r1.a, r1.b +(4 rows) + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + a | b +----+--- + 24 | 5 +(1 row) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + Remote SQL: UPDATE public.base_tbl SET b = $2 WHERE ctid = $1 RETURNING a, b + -> Foreign Scan + Output: CASE WHEN (random() >= '0'::double precision) THEN 5 ELSE 0 END, r.ctid, r.*, t.* + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() t) + Remote SQL: SELECT r1.ctid, CASE WHEN (r1.*)::text IS NOT NULL THEN ROW(r1.a, r1.b) END, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2.bx) END FROM (public.base_tbl r1 INNER JOIN unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) ON (((r1.a = area(r2.bx))))) FOR UPDATE OF r1 + -> Hash Join + Output: r.ctid, r.*, t.* + Hash Cond: ((r.a)::double precision = area(t.bx)) + -> Foreign Scan on public.remote_tbl r + Output: r.ctid, r.*, r.a + Remote SQL: SELECT a, b, ctid FROM public.base_tbl FOR UPDATE + -> Hash + Output: t.*, t.bx + -> Function Scan on pg_catalog.unnest t + Output: t.*, t.bx + Function Call: unnest('{(2,3),(-2,-3)}'::box[]) +(18 rows) + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + a | b +----+--- + 24 | 5 +(1 row) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Update on public.remote_tbl r + Output: r.a, r.b + -> Foreign Update + Remote SQL: UPDATE public.base_tbl r1 SET b = 5 FROM ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) WHERE ((r1.a >= r2.l)) AND ((r1.a <= area(r2.bx))) RETURNING r1.a, r1.b +(4 rows) + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + a | b +----+--- + 10 | 5 + 11 | 5 + 12 | 5 + 13 | 5 + 14 | 5 + 15 | 5 + 16 | 5 + 17 | 5 + 18 | 5 + 19 | 5 + 20 | 5 + 21 | 5 + 22 | 5 + 23 | 5 + 25 | 5 + 26 | 5 + 27 | 5 + 28 | 5 + 24 | 5 +(19 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + Remote SQL: UPDATE public.base_tbl SET b = $2 WHERE ctid = $1 RETURNING a, b + -> Foreign Scan + Output: CASE WHEN (random() >= '0'::double precision) THEN 5 ELSE 0 END, r.ctid, r.*, t.* + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM(pg_catalog.unnest(), pg_catalog.unnest()) t) + Remote SQL: SELECT r1.ctid, CASE WHEN (r1.*)::text IS NOT NULL THEN ROW(r1.a, r1.b) END, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2.l,r2.bx) END FROM (public.base_tbl r1 INNER JOIN ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) ON (((r1.a >= r2.l)) AND ((r1.a <= area(r2.bx))))) FOR UPDATE OF r1 + -> Nested Loop + Output: r.ctid, r.*, t.* + Join Filter: ((r.a >= t.l) AND ((r.a)::double precision <= area(t.bx))) + -> Foreign Scan on public.remote_tbl r + Output: r.ctid, r.*, r.a + Remote SQL: SELECT a, b, ctid FROM public.base_tbl FOR UPDATE + -> Function Scan on t + Output: t.*, t.l, t.bx + Function Call: unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[]) +(16 rows) + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + a | b +----+--- + 10 | 5 + 11 | 5 + 12 | 5 + 13 | 5 + 14 | 5 + 15 | 5 + 16 | 5 + 17 | 5 + 18 | 5 + 19 | 5 + 20 | 5 + 21 | 5 + 22 | 5 + 23 | 5 + 25 | 5 + 26 | 5 + 27 | 5 + 28 | 5 + 24 | 5 +(19 rows) + +-- Test that local functions are not pushed down +CREATE OR REPLACE FUNCTION f(INTEGER) +RETURNS SETOF INTEGER +LANGUAGE sql AS 'select generate_series(1,$1);' IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, f(10) n +WHERE r.a = n; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: r.a, r.b, (generate_series(1, 10)) + Hash Cond: (r.a = (generate_series(1, 10))) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a, b FROM public.base_tbl + -> Hash + Output: (generate_series(1, 10)) + -> ProjectSet + Output: generate_series(1, 10) + -> Result +(11 rows) + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a AND n > 3; + a | b | c | d | n +---+---+---+-------+--- + 4 | 8 | 4 | text4 | 4 +(1 row) + +-- Test that a function that returns a record is not pushed down +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ SELECT (1,2)::record $$ language SQL IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD function f_ret_record(); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +----------------------------------------------------------------------------- + Nested Loop + Output: s.* + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl WHERE ((a = $1::integer)) +(8 rows) + +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + s +------- + (1,2) +(1 row) + +DROP FUNCTION f(INTEGER); +ALTER EXTENSION postgres_fdw DROP FUNCTION get_constant_texts(); +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ret_record(); +DROP FUNCTION get_constant_texts(); +DROP FUNCTION f_ret_record(); +DROP TABLE base_tbl, base_tbl1; +DROP FOREIGN TABLE remote_tbl, remote_tbl1; +-- Test that function WITH ORDINALITY is not pushed down +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) SERVER loopback OPTIONS (table_name 'base_tbl'); +INSERT INTO remote_tbl VALUES (1, 2), (2, 3), (3, 4), (5, 6); +ANALYZE remote_tbl; +SET enable_mergejoin TO false; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + QUERY PLAN +------------------------------------------------------------------------ + Hash Join + Output: remote_tbl.a, remote_tbl.b, unnest.unnest, unnest.ordinality + Hash Cond: (remote_tbl.a = unnest.unnest) + -> Foreign Scan on public.remote_tbl + Output: remote_tbl.a, remote_tbl.b + Remote SQL: SELECT a, b FROM public.base_tbl + -> Hash + Output: unnest.unnest, unnest.ordinality + -> Function Scan on pg_catalog.unnest + Output: unnest.unnest, unnest.ordinality + Function Call: unnest('{1,2}'::integer[]) +(11 rows) + +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + a | b | unnest | ordinality +---+---+--------+------------ + 1 | 2 | 1 | 1 + 2 | 3 | 2 | 2 +(2 rows) + +DROP TABLE base_tbl; +DROP FOREIGN TABLE remote_tbl; +RESET enable_mergejoin; diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 53733d642d..5d0a339ca0 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -36,6 +36,7 @@ #include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "optimizer/tlist.h" +#include "optimizer/clauses.h" #include "parser/parsetree.h" #include "postgres_fdw.h" #include "storage/latch.h" @@ -406,6 +407,14 @@ static void postgresGetForeignJoinPaths(PlannerInfo *root, RelOptInfo *innerrel, JoinType jointype, JoinPathExtraData *extra); + +static void postgresTryShippableJoinPaths(PlannerInfo *root, + RelOptInfo *joinrel, + RelOptInfo *outerrel, + RelOptInfo *innerrel, + JoinType jointype, + JoinPathExtraData *extra); + static bool postgresRecheckForeignScan(ForeignScanState *node, TupleTableSlot *slot); static void postgresGetForeignUpperPaths(PlannerInfo *root, @@ -476,7 +485,7 @@ static void store_returning_result(PgFdwModifyState *fmstate, static void finish_foreign_modify(PgFdwModifyState *fmstate); static void deallocate_query(PgFdwModifyState *fmstate); static List *build_remote_returning(Index rtindex, Relation rel, - List *returningList); + List *returningList, Var *tid); static void rebuild_fdw_scan_tlist(ForeignScan *fscan, List *tlist); static void execute_dml_stmt(ForeignScanState *node); static TupleTableSlot *get_returning_data(ForeignScanState *node); @@ -542,6 +551,11 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_i); static int get_batch_size_option(Relation rel); +static bool is_nonrel_relinfo_ok(PlannerInfo *root, RelOptInfo *foreignrel); +static void init_fpinfo(PlannerInfo *root, + RelOptInfo *baserel, + Oid foreigntableid, + PgFdwRelationInfo *existing_fpinfo); /* * Foreign-data wrapper handler function: return a struct with pointers @@ -597,6 +611,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS) /* Support functions for join push-down */ routine->GetForeignJoinPaths = postgresGetForeignJoinPaths; + routine->TryShippableJoinPaths = postgresTryShippableJoinPaths; /* Support functions for upper relation push-down */ routine->GetForeignUpperPaths = postgresGetForeignUpperPaths; @@ -621,10 +636,32 @@ static void postgresGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid) +{ + init_fpinfo(root, baserel, foreigntableid, NULL); +} + +/* + * init_fpinfo + * + * Either initialize fpinfo based on foreign table or generate one, based on + * existing fpinfo. + * Also estimate # of rows and width of the result of the scan. + * + * We should consider the effect of all baserestrictinfo clauses here, but + * not any join clauses. + */ +static void +init_fpinfo(PlannerInfo *root, + RelOptInfo *baserel, + Oid foreigntableid, + PgFdwRelationInfo *existing_fpinfo) { PgFdwRelationInfo *fpinfo; ListCell *lc; + Assert(existing_fpinfo || foreigntableid != InvalidOid); + Assert(existing_fpinfo == NULL || foreigntableid == InvalidOid); + /* * We use PgFdwRelationInfo to pass various information to subsequent * functions. @@ -635,40 +672,64 @@ postgresGetForeignRelSize(PlannerInfo *root, /* Base foreign tables need to be pushed down always. */ fpinfo->pushdown_safe = true; - /* Look up foreign-table catalog info. */ - fpinfo->table = GetForeignTable(foreigntableid); - fpinfo->server = GetForeignServer(fpinfo->table->serverid); - - /* - * Extract user-settable option values. Note that per-table settings of - * use_remote_estimate, fetch_size and async_capable override per-server - * settings of them, respectively. - */ - fpinfo->use_remote_estimate = false; - fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST; - fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST; - fpinfo->shippable_extensions = NIL; - fpinfo->fetch_size = 100; - fpinfo->async_capable = false; - - apply_server_options(fpinfo); - apply_table_options(fpinfo); + if (existing_fpinfo) + { + /* We don't have any table, related to query */ + fpinfo->table = NULL; + fpinfo->server = existing_fpinfo->server; + } + else + { + /* Look up foreign-table catalog info. */ + fpinfo->table = GetForeignTable(foreigntableid); + fpinfo->server = GetForeignServer(fpinfo->table->serverid); + } - /* - * If the table or the server is configured to use remote estimates, - * identify which user to do remote access as during planning. This - * should match what ExecCheckPermissions() does. If we fail due to lack - * of permissions, the query would have failed at runtime anyway. - */ - if (fpinfo->use_remote_estimate) + if (existing_fpinfo) { - Oid userid; + merge_fdw_options(fpinfo, existing_fpinfo, NULL); + fpinfo->user = existing_fpinfo->user; - userid = OidIsValid(baserel->userid) ? baserel->userid : GetUserId(); - fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid); + /* + * Don't try to execute anything on remote server for + * non-relation-based query + */ + fpinfo->use_remote_estimate = false; } else - fpinfo->user = NULL; + { + /* + * Extract user-settable option values. Note that per-table settings + * of use_remote_estimate, fetch_size and async_capable override + * per-server settings of them, respectively. + */ + fpinfo->use_remote_estimate = false; + fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST; + fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST; + fpinfo->shippable_extensions = NIL; + fpinfo->fetch_size = 100; + fpinfo->async_capable = false; + fpinfo->is_generated = false; + + apply_server_options(fpinfo); + apply_table_options(fpinfo); + + /* + * If the table or the server is configured to use remote estimates, + * identify which user to do remote access as during planning. This + * should match what ExecCheckPermissions() does. If we fail due to lack + * of permissions, the query would have failed at runtime anyway. + */ + if (fpinfo->use_remote_estimate) + { + Oid userid; + + userid = OidIsValid(baserel->userid) ? baserel->userid : GetUserId(); + fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid); + } + else + fpinfo->user = NULL; + } /* * Identify which baserestrictinfo clauses can be sent to the remote @@ -783,6 +844,9 @@ postgresGetForeignRelSize(PlannerInfo *root, fpinfo->hidden_subquery_rels = NULL; /* Set the relation index. */ fpinfo->relation_index = baserel->relid; + if (existing_fpinfo) + /* Mark fpinfo generated */ + fpinfo->is_generated = true; } /* @@ -1476,13 +1540,72 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION) + { + RangeTblFunction *rtfunc; + TupleDesc td; + Oid funcrettype; + int num_funcs, + attnum; + ListCell *lc, + *lctype, + *lcname; + bool functype_OK = true; + List *functypes = NIL; + + if (rte->funcordinality) + continue; + + num_funcs = list_length(rte->functions); + Assert(num_funcs >= 0); + + foreach(lc, rte->functions) + { + rtfunc = (RangeTblFunction *) lfirst(lc); + get_expr_result_type(rtfunc->funcexpr, &funcrettype, NULL); + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + { + functype_OK = false; + break; + } + functypes = lappend_oid(functypes, funcrettype); + } + if (!functype_OK) + continue; + td = CreateTemplateTupleDesc(num_funcs); + + /* + * funcrettype != RECORD, so we have only one return attribute per + * function + */ + Assert(list_length(rte->eref->colnames) == num_funcs); + attnum = 1; + forthree(lc, rte->functions, lctype, functypes, lcname, rte->eref->colnames) + { + char *colname; + + rtfunc = (RangeTblFunction *) lfirst(lc); + funcrettype = lfirst_oid(lctype); + colname = strVal(lfirst(lcname)); + + TupleDescInitEntry(td, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(td, (AttrNumber) attnum, + exprCollation(rtfunc->funcexpr)); + attnum++; + } + + assign_record_type_typmod(td); + att->atttypmod = td->tdtypmod; + } } return tupdesc; } @@ -1518,14 +1641,26 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. In case of a join or aggregate, scan RTEs + * until RTE_RELATION is found. We would get the same result from any. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte && rte->rtekind == RTE_RELATION) + break; + } + Assert(rte && rte->rtekind == RTE_RELATION); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -2566,8 +2701,30 @@ postgresPlanDirectModify(PlannerInfo *root, * node below. */ if (fscan->scan.scanrelid == 0) + { + ListCell *lc; + Var *tid_var = NULL; + + /* + * We should explicitly add tableoid to returning list if it's + * requested + */ + foreach(lc, processed_tlist) + { + TargetEntry *tle = lfirst_node(TargetEntry, lc); + Var *var = (Var *) tle->expr; + + if (IsA(var, Var) && (var->varattno == TableOidAttributeNumber) && (strcmp(tle->resname, "tableoid") == 0)) + { + tid_var = var; + break; + } + + } + returningList = build_remote_returning(resultRelation, rel, - returningList); + returningList, tid_var); + } } /* @@ -2889,21 +3046,66 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); - Assert(rte->rtekind == RTE_RELATION); /* This logic should agree with explain.c's ExplainTargetRel */ - relname = get_rel_name(rte->relid); - if (es->verbose) + if (rte->rtekind == RTE_RELATION) { - char *namespace; - - namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); - appendStringInfo(relations, "%s.%s", - quote_identifier(namespace), - quote_identifier(relname)); + // Note: relname may be uninitialized. + relname = get_rel_name(rte->relid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); + appendStringInfo(relations, "%s.%s", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfoString(relations, + quote_identifier(relname)); + } + else if (rte->rtekind == RTE_FUNCTION) + { + ListCell *lc; + int n; + bool first = true; + + + n = list_length(rte->functions); + + if (n > 1) + appendStringInfo(relations, "ROWS FROM("); + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (!first) + appendStringInfoString(relations, ", "); + else + first = false; + + if (IsA(rtfunc->funcexpr, FuncExpr)) + { + FuncExpr *funcexpr = (FuncExpr *) rtfunc->funcexpr; + Oid funcid = funcexpr->funcid; + + relname = get_func_name(funcid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name(get_func_namespace(funcid)); + appendStringInfo(relations, "%s.%s()", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfo(relations, "%s()", quote_identifier(relname)); + } + } + if (n > 1) + appendStringInfo(relations, ")"); } - else - appendStringInfoString(relations, - quote_identifier(relname)); refname = (char *) list_nth(es->rtable_names, rti - 1); if (refname == NULL) refname = rte->eref->aliasname; @@ -4427,7 +4629,7 @@ deallocate_query(PgFdwModifyState *fmstate) * UPDATE/DELETE .. RETURNING on a join directly */ static List * -build_remote_returning(Index rtindex, Relation rel, List *returningList) +build_remote_returning(Index rtindex, Relation rel, List *returningList, Var *tid) { bool have_wholerow = false; List *tlist = NIL; @@ -4436,6 +4638,19 @@ build_remote_returning(Index rtindex, Relation rel, List *returningList) Assert(returningList); + /* + * If tid is requested, add it to the returning list + */ + if (tid) + { + tlist = lappend(tlist, + makeTargetEntry((Expr *) tid, + list_length(tlist) + 1, + NULL, + false)); + + } + vars = pull_var_clause((Node *) returningList, PVC_INCLUDE_PLACEHOLDERS); /* @@ -4727,11 +4942,13 @@ init_returning_filter(PgFdwDirectModifyState *dmstate, if (attrno < 0) { /* - * We don't retrieve system columns other than ctid and oid. + * We don't retrieve system columns other than ctid and oid, + * but locally-generated tableoid can appear in returning + * list. */ if (attrno == SelfItemPointerAttributeNumber) dmstate->ctidAttno = i; - else + else if (attrno != TableOidAttributeNumber) Assert(false); dmstate->hasSystemCols = true; } @@ -5745,6 +5962,63 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid) return commands; } +/* + * Determine if foreignrel, not backed by foreign + * table, is fine to push down. + */ +static bool +is_nonrel_relinfo_ok(PlannerInfo *root, RelOptInfo *foreignrel) +{ + RangeTblEntry *rte; + RangeTblFunction *rtfunc; + TupleDesc tupdesc; + Oid funcrettype; + + rte = planner_rt_fetch(foreignrel->relid, root); + + if (!rte) + return false; + + Assert(foreignrel->fdw_private); + + if (rte->rtekind == RTE_FUNCTION) + { + ListCell *lc; + + /* + * WITH ORDINALITY pushdown is not implemented yet. + */ + if (rte->funcordinality) + return false; + + Assert(list_length(rte->functions) >= 1); + foreach(lc, rte->functions) + { + rtfunc = (RangeTblFunction *) lfirst(lc); + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + /* + * Remote server requires a well defined return type for a + * function pushdown. + */ + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID || funcrettype == VOIDOID) + return false; + + if (contain_var_clause(rtfunc->funcexpr) || + contain_mutable_functions(rtfunc->funcexpr) || + contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, foreignrel, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; + } + + return false; +} + /* * Check if reltarget is safe enough to push down semi-join. Reltarget is not * safe, if it contains references to inner rel relids, which do not belong to @@ -6477,6 +6751,43 @@ postgresGetForeignJoinPaths(PlannerInfo *root, /* XXX Consider parameterized paths for the join relation */ } +/* + * postgresTryShippableJoinPaths + * + * Try to add foreign join of foreign relation with shippable RTE. + */ +static void +postgresTryShippableJoinPaths(PlannerInfo *root, + RelOptInfo *joinrel, + RelOptInfo *outerrel, + RelOptInfo *innerrel, + JoinType jointype, + JoinPathExtraData *extra) +{ + PgFdwRelationInfo *fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + PgFdwRelationInfo *fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + + if (fpinfo_o == NULL) + /* Outer path is not foreign relation or foreign JOIN. */ + return; + + if (joinrel->fdwroutine != NULL || innerrel->reloptkind != RELOPT_BASEREL) + return; + + if (fpinfo_i == NULL || fpinfo_i->is_generated) + init_fpinfo(root, innerrel, InvalidOid, fpinfo_o); + + if (!is_nonrel_relinfo_ok(root, innerrel)) + return; + + joinrel->serverid = outerrel->serverid; + joinrel->userid = outerrel->userid; + joinrel->useridiscurrent = outerrel->useridiscurrent; + joinrel->fdwroutine = outerrel->fdwroutine; + + postgresGetForeignJoinPaths(root, joinrel, outerrel, innerrel, jointype, extra); +} + /* * Assess whether the aggregation, grouping and having operations can be pushed * down to the foreign server. As a side effect, save information we obtain in diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index 9e501660d1..772144d611 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -52,6 +52,12 @@ typedef struct PgFdwRelationInfo /* True means that the query_pathkeys is safe to push down */ bool qp_is_pushdown_safe; + /* + * True means that PgFdwRelationInfo is not extracted from catalogs, but + * generated + */ + bool is_generated; + /* Cost and selectivity of local_conds. */ QualCost local_conds_cost; Selectivity local_conds_sel; diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 372fe6dad1..6c717b58b8 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -4278,3 +4278,151 @@ SELECT CASE WHEN closed IS NOT false THEN 1 ELSE 0 END -- Clean up \set VERBOSITY default RESET debug_discard_caches; + +-- =================================================================== +-- test function scan pushdown +-- =================================================================== +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl'); +ALTER FOREIGN TABLE remote_tbl OPTIONS (use_remote_estimate 'true'); +CREATE TABLE base_tbl1 (c int, d text); +CREATE FOREIGN TABLE remote_tbl1 (c int, d text) + SERVER loopback OPTIONS (table_name 'base_tbl1'); +ALTER FOREIGN TABLE remote_tbl1 OPTIONS (use_remote_estimate 'true'); + +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO remote_tbl1 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE base_tbl; +ANALYZE base_tbl1; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n; + +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n; + +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a; + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*,n from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + +SELECT * from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + +CREATE OR REPLACE FUNCTION get_constant_texts() +RETURNS TABLE (text_value text) AS $$ +BEGIN + RETURN QUERY VALUES + ('text1'), + ('text4'); +END; +$$ LANGUAGE plpgsql IMMUTABLE; + +ALTER EXTENSION postgres_fdw ADD FUNCTION get_constant_texts(); +ALTER SERVER loopback OPTIONS (extensions 'postgres_fdw'); + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*, t.n from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + +SELECT r.*, t.txt from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + +-- Complex types +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx); + +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx) +ORDER BY r.a; + +-- DML +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +-- Test that local functions are not pushed down +CREATE OR REPLACE FUNCTION f(INTEGER) +RETURNS SETOF INTEGER +LANGUAGE sql AS 'select generate_series(1,$1);' IMMUTABLE; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, f(10) n +WHERE r.a = n; + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a AND n > 3; + +-- Test that a function that returns a record is not pushed down +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ SELECT (1,2)::record $$ language SQL IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD function f_ret_record(); + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + +DROP FUNCTION f(INTEGER); +ALTER EXTENSION postgres_fdw DROP FUNCTION get_constant_texts(); +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ret_record(); +DROP FUNCTION get_constant_texts(); +DROP FUNCTION f_ret_record(); +DROP TABLE base_tbl, base_tbl1; +DROP FOREIGN TABLE remote_tbl, remote_tbl1; + +-- Test that function WITH ORDINALITY is not pushed down +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) SERVER loopback OPTIONS (table_name 'base_tbl'); +INSERT INTO remote_tbl VALUES (1, 2), (2, 3), (3, 4), (5, 6); +ANALYZE remote_tbl; +SET enable_mergejoin TO false; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + +DROP TABLE base_tbl; +DROP FOREIGN TABLE remote_tbl; +RESET enable_mergejoin; diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c index 3971138480..57430a8165 100644 --- a/src/backend/optimizer/path/joinpath.c +++ b/src/backend/optimizer/path/joinpath.c @@ -333,6 +333,17 @@ add_paths_to_joinrel(PlannerInfo *root, outerrel, innerrel, jointype, &extra); + /* + * If push down of join is not possible we can try to join foreign + * relation with shippable RTE. In this case we have a chance to push down + * this join yet. + */ + else if (outerrel->fdwroutine && + outerrel->fdwroutine->TryShippableJoinPaths) + outerrel->fdwroutine->TryShippableJoinPaths(root, joinrel, + outerrel, innerrel, + jointype, &extra); + /* * 6. Finally, give extensions a chance to manipulate the path list. They * could add new paths (such as CustomPaths) by calling add_path(), or diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c index 91c7c4fe2f..088845c00f 100644 --- a/src/backend/optimizer/plan/setrefs.c +++ b/src/backend/optimizer/plan/setrefs.c @@ -552,7 +552,6 @@ add_rte_to_flat_rtable(PlannerGlobal *glob, List *rteperminfos, newrte->joinleftcols = NIL; newrte->joinrightcols = NIL; newrte->join_using_alias = NULL; - newrte->functions = NIL; newrte->tablefunc = NULL; newrte->values_lists = NIL; newrte->coltypes = NIL; diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h index fcde3876b2..0ccd6776a8 100644 --- a/src/include/foreign/fdwapi.h +++ b/src/include/foreign/fdwapi.h @@ -221,6 +221,7 @@ typedef struct FdwRoutine /* Functions for remote-join planning */ GetForeignJoinPaths_function GetForeignJoinPaths; + GetForeignJoinPaths_function TryShippableJoinPaths; /* Functions for remote upper-relation (post scan/join) planning */ GetForeignUpperPaths_function GetForeignUpperPaths; diff --git a/src/test/regress/expected/create_view.out b/src/test/regress/expected/create_view.out index f551624afb..3fda68bf7f 100644 --- a/src/test/regress/expected/create_view.out +++ b/src/test/regress/expected/create_view.out @@ -1681,10 +1681,10 @@ select pg_get_viewdef('tt14v', true); -- ... and you can even EXPLAIN it ... explain (verbose, costs off) select * from tt14v; - QUERY PLAN ----------------------------------------- + QUERY PLAN +-------------------------------------------- Function Scan on testviewschm2.tt14f t - Output: t.f1, t.f3, t.f4 + Output: t.f1, t."?dropped?column?", t.f4 Function Call: tt14f() (3 rows) -- 2.43.0
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2021-05-20 17:43 Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2021-06-15 13:15 ` Re: Function scan FDW pushdown Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
  2021-10-04 07:42   ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2024-11-05 16:11     ` Re: Function scan FDW pushdown g.kashkin@postgrespro.ru
@ 2025-08-05 21:32       ` Álvaro Herrera <alvherre@kurilemu.de>
  0 siblings, 0 replies; 36+ messages in thread

From: Álvaro Herrera @ 2025-08-05 21:32 UTC (permalink / raw)
  To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hello,

On 2024-Nov-05, g.kashkin@postgrespro.ru wrote:

> This is a long-overdue follow-up to the original patch.
> Note that this patch contains only the changes required for
> function scan pushdown, examples and code related to asymmetric
> join are dropped.

I've marked this as returned with feedback, as several months have
passed without a further version; the current one has a number of
gotchas, including some problematic coding detected by a compiler
warning, as well as unfinished design:

> The issue with setting newrte->functions to NIL still persists.
> [...]
> I am aware that the rte->functions will now be copied even on
> instances that don't utilize a FDW, but I don't see a way to solve it.
> Any suggestions are welcome.

Feel free to reopen this CF entry[1] once you're able to figure this out.

[1] https://commitfest.postgresql.org/patch/5470/

-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/





^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
@ 2026-03-18 12:08 Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2026-03-18 12:08 UTC (permalink / raw)
  To: Álvaro Herrera <alvherre@kurilemu.de>; +Cc: g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Álvaro Herrera писал(а) 2025-08-05 22:55:
> Hello,
> 
> On 2024-Nov-05, g.kashkin@postgrespro.ru wrote:
> 
>> This is a long-overdue follow-up to the original patch.
>> Note that this patch contains only the changes required for
>> function scan pushdown, examples and code related to asymmetric
>> join are dropped.
> 
> I've marked this as returned with feedback, as several months have
> passed without a further version; the current one has a number of
> gotchas, including some problematic coding detected by a compiler
> warning, as well as unfinished design:
> 
>> The issue with setting newrte->functions to NIL still persists.
>> [...]
>> I am aware that the rte->functions will now be copied even on
>> instances that don't utilize a FDW, but I don't see a way to solve it.
>> Any suggestions are welcome.
> 
> Feel free to reopen this CF entry[1] once you're able to figure this 
> out.
> 
> [1] https://commitfest.postgresql.org/patch/5470/

Hi.
I've updated patch with latest fixes, including more checks for corner 
cases.
Now function pushdown is forbidden for functions, returning sets of 
complex types
or which arguments contain parameters. Together with Gleb Kashkin we've 
also moved
information about functions to foreign scan private data. The tricky 
part here was
to get correct rti mappings after setrefs, but it seems we've managed to 
do it.
Also I've removed some changes, which are required only in presence of 
asymmetric
join.

Of course, I'm targeting PostgreSQL 20.
-- 
Best regards,
Alexander Pyhalov,
Postgres Professional

Attachments:

v2-0001-Push-join-with-function-scan-to-remote-server.patch (text/x-diff, 63.0K) download From 0ba2f8360667af9287b96c50686d74d925338898 Mon Sep 17 00:00:00 2001 From: Alexander Pyhalov <a.pyhalov@postgrespro.ru> Date: Wed, 18 Mar 2026 11:05:29 +0300 Subject: [PATCH] Push join with function scan to remote server The patch allows pushing joins with function RTEs to PostgreSQL data sources in general and postgres_fdw specifically. Co-authored-by: Gleb Kashkin <g.kashkin@postgrespro.ru> --- contrib/postgres_fdw/deparse.c | 192 ++++-- .../postgres_fdw/expected/postgres_fdw.out | 467 ++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 580 ++++++++++++++++-- contrib/postgres_fdw/postgres_fdw.h | 6 + contrib/postgres_fdw/sql/postgres_fdw.sql | 195 ++++++ src/backend/optimizer/path/joinpath.c | 11 + src/include/foreign/fdwapi.h | 1 + 7 files changed, 1348 insertions(+), 104 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index ebe2c3a596a..5653f00e8e9 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -154,6 +154,7 @@ static void deparseConst(Const *node, deparse_expr_cxt *context, int showtype); static void deparseParam(Param *node, deparse_expr_cxt *context); static void deparseSubscriptingRef(SubscriptingRef *node, deparse_expr_cxt *context); static void deparseFuncExpr(FuncExpr *node, deparse_expr_cxt *context); +static void deparseFuncColnames(StringInfo buf, int varno, RangeTblEntry *rte, bool qualify_col); static void deparseOpExpr(OpExpr *node, deparse_expr_cxt *context); static bool isPlainForeignVar(Expr *node, deparse_expr_cxt *context); static void deparseOperatorName(StringInfo buf, Form_pg_operator opform); @@ -1794,6 +1795,7 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, List **additional_conds, List **params_list) { PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + bool alias_required = use_alias; if (IS_JOIN_REL(foreignrel)) { @@ -2010,23 +2012,100 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, { RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); - /* - * Core code already has some lock on each rel being planned, so we - * can use NoLock here. - */ - Relation rel = table_open(rte->relid, NoLock); + Assert(rte->rtekind == RTE_RELATION || rte->rtekind == RTE_FUNCTION); + if (rte->rtekind == RTE_RELATION) + { + /* + * Core code already has some lock on each rel being planned, so + * we can use NoLock here. + */ + Relation rel = table_open(rte->relid, NoLock); - deparseRelation(buf, rel); + deparseRelation(buf, rel); + + table_close(rel, NoLock); + } + else if (rte->rtekind == RTE_FUNCTION) + { + RangeTblFunction *rtfunc; + deparse_expr_cxt context; + ListCell *lc; + bool first = true; + int n; + + n = list_length(rte->functions); + Assert(n >= 1); + + if (n > 1) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + if (!first) + appendStringInfoString(buf, ", "); + else + first = false; + + rtfunc = (RangeTblFunction *) lfirst(lc); + + context.root = root; + context.foreignrel = foreignrel; + context.scanrel = foreignrel; + context.buf = buf; + context.params_list = params_list; + + deparseExpr((Expr *) rtfunc->funcexpr, &context); + } + + if (n > 1) + appendStringInfoString(buf, ")"); + /* Function alias determines column names, and so it's required */ + alias_required = true; + } /* * Add a unique alias to avoid any conflict in relation names due to * pulled up subqueries in the query being built for a pushed down * join. */ - if (use_alias) + if (alias_required) + { appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, foreignrel->relid); + if (rte->rtekind == RTE_FUNCTION) + { + appendStringInfo(buf, " ("); + deparseFuncColnames(buf, 0, rte, false); + appendStringInfo(buf, ") "); + } + } + } +} - table_close(rel, NoLock); +/* + * Deparse function columns alias list + */ +static void +deparseFuncColnames(StringInfo buf, int varno, RangeTblEntry *rte, bool qualify_col) +{ + bool first = true; + ListCell *lc; + + Assert(rte); + Assert(rte->rtekind == RTE_FUNCTION); + Assert(rte->eref); + + foreach(lc, rte->eref->colnames) + { + char *colname = strVal(lfirst(lc)); + + if (colname[0] == '\0') + continue; + if (!first) + appendStringInfoString(buf, ","); + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); + appendStringInfoString(buf, quote_identifier(colname)); + first = false; } } @@ -2750,23 +2829,6 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, /* Required only to be passed down to deparseTargetList(). */ List *retrieved_attrs; - /* - * The lock on the relation will be held by upper callers, so it's - * fine to open it with no lock here. - */ - rel = table_open(rte->relid, NoLock); - - /* - * The local name of the foreign table can not be recognized by the - * foreign server and the table it references on foreign server might - * have different column ordering or different columns than those - * declared locally. Hence we have to deparse whole-row reference as - * ROW(columns referenced locally). Construct this by deparsing a - * "whole row" attribute. - */ - attrs_used = bms_add_member(NULL, - 0 - FirstLowInvalidHeapAttributeNumber); - /* * In case the whole-row reference is under an outer join then it has * to go NULL whenever the rest of the row goes NULL. Deparsing a join @@ -2781,16 +2843,43 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, } appendStringInfoString(buf, "ROW("); - deparseTargetList(buf, rte, varno, rel, false, attrs_used, qualify_col, - &retrieved_attrs); + if (rte->rtekind == RTE_RELATION) + { + /* + * The local name of the foreign table can not be recognized by + * the foreign server and the table it references on foreign + * server might have different column ordering or different + * columns than those declared locally. Hence we have to deparse + * whole-row reference as ROW(columns referenced locally). + * Construct this by deparsing a "whole row" attribute. + */ + attrs_used = bms_add_member(NULL, + 0 - FirstLowInvalidHeapAttributeNumber); + + /* + * The lock on the relation will be held by upper callers, so it's + * fine to open it with no lock here. + */ + rel = table_open(rte->relid, NoLock); + deparseTargetList(buf, rte, varno, rel, false, attrs_used, qualify_col, + &retrieved_attrs); + table_close(rel, NoLock); + bms_free(attrs_used); + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * Function call is translated as-is, function returns the same + * columns in the same order as on local server + */ + deparseFuncColnames(buf, varno, rte, qualify_col); + } appendStringInfoChar(buf, ')'); /* Complete the CASE WHEN statement started above. */ if (qualify_col) appendStringInfoString(buf, " END"); - table_close(rel, NoLock); - bms_free(attrs_used); } else { @@ -2805,29 +2894,40 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, * If it's a column of a foreign table, and it has the column_name FDW * option, use that value. */ - options = GetForeignColumnOptions(rte->relid, varattno); - foreach(lc, options) + if (rte->rtekind == RTE_RELATION) { - DefElem *def = (DefElem *) lfirst(lc); - - if (strcmp(def->defname, "column_name") == 0) + options = GetForeignColumnOptions(rte->relid, varattno); + foreach(lc, options) { - colname = defGetString(def); - break; + DefElem *def = (DefElem *) lfirst(lc); + + if (strcmp(def->defname, "column_name") == 0) + { + colname = defGetString(def); + break; + } } - } - /* - * If it's a column of a regular table or it doesn't have column_name - * FDW option, use attribute name. - */ - if (colname == NULL) - colname = get_attname(rte->relid, varattno, false); + /* + * If it's a column of a regular table or it doesn't have + * column_name FDW option, use attribute name. + */ + if (colname == NULL) + colname = get_attname(rte->relid, varattno, false); - if (qualify_col) - ADD_REL_QUALIFIER(buf, varno); + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); - appendStringInfoString(buf, quote_identifier(colname)); + appendStringInfoString(buf, quote_identifier(colname)); + } + else if (rte->rtekind == RTE_FUNCTION) + { + colname = get_rte_attribute_name(rte, varattno); + + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); + appendStringInfoString(buf, quote_identifier(colname)); + } } } diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index 0f5271d476e..f4c9c57d00f 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -12738,3 +12738,470 @@ SELECT server_name, -- Clean up \set VERBOSITY default RESET debug_discard_caches; +-- =================================================================== +-- test function scan pushdown +-- =================================================================== +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl'); +ALTER FOREIGN TABLE remote_tbl OPTIONS (use_remote_estimate 'true'); +CREATE TABLE base_tbl1 (c int, d text); +CREATE FOREIGN TABLE remote_tbl1 (c int, d text) + SERVER loopback OPTIONS (table_name 'base_tbl1'); +ALTER FOREIGN TABLE remote_tbl1 OPTIONS (use_remote_estimate 'true'); +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO remote_tbl1 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE base_tbl; +ANALYZE base_tbl1; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, n.n + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r2.n FROM (public.base_tbl r1 INNER JOIN unnest('{2,3,4}'::integer[]) r2 (n) ON (((r1.a = r2.n)))) +(4 rows) + +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n +ORDER BY r.a; + a | b | n +---+---+--- + 2 | 4 | 2 + 3 | 6 | 3 + 4 | 8 | 4 +(3 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: n.n, r.a, r.b + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.n, r2.a, r2.b FROM (public.base_tbl r2 INNER JOIN unnest('{2,3,4}'::integer[]) r1 (n) ON (((r2.a = r1.n)))) +(4 rows) + +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n +ORDER BY r.a; + n | a | b +---+---+--- + 2 | 2 | 4 + 3 | 3 | 6 + 4 | 4 | 8 +(3 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: r.a, r.b, r1.c, r1.d, n.n + Relations: ((public.remote_tbl r) INNER JOIN (public.remote_tbl1 r1)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r2.c, r2.d, r3.n FROM ((public.base_tbl r1 INNER JOIN public.base_tbl1 r2 ON (((r1.a = r2.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r1.a = r3.n)))) +(4 rows) + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a +ORDER BY r.a; + a | b | c | d | n +---+---+---+-------+--- + 3 | 6 | 3 | text3 | 3 + 4 | 8 | 4 | text4 | 4 +(2 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*,n from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, n.n + Relations: ((public.remote_tbl r) INNER JOIN (public.remote_tbl1 r1)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r3.n FROM ((public.base_tbl r1 INNER JOIN public.base_tbl1 r2 ON (((r1.a = r2.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r1.a = r3.n)) AND ((r3.n > 3)))) +(4 rows) + +SELECT * from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + a | b | c | d | n +---+---+---+-------+--- + 4 | 8 | 4 | text4 | 4 +(1 row) + +CREATE OR REPLACE FUNCTION get_constant_texts() +RETURNS TABLE (text_value text) AS $$ +BEGIN + RETURN QUERY VALUES + ('text1'), + ('text4'); +END; +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION get_constant_texts(); +ALTER SERVER loopback OPTIONS (extensions 'postgres_fdw'); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*, t.n from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.c, r.d, t.n + Relations: (public.remote_tbl1 r) INNER JOIN (ROWS FROM(pg_catalog.unnest(), public.get_constant_texts()) t) + Remote SQL: SELECT r1.c, r1.d, r2.n FROM (public.base_tbl1 r1 INNER JOIN ROWS FROM (unnest('{3,4}'::integer[]), public.get_constant_texts()) r2 (n,txt) ON (((r1.c = r2.n)) AND ((r2.txt = r1.d)))) +(4 rows) + +SELECT r.*, t.txt from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + c | d | txt +---+-------+------- + 4 | text4 | text4 +(1 row) + +-- Complex types +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx); + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, t.bx + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() t) + Remote SQL: SELECT r1.a, r1.b, r2.bx FROM (public.base_tbl r1 INNER JOIN unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) ON (((r1.a = area(r2.bx))))) +(4 rows) + +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx) +ORDER BY r.a; + a | b | bx +----+----+--------------- + 24 | 48 | (2,3),(-2,-3) +(1 row) + +-- DML +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + -> Foreign Update + Remote SQL: UPDATE public.base_tbl r1 SET b = 5 FROM unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) WHERE ((r1.a = area(r2.bx))) RETURNING r1.a, r1.b +(4 rows) + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + a | b +----+--- + 24 | 5 +(1 row) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + Remote SQL: UPDATE public.base_tbl SET b = $2 WHERE ctid = $1 RETURNING a, b + -> Foreign Scan + Output: CASE WHEN (random() >= '0'::double precision) THEN 5 ELSE 0 END, r.ctid, r.*, t.* + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() t) + Remote SQL: SELECT r1.ctid, CASE WHEN (r1.*)::text IS NOT NULL THEN ROW(r1.a, r1.b) END, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2.bx) END FROM (public.base_tbl r1 INNER JOIN unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) ON (((r1.a = area(r2.bx))))) FOR UPDATE OF r1 + -> Hash Join + Output: r.ctid, r.*, t.* + Hash Cond: ((r.a)::double precision = area(t.bx)) + -> Foreign Scan on public.remote_tbl r + Output: r.ctid, r.*, r.a + Remote SQL: SELECT a, b, ctid FROM public.base_tbl FOR UPDATE + -> Hash + Output: t.*, t.bx + -> Function Scan on pg_catalog.unnest t + Output: t.*, t.bx + Function Call: unnest('{(2,3),(-2,-3)}'::box[]) +(18 rows) + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + a | b +----+--- + 24 | 5 +(1 row) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Update on public.remote_tbl r + Output: r.a, r.b + -> Foreign Update + Remote SQL: UPDATE public.base_tbl r1 SET b = 5 FROM ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) WHERE ((r1.a >= r2.l)) AND ((r1.a <= area(r2.bx))) RETURNING r1.a, r1.b +(4 rows) + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + a | b +----+--- + 10 | 5 + 11 | 5 + 12 | 5 + 13 | 5 + 14 | 5 + 15 | 5 + 16 | 5 + 17 | 5 + 18 | 5 + 19 | 5 + 20 | 5 + 21 | 5 + 22 | 5 + 23 | 5 + 25 | 5 + 26 | 5 + 27 | 5 + 28 | 5 + 24 | 5 +(19 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + Remote SQL: UPDATE public.base_tbl SET b = $2 WHERE ctid = $1 RETURNING a, b + -> Foreign Scan + Output: CASE WHEN (random() >= '0'::double precision) THEN 5 ELSE 0 END, r.ctid, r.*, t.* + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM(pg_catalog.unnest(), pg_catalog.unnest()) t) + Remote SQL: SELECT r1.ctid, CASE WHEN (r1.*)::text IS NOT NULL THEN ROW(r1.a, r1.b) END, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2.l,r2.bx) END FROM (public.base_tbl r1 INNER JOIN ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) ON (((r1.a >= r2.l)) AND ((r1.a <= area(r2.bx))))) FOR UPDATE OF r1 + -> Nested Loop + Output: r.ctid, r.*, t.* + Join Filter: ((r.a >= t.l) AND ((r.a)::double precision <= area(t.bx))) + -> Foreign Scan on public.remote_tbl r + Output: r.ctid, r.*, r.a + Remote SQL: SELECT a, b, ctid FROM public.base_tbl FOR UPDATE + -> Function Scan on t + Output: t.*, t.l, t.bx + Function Call: unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[]) +(16 rows) + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + a | b +----+--- + 10 | 5 + 11 | 5 + 12 | 5 + 13 | 5 + 14 | 5 + 15 | 5 + 16 | 5 + 17 | 5 + 18 | 5 + 19 | 5 + 20 | 5 + 21 | 5 + 22 | 5 + 23 | 5 + 25 | 5 + 26 | 5 + 27 | 5 + 28 | 5 + 24 | 5 +(19 rows) + +-- Test that local functions are not pushed down +CREATE OR REPLACE FUNCTION f(INTEGER) +RETURNS SETOF INTEGER +LANGUAGE sql AS 'select generate_series(1,$1);' IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, f(10) n +WHERE r.a = n; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: r.a, r.b, (generate_series(1, 10)) + Hash Cond: (r.a = (generate_series(1, 10))) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a, b FROM public.base_tbl + -> Hash + Output: (generate_series(1, 10)) + -> ProjectSet + Output: generate_series(1, 10) + -> Result +(11 rows) + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a AND n > 3; + a | b | c | d | n +---+---+---+-------+--- + 4 | 8 | 4 | text4 | 4 +(1 row) + +-- Test that a function that returns a record is not pushed down +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ SELECT (1,2)::record $$ language SQL IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD function f_ret_record(); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +----------------------------------------------------------------------------- + Nested Loop + Output: s.* + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl WHERE ((a = $1::integer)) +(8 rows) + +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + s +------- + (1,2) +(1 row) + +DROP FUNCTION f(INTEGER); +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ret_record(); +DROP FUNCTION f_ret_record(); +-- Test that a function that returns composite type is not pushed down +CREATE TYPE c1 AS (i int, j int); +CREATE OR REPLACE FUNCTION f_ret_c1(int) RETURNS SETOF c1 AS $$ begin return next '(3,3)'::c1 ; end $$ language plpgsql immutable; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ret_c1(int); +ALTER EXTENSION postgres_fdw ADD TYPE c1; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT f FROM remote_tbl r, ROWS FROM (f_ret_c1(2), f_ret_c1(2)) AS f(i, j, k,l) WHERE f.i=r.a; + QUERY PLAN +----------------------------------------------------------------------------- + Merge Join + Output: f.* + Merge Cond: (r.a = f.i) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl ORDER BY a ASC NULLS LAST + -> Sort + Output: f.*, f.i + Sort Key: f.i + -> Function Scan on f + Output: f.*, f.i + Function Call: f_ret_c1(2), f_ret_c1(2) +(12 rows) + +SELECT f FROM remote_tbl r, ROWS FROM (f_ret_c1(2), f_ret_c1(2)) AS f(i, j, k,l) WHERE f.i=r.a; + f +----------- + (3,3,3,3) +(1 row) + +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ret_c1(int); +ALTER EXTENSION postgres_fdw DROP TYPE c1; +DROP FUNCTION f_ret_c1(int); +DROP TYPE c1; +DELETE FROM base_tbl; +-- Test that function with parameters in arguments is not pushed down +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,10) g; +ANALYZE base_tbl; +ANALYZE remote_tbl; +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int +LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD function f(INTEGER); +-- no foreign join +set enable_material = off; +-- Make local function scan not so attractive +ALTER SERVER loopback OPTIONS (ADD fdw_tuple_cost '1000'); +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) WHERE f=r2.a LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + QUERY PLAN +----------------------------------------------------------------------- + Sort + Output: s.a, s.b + Sort Key: s.a + CTE s + -> Nested Loop + Output: r1.a, r1.b + -> Foreign Scan on public.remote_tbl r1 + Output: r1.a, r1.b + Remote SQL: SELECT a, b FROM public.base_tbl + -> Limit + Output: NULL::integer + -> Nested Loop + Output: NULL::integer + Join Filter: (r2.a = f.f) + -> Foreign Scan on public.remote_tbl r2 + Output: r2.a, r2.b + Remote SQL: SELECT a FROM public.base_tbl + -> Function Scan on public.f + Output: f.f + Function Call: f(r1.a) + -> CTE Scan on s + Output: s.a, s.b +(22 rows) + +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) WHERE f=r2.a LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + a | b +----+---- + 1 | 2 + 2 | 4 + 3 | 6 + 4 | 8 + 5 | 10 + 6 | 12 + 7 | 14 + 8 | 16 + 9 | 18 + 10 | 20 +(10 rows) + +reset enable_material; +ALTER SERVER loopback OPTIONS (DROP fdw_tuple_cost); +ALTER EXTENSION postgres_fdw DROP function f(INTEGER); +ALTER EXTENSION postgres_fdw DROP FUNCTION get_constant_texts(); +DROP FUNCTION get_constant_texts(); +DROP TABLE base_tbl, base_tbl1; +DROP FOREIGN TABLE remote_tbl, remote_tbl1; +-- Test that function WITH ORDINALITY is not pushed down +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) SERVER loopback OPTIONS (table_name 'base_tbl'); +INSERT INTO remote_tbl VALUES (1, 2), (2, 3), (3, 4), (5, 6); +ANALYZE remote_tbl; +SET enable_mergejoin TO false; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + QUERY PLAN +------------------------------------------------------------------------ + Hash Join + Output: remote_tbl.a, remote_tbl.b, unnest.unnest, unnest.ordinality + Hash Cond: (remote_tbl.a = unnest.unnest) + -> Foreign Scan on public.remote_tbl + Output: remote_tbl.a, remote_tbl.b + Remote SQL: SELECT a, b FROM public.base_tbl + -> Hash + Output: unnest.unnest, unnest.ordinality + -> Function Scan on pg_catalog.unnest + Output: unnest.unnest, unnest.ordinality + Function Call: unnest('{1,2}'::integer[]) +(11 rows) + +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + a | b | unnest | ordinality +---+---+--------+------------ + 1 | 2 | 1 | 1 + 2 | 3 | 2 | 2 +(2 rows) + +DROP TABLE base_tbl; +DROP FOREIGN TABLE remote_tbl; +RESET enable_mergejoin; diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 41e47cc795b..2753a187c89 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -38,6 +38,7 @@ #include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "optimizer/tlist.h" +#include "optimizer/clauses.h" #include "parser/parsetree.h" #include "postgres_fdw.h" #include "storage/latch.h" @@ -49,6 +50,7 @@ #include "utils/rel.h" #include "utils/sampling.h" #include "utils/selfuncs.h" +#include "utils/typcache.h" PG_MODULE_MAGIC_EXT( .name = "postgres_fdw", @@ -85,6 +87,17 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of function oid, return type and collation for each function per + * rte + */ + FdwScanPrivateFunctions, + + /* + * Minimum RT index, used in foreign scan + */ + FdwScanPrivateMinRTIndex }; /* @@ -121,6 +134,8 @@ enum FdwModifyPrivateIndex * 2) Boolean flag showing if the remote query has a RETURNING clause * 3) Integer list of attribute numbers retrieved by RETURNING, if any * 4) Boolean flag showing if we set the command es_processed + * 5) Data about used RTE_FUNCTIONS - their oid, return type and collation + * 6) Minimum RT index, used in foreign scan */ enum FdwDirectModifyPrivateIndex { @@ -132,6 +147,14 @@ enum FdwDirectModifyPrivateIndex FdwDirectModifyPrivateRetrievedAttrs, /* set-processed flag (as a Boolean node) */ FdwDirectModifyPrivateSetProcessed, + + /* + * List of function oid, return type and collation for each function per + * rte + */ + FdwDirectModifyPrivateFunctions, + /* Minimum RT index, used in foreign scan */ + FdwDirectModifyPrivateMinRTIndex }; /* @@ -411,6 +434,14 @@ static void postgresGetForeignJoinPaths(PlannerInfo *root, RelOptInfo *innerrel, JoinType jointype, JoinPathExtraData *extra); + +static void postgresTryShippableJoinPaths(PlannerInfo *root, + RelOptInfo *joinrel, + RelOptInfo *outerrel, + RelOptInfo *innerrel, + JoinType jointype, + JoinPathExtraData *extra); + static bool postgresRecheckForeignScan(ForeignScanState *node, TupleTableSlot *slot); static void postgresGetForeignUpperPaths(PlannerInfo *root, @@ -547,6 +578,15 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_i); static int get_batch_size_option(Relation rel); +static bool is_nonrel_relinfo_ok(PlannerInfo *root, RelOptInfo *foreignrel); +static void init_fpinfo(PlannerInfo *root, + RelOptInfo *baserel, + Oid foreigntableid, + PgFdwRelationInfo *existing_fpinfo); +static bool contain_param_walker(Node *node, void *arg); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); /* * Foreign-data wrapper handler function: return a struct with pointers @@ -602,6 +642,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS) /* Support functions for join push-down */ routine->GetForeignJoinPaths = postgresGetForeignJoinPaths; + routine->TryShippableJoinPaths = postgresTryShippableJoinPaths; /* Support functions for upper relation push-down */ routine->GetForeignUpperPaths = postgresGetForeignUpperPaths; @@ -626,10 +667,32 @@ static void postgresGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid) +{ + init_fpinfo(root, baserel, foreigntableid, NULL); +} + +/* + * init_fpinfo + * + * Either initialize fpinfo based on foreign table or generate one, based on + * existing fpinfo. + * Also estimate # of rows and width of the result of the scan. + * + * We should consider the effect of all baserestrictinfo clauses here, but + * not any join clauses. + */ +static void +init_fpinfo(PlannerInfo *root, + RelOptInfo *baserel, + Oid foreigntableid, + PgFdwRelationInfo *existing_fpinfo) { PgFdwRelationInfo *fpinfo; ListCell *lc; + Assert(existing_fpinfo || foreigntableid != InvalidOid); + Assert(existing_fpinfo == NULL || foreigntableid == InvalidOid); + /* * We use PgFdwRelationInfo to pass various information to subsequent * functions. @@ -640,40 +703,64 @@ postgresGetForeignRelSize(PlannerInfo *root, /* Base foreign tables need to be pushed down always. */ fpinfo->pushdown_safe = true; - /* Look up foreign-table catalog info. */ - fpinfo->table = GetForeignTable(foreigntableid); - fpinfo->server = GetForeignServer(fpinfo->table->serverid); - - /* - * Extract user-settable option values. Note that per-table settings of - * use_remote_estimate, fetch_size and async_capable override per-server - * settings of them, respectively. - */ - fpinfo->use_remote_estimate = false; - fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST; - fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST; - fpinfo->shippable_extensions = NIL; - fpinfo->fetch_size = 100; - fpinfo->async_capable = false; - - apply_server_options(fpinfo); - apply_table_options(fpinfo); + if (existing_fpinfo) + { + /* We don't have any table, related to query */ + fpinfo->table = NULL; + fpinfo->server = existing_fpinfo->server; + } + else + { + /* Look up foreign-table catalog info. */ + fpinfo->table = GetForeignTable(foreigntableid); + fpinfo->server = GetForeignServer(fpinfo->table->serverid); + } - /* - * If the table or the server is configured to use remote estimates, - * identify which user to do remote access as during planning. This - * should match what ExecCheckPermissions() does. If we fail due to lack - * of permissions, the query would have failed at runtime anyway. - */ - if (fpinfo->use_remote_estimate) + if (existing_fpinfo) { - Oid userid; + merge_fdw_options(fpinfo, existing_fpinfo, NULL); + fpinfo->user = existing_fpinfo->user; - userid = OidIsValid(baserel->userid) ? baserel->userid : GetUserId(); - fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid); + /* + * Don't try to execute anything on remote server for + * non-relation-based query + */ + fpinfo->use_remote_estimate = false; } else - fpinfo->user = NULL; + { + /* + * Extract user-settable option values. Note that per-table settings + * of use_remote_estimate, fetch_size and async_capable override + * per-server settings of them, respectively. + */ + fpinfo->use_remote_estimate = false; + fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST; + fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST; + fpinfo->shippable_extensions = NIL; + fpinfo->fetch_size = 100; + fpinfo->async_capable = false; + fpinfo->is_generated = false; + + apply_server_options(fpinfo); + apply_table_options(fpinfo); + + /* + * If the table or the server is configured to use remote estimates, + * identify which user to do remote access as during planning. This + * should match what ExecCheckPermissions() does. If we fail due to + * lack of permissions, the query would have failed at runtime anyway. + */ + if (fpinfo->use_remote_estimate) + { + Oid userid; + + userid = OidIsValid(baserel->userid) ? baserel->userid : GetUserId(); + fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid); + } + else + fpinfo->user = NULL; + } /* * Identify which baserestrictinfo clauses can be sent to the remote @@ -788,6 +875,9 @@ postgresGetForeignRelSize(PlannerInfo *root, fpinfo->hidden_subquery_rels = NULL; /* Set the relation index. */ fpinfo->relation_index = baserel->relid; + if (existing_fpinfo) + /* Mark fpinfo generated */ + fpinfo->is_generated = true; } /* @@ -1009,6 +1099,112 @@ get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel) return useful_pathkeys_list; } +/* + * get_functions_data + * Collect info about function return types for executor + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + int i; + Relids fscan_relids; + + fscan_relids = get_base_relids(root, rel); + + /* + * Preserve function oid and return type for executor. Each element of + * rtfuncdata is a List, corresponding to RangeTblEntry functions. Element + * of the list is a list of three-elements lists. The first one is + * function oid (for explain), the second and the third - are actual + * result types and collation oids. + */ + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + + /* + * The place in rtfuncdata should match rtindex, so we add empty "0" + * member. Also avoid examining functions, which are not present in + * foreign scan. + */ + if (rte != NULL && i > 0 && bms_is_member(i, fscan_relids) && rte->rtekind == RTE_FUNCTION) + { + ListCell *lc; + List *funcdata = NIL; + + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc; + Oid funccollation; + TupleDesc tupdesc; + Oid funcrettype; + Oid funcid = InvalidOid; + + rtfunc = (RangeTblFunction *) lfirst(lc); + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + /* Should never happen */ + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, "could not determine return type for function"); + + funccollation = exprCollation(rtfunc->funcexpr); + + if (IsA(rtfunc->funcexpr, FuncExpr)) + funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid; + + funcdata = lappend(funcdata, list_make3( + makeInteger(funcid), + makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + else + rtfuncdata = lappend(rtfuncdata, NULL); + } + + return rtfuncdata; +} + +/* + * get_base_relids + * Get base relids, used in foreign scan + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + relids = bms_difference(relids, root->outer_join_rels); + + return relids; +} + +/* + * get_min_base_rti + * Get minimum base RTI, used in foreign scan + * + * Actually, this copies logic from create_foreignscan_plan(). + * However, we need this data prior to create_foreignscan_plan() + * does its job. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + /* * postgresGetForeignPaths * Create possible scan paths for a scan on the foreign table @@ -1423,6 +1619,12 @@ postgresGetForeignPlan(PlannerInfo *root, if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + /* We can use this value to determine rtoffset. */ + fdw_private = lappend(fdw_private, makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1445,7 +1647,7 @@ postgresGetForeignPlan(PlannerInfo *root, * Construct a tuple descriptor for the scan tuples handled by a foreign join. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1481,13 +1683,65 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* Whole row var references function RTE. Determine its rowtype. */ + TupleDesc rte_tupdesc; + int num_funcs, + attnum; + ListCell *lc, + *lcname; + List *funcdata; + + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + + num_funcs = list_length(funcdata); + Assert(num_funcs >= 0); + + /* + * funcrettype != RECORD, so we have only one return attribute per + * function + */ + Assert(list_length(rte->eref->colnames) == num_funcs); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc, funcdata, lcname, rte->eref->colnames) + { + List *fdata; + char *colname; + Oid funcrettype; + Oid funcretcollation; + + fdata = lfirst_node(List, lc); + + colname = strVal(lfirst(lcname)); + + funcrettype = lsecond_node(Integer, fdata)->ival; + funcretcollation = lthird_node(Integer, fdata)->ival; + + /* Should never happen */ + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, "could not determine return type for function"); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funcretcollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1502,7 +1756,7 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; PgFdwScanState *fsstate; - RangeTblEntry *rte; + RangeTblEntry *rte = NULL; Oid userid; ForeignTable *table; UserMapping *user; @@ -1523,14 +1777,28 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. In case of a join or aggregate, scan RTEs + * until RTE_RELATION is found. We would get the same result from any. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte && rte->rtekind == RTE_RELATION) + break; + } + /* Should never happen */ + if (rte == NULL || rte->rtekind != RTE_RELATION) + elog(ERROR, "can't find relation rte for foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1573,8 +1841,16 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = list_nth(fsplan->fdw_private, FdwScanPrivateFunctions); + Integer *minrti = list_nth(fsplan->fdw_private, FdwScanPrivateMinRTIndex); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - minrti->ival; + + /* Index sanity checks */ + Assert(minrti->ival > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2614,6 +2890,13 @@ postgresPlanDirectModify(PlannerInfo *root, makeBoolean((retrieved_attrs != NIL)), retrieved_attrs, makeBoolean(plan->canSetTag)); + fscan->fdw_private = lappend(fscan->fdw_private, get_functions_data(root, foreignrel)); + + /* + * We can use this value to determine rtoffset. It was already calculated + * while building foreign scan plan + */ + fscan->fdw_private = lappend(fscan->fdw_private, makeInteger(bms_next_member(fscan->fs_base_relids, -1))); /* * Update the foreign-join-related fields. @@ -2727,7 +3010,17 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + List *rtfuncdata = list_nth(fsplan->fdw_private, FdwDirectModifyPrivateFunctions); + Integer *minrti = list_nth(fsplan->fdw_private, FdwDirectModifyPrivateMinRTIndex); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - minrti->ival; + + /* Index sanity checks */ + Assert(minrti->ival > 0); + Assert(rtoffset >= 0); + + tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -2840,7 +3133,7 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_nth(fdw_private, FdwScanPrivateRelations)) { StringInfoData relations; char *rawrelations; @@ -2884,31 +3177,89 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) { int rti = strtol(ptr, &ptr, 10); RangeTblEntry *rte; - char *relname; + char *relname = NULL; char *refname; rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); - Assert(rte->rtekind == RTE_RELATION); + /* This logic should agree with explain.c's ExplainTargetRel */ - relname = get_rel_name(rte->relid); - if (es->verbose) + if (rte->rtekind == RTE_RELATION) { - char *namespace; - - namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); - appendStringInfo(&relations, "%s.%s", - quote_identifier(namespace), - quote_identifier(relname)); + /* Note: relname may be uninitialized. */ + relname = get_rel_name(rte->relid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); + appendStringInfo(&relations, "%s.%s", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfoString(&relations, + quote_identifier(relname)); } - else - appendStringInfoString(&relations, - quote_identifier(relname)); + else if (rte->rtekind == RTE_FUNCTION) + { + ListCell *lc; + int n; + bool first = true; + List *rtfuncdata = list_nth(fdw_private, FdwScanPrivateFunctions); + List *funcdata; +#ifdef USE_ASSERT_CHECKING + Integer *fdw_private_min_rti = list_nth(fdw_private, FdwScanPrivateMinRTIndex); + + /* Check that fdw_private_min_rti calculation is correct. */ + Assert(fdw_private_min_rti->ival == minrti); +#endif + + funcdata = list_nth(rtfuncdata, rti - rtoffset); + + n = list_length(funcdata); + + if (n > 1) + appendStringInfo(&relations, "ROWS FROM("); + foreach(lc, funcdata) + { + List *funcinfo; + Oid funcid; + + funcinfo = (List *) lfirst(lc); + + if (!first) + appendStringInfoString(&relations, ", "); + else + first = false; + + funcid = linitial_node(Integer, funcinfo)->ival; + + if (OidIsValid(funcid)) + { + relname = get_func_name(funcid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name(get_func_namespace(funcid)); + appendStringInfo(&relations, "%s.%s()", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfo(&relations, "%s()", quote_identifier(relname)); + } + } + if (n > 1) + appendStringInfo(&relations, ")"); + } + refname = (char *) list_nth(es->rtable_names, rti - 1); if (refname == NULL) refname = rte->eref->aliasname; - if (strcmp(refname, relname) != 0) + if (relname == NULL || strcmp(refname, relname) != 0) appendStringInfo(&relations, " %s", quote_identifier(refname)); } @@ -5652,6 +6003,69 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid) return commands; } +/* + * Determine if foreignrel, not backed by foreign + * table, is fine to push down. + */ +static bool +is_nonrel_relinfo_ok(PlannerInfo *root, RelOptInfo *foreignrel) +{ + RangeTblEntry *rte; + RangeTblFunction *rtfunc; + TupleDesc tupdesc; + Oid funcrettype; + + rte = planner_rt_fetch(foreignrel->relid, root); + + if (!rte) + return false; + + Assert(foreignrel->fdw_private); + + if (rte->rtekind == RTE_FUNCTION) + { + ListCell *lc; + TypeFuncClass functypclass; + + /* + * WITH ORDINALITY pushdown is not implemented yet. + */ + if (rte->funcordinality) + return false; + + Assert(list_length(rte->functions) >= 1); + foreach(lc, rte->functions) + { + rtfunc = (RangeTblFunction *) lfirst(lc); + + functypclass = get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + /* + * Remote server requires a well defined return type for a + * function pushdown. Also get_tupdesc_for_join_scan_tuples() + * doesn't expect RTE_FUNCTION to return several attributes. + */ + if (functypclass != TYPEFUNC_SCALAR) + return false; + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID || funcrettype == VOIDOID) + return false; + + if (contain_var_clause(rtfunc->funcexpr) || + contain_mutable_functions(rtfunc->funcexpr) || + contain_subplans(rtfunc->funcexpr) || + contain_param_walker(rtfunc->funcexpr, NULL)) + return false; + if (!is_foreign_expr(root, foreignrel, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; + } + + return false; +} + /* * Check if reltarget is safe enough to push down semi-join. Reltarget is not * safe, if it contains references to inner rel relids, which do not belong to @@ -6400,6 +6814,43 @@ postgresGetForeignJoinPaths(PlannerInfo *root, /* XXX Consider parameterized paths for the join relation */ } +/* + * postgresTryShippableJoinPaths + * + * Try to add foreign join of foreign relation with shippable RTE. + */ +static void +postgresTryShippableJoinPaths(PlannerInfo *root, + RelOptInfo *joinrel, + RelOptInfo *outerrel, + RelOptInfo *innerrel, + JoinType jointype, + JoinPathExtraData *extra) +{ + PgFdwRelationInfo *fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + PgFdwRelationInfo *fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + + if (fpinfo_o == NULL) + /* Outer path is not foreign relation or foreign JOIN. */ + return; + + if (joinrel->fdwroutine != NULL || innerrel->reloptkind != RELOPT_BASEREL) + return; + + if (fpinfo_i == NULL || fpinfo_i->is_generated) + init_fpinfo(root, innerrel, InvalidOid, fpinfo_o); + + if (!is_nonrel_relinfo_ok(root, innerrel)) + return; + + joinrel->serverid = outerrel->serverid; + joinrel->userid = outerrel->userid; + joinrel->useridiscurrent = outerrel->useridiscurrent; + joinrel->fdwroutine = outerrel->fdwroutine; + + postgresGetForeignJoinPaths(root, joinrel, outerrel, innerrel, jointype, extra); +} + /* * Assess whether the aggregation, grouping and having operations can be pushed * down to the foreign server. As a side effect, save information we obtain in @@ -7887,3 +8338,16 @@ get_batch_size_option(Relation rel) return batch_size; } + +/* + * Checks if expression contains parameters + */ +static bool +contain_param_walker(Node *node, void *arg) +{ + if (node == NULL) + return false; + if (IsA(node, Param)) + return true; + return expression_tree_walker(node, contain_param_walker, NULL); +} diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..b4d3e2bfe10 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -52,6 +52,12 @@ typedef struct PgFdwRelationInfo /* True means that the query_pathkeys is safe to push down */ bool qp_is_pushdown_safe; + /* + * True means that PgFdwRelationInfo is not extracted from catalogs, but + * generated + */ + bool is_generated; + /* Cost and selectivity of local_conds. */ QualCost local_conds_cost; Selectivity local_conds_sel; diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 49ed797e8ef..758371bcf30 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -4442,3 +4442,198 @@ SELECT server_name, -- Clean up \set VERBOSITY default RESET debug_discard_caches; + +-- =================================================================== +-- test function scan pushdown +-- =================================================================== +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl'); +ALTER FOREIGN TABLE remote_tbl OPTIONS (use_remote_estimate 'true'); +CREATE TABLE base_tbl1 (c int, d text); +CREATE FOREIGN TABLE remote_tbl1 (c int, d text) + SERVER loopback OPTIONS (table_name 'base_tbl1'); +ALTER FOREIGN TABLE remote_tbl1 OPTIONS (use_remote_estimate 'true'); + +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO remote_tbl1 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE base_tbl; +ANALYZE base_tbl1; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n; + +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n; + +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a; + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*,n from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + +SELECT * from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + +CREATE OR REPLACE FUNCTION get_constant_texts() +RETURNS TABLE (text_value text) AS $$ +BEGIN + RETURN QUERY VALUES + ('text1'), + ('text4'); +END; +$$ LANGUAGE plpgsql IMMUTABLE; + +ALTER EXTENSION postgres_fdw ADD FUNCTION get_constant_texts(); +ALTER SERVER loopback OPTIONS (extensions 'postgres_fdw'); + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*, t.n from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + +SELECT r.*, t.txt from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + +-- Complex types +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx); + +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx) +ORDER BY r.a; + +-- DML +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +-- Test that local functions are not pushed down +CREATE OR REPLACE FUNCTION f(INTEGER) +RETURNS SETOF INTEGER +LANGUAGE sql AS 'select generate_series(1,$1);' IMMUTABLE; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, f(10) n +WHERE r.a = n; + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a AND n > 3; + +-- Test that a function that returns a record is not pushed down +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ SELECT (1,2)::record $$ language SQL IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD function f_ret_record(); + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + +DROP FUNCTION f(INTEGER); +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ret_record(); +DROP FUNCTION f_ret_record(); + +-- Test that a function that returns composite type is not pushed down +CREATE TYPE c1 AS (i int, j int); +CREATE OR REPLACE FUNCTION f_ret_c1(int) RETURNS SETOF c1 AS $$ begin return next '(3,3)'::c1 ; end $$ language plpgsql immutable; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ret_c1(int); +ALTER EXTENSION postgres_fdw ADD TYPE c1; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT f FROM remote_tbl r, ROWS FROM (f_ret_c1(2), f_ret_c1(2)) AS f(i, j, k,l) WHERE f.i=r.a; +SELECT f FROM remote_tbl r, ROWS FROM (f_ret_c1(2), f_ret_c1(2)) AS f(i, j, k,l) WHERE f.i=r.a; + +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ret_c1(int); +ALTER EXTENSION postgres_fdw DROP TYPE c1; +DROP FUNCTION f_ret_c1(int); +DROP TYPE c1; + +DELETE FROM base_tbl; + +-- Test that function with parameters in arguments is not pushed down +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,10) g; +ANALYZE base_tbl; +ANALYZE remote_tbl; + +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int +LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD function f(INTEGER); + +-- no foreign join +set enable_material = off; +-- Make local function scan not so attractive +ALTER SERVER loopback OPTIONS (ADD fdw_tuple_cost '1000'); +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) WHERE f=r2.a LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) WHERE f=r2.a LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; +reset enable_material; +ALTER SERVER loopback OPTIONS (DROP fdw_tuple_cost); + +ALTER EXTENSION postgres_fdw DROP function f(INTEGER); + +ALTER EXTENSION postgres_fdw DROP FUNCTION get_constant_texts(); +DROP FUNCTION get_constant_texts(); +DROP TABLE base_tbl, base_tbl1; +DROP FOREIGN TABLE remote_tbl, remote_tbl1; + +-- Test that function WITH ORDINALITY is not pushed down +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) SERVER loopback OPTIONS (table_name 'base_tbl'); +INSERT INTO remote_tbl VALUES (1, 2), (2, 3), (3, 4), (5, 6); +ANALYZE remote_tbl; +SET enable_mergejoin TO false; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + +DROP TABLE base_tbl; +DROP FOREIGN TABLE remote_tbl; +RESET enable_mergejoin; diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c index 044560da7bf..559f00ffddd 100644 --- a/src/backend/optimizer/path/joinpath.c +++ b/src/backend/optimizer/path/joinpath.c @@ -365,6 +365,17 @@ add_paths_to_joinrel(PlannerInfo *root, outerrel, innerrel, save_jointype, &extra); + /* + * If push down of join is not possible we can try to join foreign + * relation with shippable RTE. In this case we have a chance to push down + * this join yet. + */ + else if ((extra.pgs_mask & PGS_FOREIGNJOIN) != 0 && outerrel->fdwroutine && + outerrel->fdwroutine->TryShippableJoinPaths) + outerrel->fdwroutine->TryShippableJoinPaths(root, joinrel, + outerrel, innerrel, + save_jointype, &extra); + /* * 6. Finally, give extensions a chance to manipulate the path list. They * could add new paths (such as CustomPaths) by calling add_path(), or diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h index 96b6f692d2a..c772042c218 100644 --- a/src/include/foreign/fdwapi.h +++ b/src/include/foreign/fdwapi.h @@ -221,6 +221,7 @@ typedef struct FdwRoutine /* Functions for remote-join planning */ GetForeignJoinPaths_function GetForeignJoinPaths; + GetForeignJoinPaths_function TryShippableJoinPaths; /* Functions for remote upper-relation (post scan/join) planning */ GetForeignUpperPaths_function GetForeignUpperPaths; -- 2.43.0
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-05-06 06:59 ` Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2026-05-06 06:59 UTC (permalink / raw)
  To: Álvaro Herrera <alvherre@kurilemu.de>; +Cc: g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Alexander Pyhalov писал(а) 2026-03-18 15:08:
> Álvaro Herrera писал(а) 2025-08-05 22:55:
>> Hello,
>> 
>> On 2024-Nov-05, g.kashkin@postgrespro.ru wrote:
>> 
>>> This is a long-overdue follow-up to the original patch.
>>> Note that this patch contains only the changes required for
>>> function scan pushdown, examples and code related to asymmetric
>>> join are dropped.
>> 
>> I've marked this as returned with feedback, as several months have
>> passed without a further version; the current one has a number of
>> gotchas, including some problematic coding detected by a compiler
>> warning, as well as unfinished design:
>> 
>>> The issue with setting newrte->functions to NIL still persists.
>>> [...]
>>> I am aware that the rte->functions will now be copied even on
>>> instances that don't utilize a FDW, but I don't see a way to solve 
>>> it.
>>> Any suggestions are welcome.
>> 
>> Feel free to reopen this CF entry[1] once you're able to figure this 
>> out.
>> 
>> [1] https://commitfest.postgresql.org/patch/5470/
> 
> Hi.
> I've updated patch with latest fixes, including more checks for corner 
> cases.
> Now function pushdown is forbidden for functions, returning sets of 
> complex types
> or which arguments contain parameters. Together with Gleb Kashkin we've 
> also moved
> information about functions to foreign scan private data. The tricky 
> part here was
> to get correct rti mappings after setrefs, but it seems we've managed 
> to do it.
> Also I've removed some changes, which are required only in presence of 
> asymmetric
> join.
> 
> Of course, I'm targeting PostgreSQL 20.

Hi.  Updated patch to apply cleanly after recent changes.
-- 
Best regards,
Alexander Pyhalov,
Postgres Professional

Attachments:

v3-0001-Push-join-with-function-scan-to-remote-server.patch (text/x-diff, 63.2K) download From b0033119eae5dd382095cf8cb6a63be2439636f1 Mon Sep 17 00:00:00 2001 From: Alexander Pyhalov <a.pyhalov@postgrespro.ru> Date: Wed, 6 May 2026 09:56:56 +0300 Subject: [PATCH] Push join with function scan to remote server The patch allows pushing joins with function RTEs to PostgreSQL data sources in general and postgres_fdw specifically. Co-authored-by: Gleb Kashkin <g.kashkin@postgrespro.ru> --- contrib/postgres_fdw/deparse.c | 192 ++++-- .../postgres_fdw/expected/postgres_fdw.out | 467 ++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 580 ++++++++++++++++-- contrib/postgres_fdw/postgres_fdw.h | 6 + contrib/postgres_fdw/sql/postgres_fdw.sql | 195 ++++++ src/backend/optimizer/path/joinpath.c | 11 + src/include/foreign/fdwapi.h | 1 + 7 files changed, 1348 insertions(+), 104 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 2dcc6c8af1b..4b31f2a1c9f 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -154,6 +154,7 @@ static void deparseConst(Const *node, deparse_expr_cxt *context, int showtype); static void deparseParam(Param *node, deparse_expr_cxt *context); static void deparseSubscriptingRef(SubscriptingRef *node, deparse_expr_cxt *context); static void deparseFuncExpr(FuncExpr *node, deparse_expr_cxt *context); +static void deparseFuncColnames(StringInfo buf, int varno, RangeTblEntry *rte, bool qualify_col); static void deparseOpExpr(OpExpr *node, deparse_expr_cxt *context); static bool isPlainForeignVar(Expr *node, deparse_expr_cxt *context); static void deparseOperatorName(StringInfo buf, Form_pg_operator opform); @@ -1794,6 +1795,7 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, List **additional_conds, List **params_list) { PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + bool alias_required = use_alias; if (IS_JOIN_REL(foreignrel)) { @@ -2010,23 +2012,100 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, { RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); - /* - * Core code already has some lock on each rel being planned, so we - * can use NoLock here. - */ - Relation rel = table_open(rte->relid, NoLock); + Assert(rte->rtekind == RTE_RELATION || rte->rtekind == RTE_FUNCTION); + if (rte->rtekind == RTE_RELATION) + { + /* + * Core code already has some lock on each rel being planned, so + * we can use NoLock here. + */ + Relation rel = table_open(rte->relid, NoLock); - deparseRelation(buf, rel); + deparseRelation(buf, rel); + + table_close(rel, NoLock); + } + else if (rte->rtekind == RTE_FUNCTION) + { + RangeTblFunction *rtfunc; + deparse_expr_cxt context; + ListCell *lc; + bool first = true; + int n; + + n = list_length(rte->functions); + Assert(n >= 1); + + if (n > 1) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + if (!first) + appendStringInfoString(buf, ", "); + else + first = false; + + rtfunc = (RangeTblFunction *) lfirst(lc); + + context.root = root; + context.foreignrel = foreignrel; + context.scanrel = foreignrel; + context.buf = buf; + context.params_list = params_list; + + deparseExpr((Expr *) rtfunc->funcexpr, &context); + } + + if (n > 1) + appendStringInfoString(buf, ")"); + /* Function alias determines column names, and so it's required */ + alias_required = true; + } /* * Add a unique alias to avoid any conflict in relation names due to * pulled up subqueries in the query being built for a pushed down * join. */ - if (use_alias) + if (alias_required) + { appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, foreignrel->relid); + if (rte->rtekind == RTE_FUNCTION) + { + appendStringInfo(buf, " ("); + deparseFuncColnames(buf, 0, rte, false); + appendStringInfo(buf, ") "); + } + } + } +} - table_close(rel, NoLock); +/* + * Deparse function columns alias list + */ +static void +deparseFuncColnames(StringInfo buf, int varno, RangeTblEntry *rte, bool qualify_col) +{ + bool first = true; + ListCell *lc; + + Assert(rte); + Assert(rte->rtekind == RTE_FUNCTION); + Assert(rte->eref); + + foreach(lc, rte->eref->colnames) + { + char *colname = strVal(lfirst(lc)); + + if (colname[0] == '\0') + continue; + if (!first) + appendStringInfoString(buf, ","); + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); + appendStringInfoString(buf, quote_identifier(colname)); + first = false; } } @@ -2750,23 +2829,6 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, /* Required only to be passed down to deparseTargetList(). */ List *retrieved_attrs; - /* - * The lock on the relation will be held by upper callers, so it's - * fine to open it with no lock here. - */ - rel = table_open(rte->relid, NoLock); - - /* - * The local name of the foreign table can not be recognized by the - * foreign server and the table it references on foreign server might - * have different column ordering or different columns than those - * declared locally. Hence we have to deparse whole-row reference as - * ROW(columns referenced locally). Construct this by deparsing a - * "whole row" attribute. - */ - attrs_used = bms_add_member(NULL, - 0 - FirstLowInvalidHeapAttributeNumber); - /* * In case the whole-row reference is under an outer join then it has * to go NULL whenever the rest of the row goes NULL. Deparsing a join @@ -2781,16 +2843,43 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, } appendStringInfoString(buf, "ROW("); - deparseTargetList(buf, rte, varno, rel, false, attrs_used, qualify_col, - &retrieved_attrs); + if (rte->rtekind == RTE_RELATION) + { + /* + * The local name of the foreign table can not be recognized by + * the foreign server and the table it references on foreign + * server might have different column ordering or different + * columns than those declared locally. Hence we have to deparse + * whole-row reference as ROW(columns referenced locally). + * Construct this by deparsing a "whole row" attribute. + */ + attrs_used = bms_add_member(NULL, + 0 - FirstLowInvalidHeapAttributeNumber); + + /* + * The lock on the relation will be held by upper callers, so it's + * fine to open it with no lock here. + */ + rel = table_open(rte->relid, NoLock); + deparseTargetList(buf, rte, varno, rel, false, attrs_used, qualify_col, + &retrieved_attrs); + table_close(rel, NoLock); + bms_free(attrs_used); + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * Function call is translated as-is, function returns the same + * columns in the same order as on local server + */ + deparseFuncColnames(buf, varno, rte, qualify_col); + } appendStringInfoChar(buf, ')'); /* Complete the CASE WHEN statement started above. */ if (qualify_col) appendStringInfoString(buf, " END"); - table_close(rel, NoLock); - bms_free(attrs_used); } else { @@ -2805,29 +2894,40 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, * If it's a column of a foreign table, and it has the column_name FDW * option, use that value. */ - options = GetForeignColumnOptions(rte->relid, varattno); - foreach(lc, options) + if (rte->rtekind == RTE_RELATION) { - DefElem *def = (DefElem *) lfirst(lc); - - if (strcmp(def->defname, "column_name") == 0) + options = GetForeignColumnOptions(rte->relid, varattno); + foreach(lc, options) { - colname = defGetString(def); - break; + DefElem *def = (DefElem *) lfirst(lc); + + if (strcmp(def->defname, "column_name") == 0) + { + colname = defGetString(def); + break; + } } - } - /* - * If it's a column of a regular table or it doesn't have column_name - * FDW option, use attribute name. - */ - if (colname == NULL) - colname = get_attname(rte->relid, varattno, false); + /* + * If it's a column of a regular table or it doesn't have + * column_name FDW option, use attribute name. + */ + if (colname == NULL) + colname = get_attname(rte->relid, varattno, false); - if (qualify_col) - ADD_REL_QUALIFIER(buf, varno); + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); - appendStringInfoString(buf, quote_identifier(colname)); + appendStringInfoString(buf, quote_identifier(colname)); + } + else if (rte->rtekind == RTE_FUNCTION) + { + colname = get_rte_attribute_name(rte, varattno); + + if (qualify_col) + ADD_REL_QUALIFIER(buf, varno); + appendStringInfoString(buf, quote_identifier(colname)); + } } } diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index aaffcf31271..643aa22e64b 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -13053,3 +13053,470 @@ RESET client_min_messages; DROP FUNCTION wait_for_backend_termination(int); DROP FOREIGN TABLE remote_backend_pid; DROP VIEW my_backend_pid; +-- =================================================================== +-- test function scan pushdown +-- =================================================================== +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl'); +ALTER FOREIGN TABLE remote_tbl OPTIONS (use_remote_estimate 'true'); +CREATE TABLE base_tbl1 (c int, d text); +CREATE FOREIGN TABLE remote_tbl1 (c int, d text) + SERVER loopback OPTIONS (table_name 'base_tbl1'); +ALTER FOREIGN TABLE remote_tbl1 OPTIONS (use_remote_estimate 'true'); +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO remote_tbl1 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE base_tbl; +ANALYZE base_tbl1; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, n.n + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r2.n FROM (public.base_tbl r1 INNER JOIN unnest('{2,3,4}'::integer[]) r2 (n) ON (((r1.a = r2.n)))) +(4 rows) + +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n +ORDER BY r.a; + a | b | n +---+---+--- + 2 | 4 | 2 + 3 | 6 | 3 + 4 | 8 | 4 +(3 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: n.n, r.a, r.b + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.n, r2.a, r2.b FROM (public.base_tbl r2 INNER JOIN unnest('{2,3,4}'::integer[]) r1 (n) ON (((r2.a = r1.n)))) +(4 rows) + +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n +ORDER BY r.a; + n | a | b +---+---+--- + 2 | 2 | 4 + 3 | 3 | 6 + 4 | 4 | 8 +(3 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: r.a, r.b, r1.c, r1.d, n.n + Relations: ((public.remote_tbl r) INNER JOIN (public.remote_tbl1 r1)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r2.c, r2.d, r3.n FROM ((public.base_tbl r1 INNER JOIN public.base_tbl1 r2 ON (((r1.a = r2.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r1.a = r3.n)))) +(4 rows) + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a +ORDER BY r.a; + a | b | c | d | n +---+---+---+-------+--- + 3 | 6 | 3 | text3 | 3 + 4 | 8 | 4 | text4 | 4 +(2 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*,n from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, n.n + Relations: ((public.remote_tbl r) INNER JOIN (public.remote_tbl1 r1)) INNER JOIN (pg_catalog.unnest() n) + Remote SQL: SELECT r1.a, r1.b, r3.n FROM ((public.base_tbl r1 INNER JOIN public.base_tbl1 r2 ON (((r1.a = r2.c)))) INNER JOIN unnest('{3,4}'::integer[]) r3 (n) ON (((r1.a = r3.n)) AND ((r3.n > 3)))) +(4 rows) + +SELECT * from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + a | b | c | d | n +---+---+---+-------+--- + 4 | 8 | 4 | text4 | 4 +(1 row) + +CREATE OR REPLACE FUNCTION get_constant_texts() +RETURNS TABLE (text_value text) AS $$ +BEGIN + RETURN QUERY VALUES + ('text1'), + ('text4'); +END; +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION get_constant_texts(); +ALTER SERVER loopback OPTIONS (extensions 'postgres_fdw'); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*, t.n from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.c, r.d, t.n + Relations: (public.remote_tbl1 r) INNER JOIN (ROWS FROM(pg_catalog.unnest(), public.get_constant_texts()) t) + Remote SQL: SELECT r1.c, r1.d, r2.n FROM (public.base_tbl1 r1 INNER JOIN ROWS FROM (unnest('{3,4}'::integer[]), public.get_constant_texts()) r2 (n,txt) ON (((r1.c = r2.n)) AND ((r2.txt = r1.d)))) +(4 rows) + +SELECT r.*, t.txt from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + c | d | txt +---+-------+------- + 4 | text4 | text4 +(1 row) + +-- Complex types +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx); + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: r.a, r.b, t.bx + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() t) + Remote SQL: SELECT r1.a, r1.b, r2.bx FROM (public.base_tbl r1 INNER JOIN unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) ON (((r1.a = area(r2.bx))))) +(4 rows) + +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx) +ORDER BY r.a; + a | b | bx +----+----+--------------- + 24 | 48 | (2,3),(-2,-3) +(1 row) + +-- DML +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + -> Foreign Update + Remote SQL: UPDATE public.base_tbl r1 SET b = 5 FROM unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) WHERE ((r1.a = area(r2.bx))) RETURNING r1.a, r1.b +(4 rows) + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + a | b +----+--- + 24 | 5 +(1 row) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + Remote SQL: UPDATE public.base_tbl SET b = $2 WHERE ctid = $1 RETURNING a, b + -> Foreign Scan + Output: CASE WHEN (random() >= '0'::double precision) THEN 5 ELSE 0 END, r.ctid, r.*, t.* + Relations: (public.remote_tbl r) INNER JOIN (pg_catalog.unnest() t) + Remote SQL: SELECT r1.ctid, CASE WHEN (r1.*)::text IS NOT NULL THEN ROW(r1.a, r1.b) END, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2.bx) END FROM (public.base_tbl r1 INNER JOIN unnest('{(2,3),(-2,-3)}'::box[]) r2 (bx) ON (((r1.a = area(r2.bx))))) FOR UPDATE OF r1 + -> Hash Join + Output: r.ctid, r.*, t.* + Hash Cond: ((r.a)::double precision = area(t.bx)) + -> Foreign Scan on public.remote_tbl r + Output: r.ctid, r.*, r.a + Remote SQL: SELECT a, b, ctid FROM public.base_tbl FOR UPDATE + -> Hash + Output: t.*, t.bx + -> Function Scan on pg_catalog.unnest t + Output: t.*, t.bx + Function Call: unnest('{(2,3),(-2,-3)}'::box[]) +(18 rows) + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + a | b +----+--- + 24 | 5 +(1 row) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Update on public.remote_tbl r + Output: r.a, r.b + -> Foreign Update + Remote SQL: UPDATE public.base_tbl r1 SET b = 5 FROM ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) WHERE ((r1.a >= r2.l)) AND ((r1.a <= area(r2.bx))) RETURNING r1.a, r1.b +(4 rows) + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + a | b +----+--- + 10 | 5 + 11 | 5 + 12 | 5 + 13 | 5 + 14 | 5 + 15 | 5 + 16 | 5 + 17 | 5 + 18 | 5 + 19 | 5 + 20 | 5 + 21 | 5 + 22 | 5 + 23 | 5 + 25 | 5 + 26 | 5 + 27 | 5 + 28 | 5 + 24 | 5 +(19 rows) + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Update on public.remote_tbl r + Output: r.a, r.b + Remote SQL: UPDATE public.base_tbl SET b = $2 WHERE ctid = $1 RETURNING a, b + -> Foreign Scan + Output: CASE WHEN (random() >= '0'::double precision) THEN 5 ELSE 0 END, r.ctid, r.*, t.* + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM(pg_catalog.unnest(), pg_catalog.unnest()) t) + Remote SQL: SELECT r1.ctid, CASE WHEN (r1.*)::text IS NOT NULL THEN ROW(r1.a, r1.b) END, CASE WHEN (r2.*)::text IS NOT NULL THEN ROW(r2.l,r2.bx) END FROM (public.base_tbl r1 INNER JOIN ROWS FROM (unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[])) r2 (l,bx) ON (((r1.a >= r2.l)) AND ((r1.a <= area(r2.bx))))) FOR UPDATE OF r1 + -> Nested Loop + Output: r.ctid, r.*, t.* + Join Filter: ((r.a >= t.l) AND ((r.a)::double precision <= area(t.bx))) + -> Foreign Scan on public.remote_tbl r + Output: r.ctid, r.*, r.a + Remote SQL: SELECT a, b, ctid FROM public.base_tbl FOR UPDATE + -> Function Scan on t + Output: t.*, t.l, t.bx + Function Call: unnest('{10,20}'::integer[]), unnest('{(2,3),(-2,-4);(1,2),(-2,-3)}'::box[]) +(16 rows) + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + a | b +----+--- + 10 | 5 + 11 | 5 + 12 | 5 + 13 | 5 + 14 | 5 + 15 | 5 + 16 | 5 + 17 | 5 + 18 | 5 + 19 | 5 + 20 | 5 + 21 | 5 + 22 | 5 + 23 | 5 + 25 | 5 + 26 | 5 + 27 | 5 + 28 | 5 + 24 | 5 +(19 rows) + +-- Test that local functions are not pushed down +CREATE OR REPLACE FUNCTION f(INTEGER) +RETURNS SETOF INTEGER +LANGUAGE sql AS 'select generate_series(1,$1);' IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, f(10) n +WHERE r.a = n; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: r.a, r.b, (generate_series(1, 10)) + Hash Cond: (r.a = (generate_series(1, 10))) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a, b FROM public.base_tbl + -> Hash + Output: (generate_series(1, 10)) + -> ProjectSet + Output: generate_series(1, 10) + -> Result +(11 rows) + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a AND n > 3; + a | b | c | d | n +---+---+---+-------+--- + 4 | 8 | 4 | text4 | 4 +(1 row) + +-- Test that a function that returns a record is not pushed down +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ SELECT (1,2)::record $$ language SQL IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD function f_ret_record(); +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +----------------------------------------------------------------------------- + Nested Loop + Output: s.* + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl WHERE ((a = $1::integer)) +(8 rows) + +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + s +------- + (1,2) +(1 row) + +DROP FUNCTION f(INTEGER); +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ret_record(); +DROP FUNCTION f_ret_record(); +-- Test that a function that returns composite type is not pushed down +CREATE TYPE c1 AS (i int, j int); +CREATE OR REPLACE FUNCTION f_ret_c1(int) RETURNS SETOF c1 AS $$ begin return next '(3,3)'::c1 ; end $$ language plpgsql immutable; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ret_c1(int); +ALTER EXTENSION postgres_fdw ADD TYPE c1; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT f FROM remote_tbl r, ROWS FROM (f_ret_c1(2), f_ret_c1(2)) AS f(i, j, k,l) WHERE f.i=r.a; + QUERY PLAN +----------------------------------------------------------------------------- + Merge Join + Output: f.* + Merge Cond: (r.a = f.i) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl ORDER BY a ASC NULLS LAST + -> Sort + Output: f.*, f.i + Sort Key: f.i + -> Function Scan on f + Output: f.*, f.i + Function Call: f_ret_c1(2), f_ret_c1(2) +(12 rows) + +SELECT f FROM remote_tbl r, ROWS FROM (f_ret_c1(2), f_ret_c1(2)) AS f(i, j, k,l) WHERE f.i=r.a; + f +----------- + (3,3,3,3) +(1 row) + +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ret_c1(int); +ALTER EXTENSION postgres_fdw DROP TYPE c1; +DROP FUNCTION f_ret_c1(int); +DROP TYPE c1; +DELETE FROM base_tbl; +-- Test that function with parameters in arguments is not pushed down +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,10) g; +ANALYZE base_tbl; +ANALYZE remote_tbl; +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int +LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD function f(INTEGER); +-- no foreign join +set enable_material = off; +-- Make local function scan not so attractive +ALTER SERVER loopback OPTIONS (ADD fdw_tuple_cost '1000'); +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) WHERE f=r2.a LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + QUERY PLAN +----------------------------------------------------------------------- + Sort + Output: s.a, s.b + Sort Key: s.a + CTE s + -> Nested Loop + Output: r1.a, r1.b + -> Foreign Scan on public.remote_tbl r1 + Output: r1.a, r1.b + Remote SQL: SELECT a, b FROM public.base_tbl + -> Limit + Output: NULL::integer + -> Nested Loop + Output: NULL::integer + Join Filter: (r2.a = f.f) + -> Foreign Scan on public.remote_tbl r2 + Output: r2.a, r2.b + Remote SQL: SELECT a FROM public.base_tbl + -> Function Scan on public.f + Output: f.f + Function Call: f(r1.a) + -> CTE Scan on s + Output: s.a, s.b +(22 rows) + +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) WHERE f=r2.a LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + a | b +----+---- + 1 | 2 + 2 | 4 + 3 | 6 + 4 | 8 + 5 | 10 + 6 | 12 + 7 | 14 + 8 | 16 + 9 | 18 + 10 | 20 +(10 rows) + +reset enable_material; +ALTER SERVER loopback OPTIONS (DROP fdw_tuple_cost); +ALTER EXTENSION postgres_fdw DROP function f(INTEGER); +ALTER EXTENSION postgres_fdw DROP FUNCTION get_constant_texts(); +DROP FUNCTION get_constant_texts(); +DROP TABLE base_tbl, base_tbl1; +DROP FOREIGN TABLE remote_tbl, remote_tbl1; +-- Test that function WITH ORDINALITY is not pushed down +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) SERVER loopback OPTIONS (table_name 'base_tbl'); +INSERT INTO remote_tbl VALUES (1, 2), (2, 3), (3, 4), (5, 6); +ANALYZE remote_tbl; +SET enable_mergejoin TO false; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + QUERY PLAN +------------------------------------------------------------------------ + Hash Join + Output: remote_tbl.a, remote_tbl.b, unnest.unnest, unnest.ordinality + Hash Cond: (remote_tbl.a = unnest.unnest) + -> Foreign Scan on public.remote_tbl + Output: remote_tbl.a, remote_tbl.b + Remote SQL: SELECT a, b FROM public.base_tbl + -> Hash + Output: unnest.unnest, unnest.ordinality + -> Function Scan on pg_catalog.unnest + Output: unnest.unnest, unnest.ordinality + Function Call: unnest('{1,2}'::integer[]) +(11 rows) + +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + a | b | unnest | ordinality +---+---+--------+------------ + 1 | 2 | 1 | 1 + 2 | 3 | 2 | 2 +(2 rows) + +DROP TABLE base_tbl; +DROP FOREIGN TABLE remote_tbl; +RESET enable_mergejoin; diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index c42cb690c7b..ca08536f45e 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -40,6 +40,7 @@ #include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "optimizer/tlist.h" +#include "optimizer/clauses.h" #include "parser/parsetree.h" #include "postgres_fdw.h" #include "statistics/statistics.h" @@ -52,6 +53,7 @@ #include "utils/rel.h" #include "utils/sampling.h" #include "utils/selfuncs.h" +#include "utils/typcache.h" PG_MODULE_MAGIC_EXT( .name = "postgres_fdw", @@ -88,6 +90,17 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of function oid, return type and collation for each function per + * rte + */ + FdwScanPrivateFunctions, + + /* + * Minimum RT index, used in foreign scan + */ + FdwScanPrivateMinRTIndex }; /* @@ -124,6 +137,8 @@ enum FdwModifyPrivateIndex * 2) Boolean flag showing if the remote query has a RETURNING clause * 3) Integer list of attribute numbers retrieved by RETURNING, if any * 4) Boolean flag showing if we set the command es_processed + * 5) Data about used RTE_FUNCTIONS - their oid, return type and collation + * 6) Minimum RT index, used in foreign scan */ enum FdwDirectModifyPrivateIndex { @@ -135,6 +150,14 @@ enum FdwDirectModifyPrivateIndex FdwDirectModifyPrivateRetrievedAttrs, /* set-processed flag (as a Boolean node) */ FdwDirectModifyPrivateSetProcessed, + + /* + * List of function oid, return type and collation for each function per + * rte + */ + FdwDirectModifyPrivateFunctions, + /* Minimum RT index, used in foreign scan */ + FdwDirectModifyPrivateMinRTIndex }; /* @@ -593,6 +616,14 @@ static void postgresGetForeignJoinPaths(PlannerInfo *root, RelOptInfo *innerrel, JoinType jointype, JoinPathExtraData *extra); + +static void postgresTryShippableJoinPaths(PlannerInfo *root, + RelOptInfo *joinrel, + RelOptInfo *outerrel, + RelOptInfo *innerrel, + JoinType jointype, + JoinPathExtraData *extra); + static bool postgresRecheckForeignScan(ForeignScanState *node, TupleTableSlot *slot); static void postgresGetForeignUpperPaths(PlannerInfo *root, @@ -760,6 +791,15 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_i); static int get_batch_size_option(Relation rel); +static bool is_nonrel_relinfo_ok(PlannerInfo *root, RelOptInfo *foreignrel); +static void init_fpinfo(PlannerInfo *root, + RelOptInfo *baserel, + Oid foreigntableid, + PgFdwRelationInfo *existing_fpinfo); +static bool contain_param_walker(Node *node, void *arg); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); /* * Foreign-data wrapper handler function: return a struct with pointers @@ -816,6 +856,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS) /* Support functions for join push-down */ routine->GetForeignJoinPaths = postgresGetForeignJoinPaths; + routine->TryShippableJoinPaths = postgresTryShippableJoinPaths; /* Support functions for upper relation push-down */ routine->GetForeignUpperPaths = postgresGetForeignUpperPaths; @@ -840,10 +881,32 @@ static void postgresGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid) +{ + init_fpinfo(root, baserel, foreigntableid, NULL); +} + +/* + * init_fpinfo + * + * Either initialize fpinfo based on foreign table or generate one, based on + * existing fpinfo. + * Also estimate # of rows and width of the result of the scan. + * + * We should consider the effect of all baserestrictinfo clauses here, but + * not any join clauses. + */ +static void +init_fpinfo(PlannerInfo *root, + RelOptInfo *baserel, + Oid foreigntableid, + PgFdwRelationInfo *existing_fpinfo) { PgFdwRelationInfo *fpinfo; ListCell *lc; + Assert(existing_fpinfo || foreigntableid != InvalidOid); + Assert(existing_fpinfo == NULL || foreigntableid == InvalidOid); + /* * We use PgFdwRelationInfo to pass various information to subsequent * functions. @@ -854,40 +917,64 @@ postgresGetForeignRelSize(PlannerInfo *root, /* Base foreign tables need to be pushed down always. */ fpinfo->pushdown_safe = true; - /* Look up foreign-table catalog info. */ - fpinfo->table = GetForeignTable(foreigntableid); - fpinfo->server = GetForeignServer(fpinfo->table->serverid); - - /* - * Extract user-settable option values. Note that per-table settings of - * use_remote_estimate, fetch_size and async_capable override per-server - * settings of them, respectively. - */ - fpinfo->use_remote_estimate = false; - fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST; - fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST; - fpinfo->shippable_extensions = NIL; - fpinfo->fetch_size = 100; - fpinfo->async_capable = false; - - apply_server_options(fpinfo); - apply_table_options(fpinfo); + if (existing_fpinfo) + { + /* We don't have any table, related to query */ + fpinfo->table = NULL; + fpinfo->server = existing_fpinfo->server; + } + else + { + /* Look up foreign-table catalog info. */ + fpinfo->table = GetForeignTable(foreigntableid); + fpinfo->server = GetForeignServer(fpinfo->table->serverid); + } - /* - * If the table or the server is configured to use remote estimates, - * identify which user to do remote access as during planning. This - * should match what ExecCheckPermissions() does. If we fail due to lack - * of permissions, the query would have failed at runtime anyway. - */ - if (fpinfo->use_remote_estimate) + if (existing_fpinfo) { - Oid userid; + merge_fdw_options(fpinfo, existing_fpinfo, NULL); + fpinfo->user = existing_fpinfo->user; - userid = OidIsValid(baserel->userid) ? baserel->userid : GetUserId(); - fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid); + /* + * Don't try to execute anything on remote server for + * non-relation-based query + */ + fpinfo->use_remote_estimate = false; } else - fpinfo->user = NULL; + { + /* + * Extract user-settable option values. Note that per-table settings + * of use_remote_estimate, fetch_size and async_capable override + * per-server settings of them, respectively. + */ + fpinfo->use_remote_estimate = false; + fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST; + fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST; + fpinfo->shippable_extensions = NIL; + fpinfo->fetch_size = 100; + fpinfo->async_capable = false; + fpinfo->is_generated = false; + + apply_server_options(fpinfo); + apply_table_options(fpinfo); + + /* + * If the table or the server is configured to use remote estimates, + * identify which user to do remote access as during planning. This + * should match what ExecCheckPermissions() does. If we fail due to + * lack of permissions, the query would have failed at runtime anyway. + */ + if (fpinfo->use_remote_estimate) + { + Oid userid; + + userid = OidIsValid(baserel->userid) ? baserel->userid : GetUserId(); + fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid); + } + else + fpinfo->user = NULL; + } /* * Identify which baserestrictinfo clauses can be sent to the remote @@ -1002,6 +1089,9 @@ postgresGetForeignRelSize(PlannerInfo *root, fpinfo->hidden_subquery_rels = NULL; /* Set the relation index. */ fpinfo->relation_index = baserel->relid; + if (existing_fpinfo) + /* Mark fpinfo generated */ + fpinfo->is_generated = true; } /* @@ -1223,6 +1313,112 @@ get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel) return useful_pathkeys_list; } +/* + * get_functions_data + * Collect info about function return types for executor + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + int i; + Relids fscan_relids; + + fscan_relids = get_base_relids(root, rel); + + /* + * Preserve function oid and return type for executor. Each element of + * rtfuncdata is a List, corresponding to RangeTblEntry functions. Element + * of the list is a list of three-elements lists. The first one is + * function oid (for explain), the second and the third - are actual + * result types and collation oids. + */ + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + + /* + * The place in rtfuncdata should match rtindex, so we add empty "0" + * member. Also avoid examining functions, which are not present in + * foreign scan. + */ + if (rte != NULL && i > 0 && bms_is_member(i, fscan_relids) && rte->rtekind == RTE_FUNCTION) + { + ListCell *lc; + List *funcdata = NIL; + + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc; + Oid funccollation; + TupleDesc tupdesc; + Oid funcrettype; + Oid funcid = InvalidOid; + + rtfunc = (RangeTblFunction *) lfirst(lc); + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + /* Should never happen */ + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, "could not determine return type for function"); + + funccollation = exprCollation(rtfunc->funcexpr); + + if (IsA(rtfunc->funcexpr, FuncExpr)) + funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid; + + funcdata = lappend(funcdata, list_make3( + makeInteger(funcid), + makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + else + rtfuncdata = lappend(rtfuncdata, NULL); + } + + return rtfuncdata; +} + +/* + * get_base_relids + * Get base relids, used in foreign scan + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + relids = bms_difference(relids, root->outer_join_rels); + + return relids; +} + +/* + * get_min_base_rti + * Get minimum base RTI, used in foreign scan + * + * Actually, this copies logic from create_foreignscan_plan(). + * However, we need this data prior to create_foreignscan_plan() + * does its job. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + /* * postgresGetForeignPaths * Create possible scan paths for a scan on the foreign table @@ -1637,6 +1833,12 @@ postgresGetForeignPlan(PlannerInfo *root, if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + /* We can use this value to determine rtoffset. */ + fdw_private = lappend(fdw_private, makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1659,7 +1861,7 @@ postgresGetForeignPlan(PlannerInfo *root, * Construct a tuple descriptor for the scan tuples handled by a foreign join. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1695,13 +1897,65 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* Whole row var references function RTE. Determine its rowtype. */ + TupleDesc rte_tupdesc; + int num_funcs, + attnum; + ListCell *lc, + *lcname; + List *funcdata; + + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + + num_funcs = list_length(funcdata); + Assert(num_funcs >= 0); + + /* + * funcrettype != RECORD, so we have only one return attribute per + * function + */ + Assert(list_length(rte->eref->colnames) == num_funcs); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc, funcdata, lcname, rte->eref->colnames) + { + List *fdata; + char *colname; + Oid funcrettype; + Oid funcretcollation; + + fdata = lfirst_node(List, lc); + + colname = strVal(lfirst(lcname)); + + funcrettype = lsecond_node(Integer, fdata)->ival; + funcretcollation = lthird_node(Integer, fdata)->ival; + + /* Should never happen */ + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, "could not determine return type for function"); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funcretcollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1716,7 +1970,7 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; PgFdwScanState *fsstate; - RangeTblEntry *rte; + RangeTblEntry *rte = NULL; Oid userid; ForeignTable *table; UserMapping *user; @@ -1737,14 +1991,28 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. In case of a join or aggregate, scan RTEs + * until RTE_RELATION is found. We would get the same result from any. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte && rte->rtekind == RTE_RELATION) + break; + } + /* Should never happen */ + if (rte == NULL || rte->rtekind != RTE_RELATION) + elog(ERROR, "can't find relation rte for foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1787,8 +2055,16 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = list_nth(fsplan->fdw_private, FdwScanPrivateFunctions); + Integer *minrti = list_nth(fsplan->fdw_private, FdwScanPrivateMinRTIndex); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - minrti->ival; + + /* Index sanity checks */ + Assert(minrti->ival > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2828,6 +3104,13 @@ postgresPlanDirectModify(PlannerInfo *root, makeBoolean((retrieved_attrs != NIL)), retrieved_attrs, makeBoolean(plan->canSetTag)); + fscan->fdw_private = lappend(fscan->fdw_private, get_functions_data(root, foreignrel)); + + /* + * We can use this value to determine rtoffset. It was already calculated + * while building foreign scan plan + */ + fscan->fdw_private = lappend(fscan->fdw_private, makeInteger(bms_next_member(fscan->fs_base_relids, -1))); /* * Update the foreign-join-related fields. @@ -2941,7 +3224,17 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + List *rtfuncdata = list_nth(fsplan->fdw_private, FdwDirectModifyPrivateFunctions); + Integer *minrti = list_nth(fsplan->fdw_private, FdwDirectModifyPrivateMinRTIndex); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - minrti->ival; + + /* Index sanity checks */ + Assert(minrti->ival > 0); + Assert(rtoffset >= 0); + + tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -3054,7 +3347,7 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_nth(fdw_private, FdwScanPrivateRelations)) { StringInfoData relations; char *rawrelations; @@ -3098,31 +3391,89 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) { int rti = strtol(ptr, &ptr, 10); RangeTblEntry *rte; - char *relname; + char *relname = NULL; char *refname; rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); - Assert(rte->rtekind == RTE_RELATION); + /* This logic should agree with explain.c's ExplainTargetRel */ - relname = get_rel_name(rte->relid); - if (es->verbose) + if (rte->rtekind == RTE_RELATION) { - char *namespace; - - namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); - appendStringInfo(&relations, "%s.%s", - quote_identifier(namespace), - quote_identifier(relname)); + /* Note: relname may be uninitialized. */ + relname = get_rel_name(rte->relid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); + appendStringInfo(&relations, "%s.%s", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfoString(&relations, + quote_identifier(relname)); } - else - appendStringInfoString(&relations, - quote_identifier(relname)); + else if (rte->rtekind == RTE_FUNCTION) + { + ListCell *lc; + int n; + bool first = true; + List *rtfuncdata = list_nth(fdw_private, FdwScanPrivateFunctions); + List *funcdata; +#ifdef USE_ASSERT_CHECKING + Integer *fdw_private_min_rti = list_nth(fdw_private, FdwScanPrivateMinRTIndex); + + /* Check that fdw_private_min_rti calculation is correct. */ + Assert(fdw_private_min_rti->ival == minrti); +#endif + + funcdata = list_nth(rtfuncdata, rti - rtoffset); + + n = list_length(funcdata); + + if (n > 1) + appendStringInfo(&relations, "ROWS FROM("); + foreach(lc, funcdata) + { + List *funcinfo; + Oid funcid; + + funcinfo = (List *) lfirst(lc); + + if (!first) + appendStringInfoString(&relations, ", "); + else + first = false; + + funcid = linitial_node(Integer, funcinfo)->ival; + + if (OidIsValid(funcid)) + { + relname = get_func_name(funcid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name(get_func_namespace(funcid)); + appendStringInfo(&relations, "%s.%s()", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfo(&relations, "%s()", quote_identifier(relname)); + } + } + if (n > 1) + appendStringInfo(&relations, ")"); + } + refname = (char *) list_nth(es->rtable_names, rti - 1); if (refname == NULL) refname = rte->eref->aliasname; - if (strcmp(refname, relname) != 0) + if (relname == NULL || strcmp(refname, relname) != 0) appendStringInfo(&relations, " %s", quote_identifier(refname)); } @@ -6580,6 +6931,69 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid) return commands; } +/* + * Determine if foreignrel, not backed by foreign + * table, is fine to push down. + */ +static bool +is_nonrel_relinfo_ok(PlannerInfo *root, RelOptInfo *foreignrel) +{ + RangeTblEntry *rte; + RangeTblFunction *rtfunc; + TupleDesc tupdesc; + Oid funcrettype; + + rte = planner_rt_fetch(foreignrel->relid, root); + + if (!rte) + return false; + + Assert(foreignrel->fdw_private); + + if (rte->rtekind == RTE_FUNCTION) + { + ListCell *lc; + TypeFuncClass functypclass; + + /* + * WITH ORDINALITY pushdown is not implemented yet. + */ + if (rte->funcordinality) + return false; + + Assert(list_length(rte->functions) >= 1); + foreach(lc, rte->functions) + { + rtfunc = (RangeTblFunction *) lfirst(lc); + + functypclass = get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + /* + * Remote server requires a well defined return type for a + * function pushdown. Also get_tupdesc_for_join_scan_tuples() + * doesn't expect RTE_FUNCTION to return several attributes. + */ + if (functypclass != TYPEFUNC_SCALAR) + return false; + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID || funcrettype == VOIDOID) + return false; + + if (contain_var_clause(rtfunc->funcexpr) || + contain_mutable_functions(rtfunc->funcexpr) || + contain_subplans(rtfunc->funcexpr) || + contain_param_walker(rtfunc->funcexpr, NULL)) + return false; + if (!is_foreign_expr(root, foreignrel, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; + } + + return false; +} + /* * Check if reltarget is safe enough to push down semi-join. Reltarget is not * safe, if it contains references to inner rel relids, which do not belong to @@ -7328,6 +7742,43 @@ postgresGetForeignJoinPaths(PlannerInfo *root, /* XXX Consider parameterized paths for the join relation */ } +/* + * postgresTryShippableJoinPaths + * + * Try to add foreign join of foreign relation with shippable RTE. + */ +static void +postgresTryShippableJoinPaths(PlannerInfo *root, + RelOptInfo *joinrel, + RelOptInfo *outerrel, + RelOptInfo *innerrel, + JoinType jointype, + JoinPathExtraData *extra) +{ + PgFdwRelationInfo *fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + PgFdwRelationInfo *fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + + if (fpinfo_o == NULL) + /* Outer path is not foreign relation or foreign JOIN. */ + return; + + if (joinrel->fdwroutine != NULL || innerrel->reloptkind != RELOPT_BASEREL) + return; + + if (fpinfo_i == NULL || fpinfo_i->is_generated) + init_fpinfo(root, innerrel, InvalidOid, fpinfo_o); + + if (!is_nonrel_relinfo_ok(root, innerrel)) + return; + + joinrel->serverid = outerrel->serverid; + joinrel->userid = outerrel->userid; + joinrel->useridiscurrent = outerrel->useridiscurrent; + joinrel->fdwroutine = outerrel->fdwroutine; + + postgresGetForeignJoinPaths(root, joinrel, outerrel, innerrel, jointype, extra); +} + /* * Assess whether the aggregation, grouping and having operations can be pushed * down to the foreign server. As a side effect, save information we obtain in @@ -8815,3 +9266,16 @@ get_batch_size_option(Relation rel) return batch_size; } + +/* + * Checks if expression contains parameters + */ +static bool +contain_param_walker(Node *node, void *arg) +{ + if (node == NULL) + return false; + if (IsA(node, Param)) + return true; + return expression_tree_walker(node, contain_param_walker, NULL); +} diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..b4d3e2bfe10 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -52,6 +52,12 @@ typedef struct PgFdwRelationInfo /* True means that the query_pathkeys is safe to push down */ bool qp_is_pushdown_safe; + /* + * True means that PgFdwRelationInfo is not extracted from catalogs, but + * generated + */ + bool is_generated; + /* Cost and selectivity of local_conds. */ QualCost local_conds_cost; Selectivity local_conds_sel; diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 267d3c1a7e7..5140f2027ca 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -4671,3 +4671,198 @@ RESET client_min_messages; DROP FUNCTION wait_for_backend_termination(int); DROP FOREIGN TABLE remote_backend_pid; DROP VIEW my_backend_pid; + +-- =================================================================== +-- test function scan pushdown +-- =================================================================== +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl'); +ALTER FOREIGN TABLE remote_tbl OPTIONS (use_remote_estimate 'true'); +CREATE TABLE base_tbl1 (c int, d text); +CREATE FOREIGN TABLE remote_tbl1 (c int, d text) + SERVER loopback OPTIONS (table_name 'base_tbl1'); +ALTER FOREIGN TABLE remote_tbl1 OPTIONS (use_remote_estimate 'true'); + +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,1000) g; +INSERT INTO remote_tbl1 SELECT g, 'text'|| g from generate_series(1,500) g; +ANALYZE base_tbl; +ANALYZE base_tbl1; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n; + +SELECT * FROM remote_tbl r, unnest(array[2,3,4]) n WHERE r.a = n +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n; + +SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a; + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a +ORDER BY r.a; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*,n from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + +SELECT * from remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a and n > 3; + +CREATE OR REPLACE FUNCTION get_constant_texts() +RETURNS TABLE (text_value text) AS $$ +BEGIN + RETURN QUERY VALUES + ('text1'), + ('text4'); +END; +$$ LANGUAGE plpgsql IMMUTABLE; + +ALTER EXTENSION postgres_fdw ADD FUNCTION get_constant_texts(); +ALTER SERVER loopback OPTIONS (extensions 'postgres_fdw'); + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.*, t.n from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + +SELECT r.*, t.txt from remote_tbl1 r, ROWS FROM (unnest(array[3,4]), get_constant_texts()) t (n, txt) +WHERE r.c = t.n AND r.d = t.txt; + +-- Complex types +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx); + +SELECT * FROM remote_tbl r JOIN UNNEST(array[box '((2,3),(-2,-3))']) as t(bx) ON a = area(bx) +ORDER BY r.a; + +-- DML +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=5 FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +EXPLAIN (VERBOSE, COSTS OFF) +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM UNNEST(array[10,20], array[box '((2,3),(-2,-4))', box '((1,2),(-2,-3))']) AS t (l, bx) WHERE r.a between l and area(t.bx) +RETURNING a,b; + +-- Test that local functions are not pushed down +CREATE OR REPLACE FUNCTION f(INTEGER) +RETURNS SETOF INTEGER +LANGUAGE sql AS 'select generate_series(1,$1);' IMMUTABLE; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl r, f(10) n +WHERE r.a = n; + +SELECT * FROM remote_tbl r, remote_tbl1 r1, unnest(array[3,4]) n +WHERE r.a = n AND r1.c = r.a AND n > 3; + +-- Test that a function that returns a record is not pushed down +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ SELECT (1,2)::record $$ language SQL IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD function f_ret_record(); + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + +DROP FUNCTION f(INTEGER); +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ret_record(); +DROP FUNCTION f_ret_record(); + +-- Test that a function that returns composite type is not pushed down +CREATE TYPE c1 AS (i int, j int); +CREATE OR REPLACE FUNCTION f_ret_c1(int) RETURNS SETOF c1 AS $$ begin return next '(3,3)'::c1 ; end $$ language plpgsql immutable; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ret_c1(int); +ALTER EXTENSION postgres_fdw ADD TYPE c1; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT f FROM remote_tbl r, ROWS FROM (f_ret_c1(2), f_ret_c1(2)) AS f(i, j, k,l) WHERE f.i=r.a; +SELECT f FROM remote_tbl r, ROWS FROM (f_ret_c1(2), f_ret_c1(2)) AS f(i, j, k,l) WHERE f.i=r.a; + +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ret_c1(int); +ALTER EXTENSION postgres_fdw DROP TYPE c1; +DROP FUNCTION f_ret_c1(int); +DROP TYPE c1; + +DELETE FROM base_tbl; + +-- Test that function with parameters in arguments is not pushed down +INSERT INTO remote_tbl SELECT g, g*2 from generate_series(1,10) g; +ANALYZE base_tbl; +ANALYZE remote_tbl; + +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int +LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD function f(INTEGER); + +-- no foreign join +set enable_material = off; +-- Make local function scan not so attractive +ALTER SERVER loopback OPTIONS (ADD fdw_tuple_cost '1000'); +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) WHERE f=r2.a LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) WHERE f=r2.a LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; +reset enable_material; +ALTER SERVER loopback OPTIONS (DROP fdw_tuple_cost); + +ALTER EXTENSION postgres_fdw DROP function f(INTEGER); + +ALTER EXTENSION postgres_fdw DROP FUNCTION get_constant_texts(); +DROP FUNCTION get_constant_texts(); +DROP TABLE base_tbl, base_tbl1; +DROP FOREIGN TABLE remote_tbl, remote_tbl1; + +-- Test that function WITH ORDINALITY is not pushed down +CREATE TABLE base_tbl (a int, b int); +CREATE FOREIGN TABLE remote_tbl (a int, b int) SERVER loopback OPTIONS (table_name 'base_tbl'); +INSERT INTO remote_tbl VALUES (1, 2), (2, 3), (3, 4), (5, 6); +ANALYZE remote_tbl; +SET enable_mergejoin TO false; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + +SELECT * FROM remote_tbl, unnest(ARRAY[1, 2]) WITH ORDINALITY +WHERE a=unnest; + +DROP TABLE base_tbl; +DROP FOREIGN TABLE remote_tbl; +RESET enable_mergejoin; diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c index 713283a73aa..5e5282dfda8 100644 --- a/src/backend/optimizer/path/joinpath.c +++ b/src/backend/optimizer/path/joinpath.c @@ -365,6 +365,17 @@ add_paths_to_joinrel(PlannerInfo *root, outerrel, innerrel, save_jointype, &extra); + /* + * If push down of join is not possible we can try to join foreign + * relation with shippable RTE. In this case we have a chance to push down + * this join yet. + */ + else if ((extra.pgs_mask & PGS_FOREIGNJOIN) != 0 && outerrel->fdwroutine && + outerrel->fdwroutine->TryShippableJoinPaths) + outerrel->fdwroutine->TryShippableJoinPaths(root, joinrel, + outerrel, innerrel, + save_jointype, &extra); + /* * 6. Finally, give extensions a chance to manipulate the path list. They * could add new paths (such as CustomPaths) by calling add_path(), or diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h index abf59a0d8ad..81b74eaadd8 100644 --- a/src/include/foreign/fdwapi.h +++ b/src/include/foreign/fdwapi.h @@ -225,6 +225,7 @@ typedef struct FdwRoutine /* Functions for remote-join planning */ GetForeignJoinPaths_function GetForeignJoinPaths; + GetForeignJoinPaths_function TryShippableJoinPaths; /* Functions for remote upper-relation (post scan/join) planning */ GetForeignUpperPaths_function GetForeignUpperPaths; -- 2.43.0
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-05-08 05:17   ` solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  0 siblings, 1 reply; 36+ messages in thread

From: solaimurugan vellaipandiyan @ 2026-05-08 05:17 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

I tested the v3 patch on current master using a postgres_fdw loopback setup.

The patch mostly applied cleanly for me, with only a small manual
conflict resolution needed in postgres_fdw.c (missing
optimizer/clauses.h include). PostgreSQL built and started
successfully after that.

For testing, I used queries involving generate_series() together with
a foreign table, for example:

SELECT *
FROM ft
JOIN generate_series(1,3) g
ON ft.id = g;

I also tried:
1. implicit join syntax
2. LATERAL usage
3. disabling hashjoin/mergejoin to force different join paths

In all cases, the plans still showed a local Function Scan and local
join execution. The Remote SQL remained:
SELECT id FROM public.localtab
So I wasn't able to observe function scan pushdown with these testcases.
Maybe I'm missing a query shape or planner condition required to
trigger the new functionality. It would help to know which cases are
currently expected to be pushed down.

Regards,
Solaimurugan V





^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
@ 2026-05-08 06:03     ` Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2026-05-08 06:03 UTC (permalink / raw)
  To: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; +Cc: Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

solaimurugan vellaipandiyan писал(а) 2026-05-08 08:17:
> Hi,
> 
> I tested the v3 patch on current master using a postgres_fdw loopback 
> setup.
> 
> The patch mostly applied cleanly for me, with only a small manual
> conflict resolution needed in postgres_fdw.c (missing
> optimizer/clauses.h include). PostgreSQL built and started
> successfully after that.
> 
> For testing, I used queries involving generate_series() together with
> a foreign table, for example:
> 
> SELECT *
> FROM ft
> JOIN generate_series(1,3) g
> ON ft.id = g;
> 
> I also tried:
> 1. implicit join syntax
> 2. LATERAL usage
> 3. disabling hashjoin/mergejoin to force different join paths
> 
> In all cases, the plans still showed a local Function Scan and local
> join execution. The Remote SQL remained:
> SELECT id FROM public.localtab
> So I wasn't able to observe function scan pushdown with these 
> testcases.
> Maybe I'm missing a query shape or planner condition required to
> trigger the new functionality. It would help to know which cases are
> currently expected to be pushed down.
> 
> Regards,
> Solaimurugan V


Hi. Of course, this depends on foreign scan cost. Foreign join should be 
cheaper than local one.
The cost of foreign join consists from
1) cost of evaluating inner and outer part of the join,
2) total costs of retreiving rows (nrows * cost of qual evaluation),
3) cost of preparing to evaluate quals (remote and local),
4) fdw_startup_cost
5) (fdw_tuple_cost + cpu_tuple_cost) * retrieved_rows.
Look at estimate_path_cost_size().

The cost of retreiving foreign rows consists from
1) cost of estimating baserestrictinfos
2) cost of remote sequential scan
3) cost of evaluating foreign relation target list
4) fdw_startup_cost
5) (fdw_tuple_cost + cpu_tuple_cost) * retrieved_rows.

If we compare function scan pushdown for foreign table and function with 
foreign join pushdown of two foreign tables, we don't have  two 
penalties from fdw_startup_cost here. So, for function scan pushdown to 
be chosen, it should filter out significant part of data, as data 
transfer cost likely dominates in foreign scan costs estimation. You can 
see this on the following toy example.


CREATE EXTENSION postgres_fdw;

SELECT current_database() AS current_database,
   current_setting('port') AS current_port \gset
CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw
         OPTIONS (dbname :'current_database', port :'current_port');
CREATE USER MAPPING FOR current_user SERVER loopback;
CREATE table t1 (i int, j text);
create foreign table ft1 (i int, j text) server loopback options 
(table_name 't1');

-- No adequate data about relation, we assume 1000+ rows in table, so 
foreign join is chosen.

#  explain select * from ft1 , generate_series(1,10) g where i=g;
                       QUERY PLAN
------------------------------------------------------
  Foreign Scan  (cost=100.00..172.16 rows=68 width=40)
    Relations: (ft1) INNER JOIN (generate_series() g)
(2 rows)

-- We have actual data, there's no use to push down foreign join
postgres=# analyze ft1;
ANALYZE
postgres=# explain select * from ft1 , generate_series(1,10) g where 
i=g;
                                  QUERY PLAN
-----------------------------------------------------------------------------
  Hash Join  (cost=100.02..100.16 rows=1 width=40)
    Hash Cond: (g.g = ft1.i)
    ->  Function Scan on generate_series g  (cost=0.00..0.10 rows=10 
width=4)
    ->  Hash  (cost=100.00..100.00 rows=1 width=36)
          ->  Foreign Scan on ft1  (cost=100.00..100.00 rows=1 width=36)

-- If we had two foreign scans below join here, its startup cost would 
be more than 2*100.
-- But evaluating function locally saves us from such great penalty.
-- Let's add some actual data.

postgres=# insert into ft1 select i, 'test'||i from 
generate_series(1,1000) i;
INSERT 0 1000
postgres=# analyze ft1;
ANALYZE

-- Now we have actual data, transfering 1000 rows (plain foreign scan 
costs ~ 410) and joining locally is more expensive than doing
-- remote join and transfering 10 rows.

postgres=# explain select * from ft1 , generate_series(1,10) g where 
i=g;
                       QUERY PLAN
------------------------------------------------------
  Foreign Scan  (cost=100.00..143.20 rows=10 width=15)
    Relations: (ft1) INNER JOIN (generate_series() g)
(2 rows)


-- 
Best regards,
Alexander Pyhalov,
Postgres Professional





^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-05-10 22:22       ` Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-11 06:01         ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  0 siblings, 2 replies; 36+ messages in thread

From: Alexander Korotkov @ 2026-05-10 22:22 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi!

On Fri, May 8, 2026 at 9:03 AM Alexander Pyhalov
<a.pyhalov@postgrespro.ru> wrote:
>
> solaimurugan vellaipandiyan писал(а) 2026-05-08 08:17:
> > Hi,
> >
> > I tested the v3 patch on current master using a postgres_fdw loopback
> > setup.
> >
> > The patch mostly applied cleanly for me, with only a small manual
> > conflict resolution needed in postgres_fdw.c (missing
> > optimizer/clauses.h include). PostgreSQL built and started
> > successfully after that.
> >
> > For testing, I used queries involving generate_series() together with
> > a foreign table, for example:
> >
> > SELECT *
> > FROM ft
> > JOIN generate_series(1,3) g
> > ON ft.id = g;
> >
> > I also tried:
> > 1. implicit join syntax
> > 2. LATERAL usage
> > 3. disabling hashjoin/mergejoin to force different join paths
> >
> > In all cases, the plans still showed a local Function Scan and local
> > join execution. The Remote SQL remained:
> > SELECT id FROM public.localtab
> > So I wasn't able to observe function scan pushdown with these
> > testcases.
> > Maybe I'm missing a query shape or planner condition required to
> > trigger the new functionality. It would help to know which cases are
> > currently expected to be pushed down.
> >
> > Regards,
> > Solaimurugan V
>
>
> Hi. Of course, this depends on foreign scan cost. Foreign join should be
> cheaper than local one.
> The cost of foreign join consists from
> 1) cost of evaluating inner and outer part of the join,
> 2) total costs of retreiving rows (nrows * cost of qual evaluation),
> 3) cost of preparing to evaluate quals (remote and local),
> 4) fdw_startup_cost
> 5) (fdw_tuple_cost + cpu_tuple_cost) * retrieved_rows.
> Look at estimate_path_cost_size().
>
> The cost of retreiving foreign rows consists from
> 1) cost of estimating baserestrictinfos
> 2) cost of remote sequential scan
> 3) cost of evaluating foreign relation target list
> 4) fdw_startup_cost
> 5) (fdw_tuple_cost + cpu_tuple_cost) * retrieved_rows.
>
> If we compare function scan pushdown for foreign table and function with
> foreign join pushdown of two foreign tables, we don't have  two
> penalties from fdw_startup_cost here. So, for function scan pushdown to
> be chosen, it should filter out significant part of data, as data
> transfer cost likely dominates in foreign scan costs estimation. You can
> see this on the following toy example.
>
>
> CREATE EXTENSION postgres_fdw;
>
> SELECT current_database() AS current_database,
>    current_setting('port') AS current_port \gset
> CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw
>          OPTIONS (dbname :'current_database', port :'current_port');
> CREATE USER MAPPING FOR current_user SERVER loopback;
> CREATE table t1 (i int, j text);
> create foreign table ft1 (i int, j text) server loopback options
> (table_name 't1');
>
> -- No adequate data about relation, we assume 1000+ rows in table, so
> foreign join is chosen.
>
> #  explain select * from ft1 , generate_series(1,10) g where i=g;
>                        QUERY PLAN
> ------------------------------------------------------
>   Foreign Scan  (cost=100.00..172.16 rows=68 width=40)
>     Relations: (ft1) INNER JOIN (generate_series() g)
> (2 rows)
>
> -- We have actual data, there's no use to push down foreign join
> postgres=# analyze ft1;
> ANALYZE
> postgres=# explain select * from ft1 , generate_series(1,10) g where
> i=g;
>                                   QUERY PLAN
> -----------------------------------------------------------------------------
>   Hash Join  (cost=100.02..100.16 rows=1 width=40)
>     Hash Cond: (g.g = ft1.i)
>     ->  Function Scan on generate_series g  (cost=0.00..0.10 rows=10
> width=4)
>     ->  Hash  (cost=100.00..100.00 rows=1 width=36)
>           ->  Foreign Scan on ft1  (cost=100.00..100.00 rows=1 width=36)
>
> -- If we had two foreign scans below join here, its startup cost would
> be more than 2*100.
> -- But evaluating function locally saves us from such great penalty.
> -- Let's add some actual data.
>
> postgres=# insert into ft1 select i, 'test'||i from
> generate_series(1,1000) i;
> INSERT 0 1000
> postgres=# analyze ft1;
> ANALYZE
>
> -- Now we have actual data, transfering 1000 rows (plain foreign scan
> costs ~ 410) and joining locally is more expensive than doing
> -- remote join and transfering 10 rows.
>
> postgres=# explain select * from ft1 , generate_series(1,10) g where
> i=g;
>                        QUERY PLAN
> ------------------------------------------------------
>   Foreign Scan  (cost=100.00..143.20 rows=10 width=15)
>     Relations: (ft1) INNER JOIN (generate_series() g)
> (2 rows)

Thank you for your work on improving this matter.  I've updated the
patch attempting to address major concerns raised in this thread.

1) Limit the support of the pushdown with immutable functions.  This
must eliminate the risk of different evaluation results on different
servers (as long as immutable is set correctly).
2) Store pointer to stub fpinfo for the function in the absorbing
foreign table.  Thus, if there are multiple foreign tables, which
could absorb the function, both ways can be considered.  This is
illustrated in the regression tests: the decision on which foreign
table would absorb the function can be changed depending on clause
selectivity.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

v4-0001-postgres_fdw-push-down-FUNCTION-RTE-into-foreign-.patch (application/octet-stream, 25.5K) download From c111e195bd683b335565e6a62caf37b3ca1be961 Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Sun, 10 May 2026 17:15:21 +0300 Subject: [PATCH v4] postgres_fdw: push down FUNCTION RTE into foreign joins A foreign join planning hook now considers a (foreign-table x function-RTE) INNER join as a push-down candidate when the function expression is IMMUTABLE and otherwise shippable. The remote query absorbs the function call as a FROM-list item (e.g. unnest(...) AS f<rti>(c1, c2, ...)), so the foreign side returns only rows that match the function-produced set and the join executes entirely on the remote. An IMMUTABLE function gives the same result on any server, so the same function RTE can be a push-down candidate for several distinct foreign servers without semantic risk. To keep the planner state consistent across those independent attempts, the per-call stub fpinfo for the function side lives on the joinrel's PgFdwRelationInfo (new outer_func_fpinfo / inner_func_fpinfo), never on the function rel itself, and the function side is detected via rtekind rather than fdw_private. set_foreign_rel_properties() propagates fdwroutine onto a joinrel that pairs a foreign rel with an RTE_FUNCTION rel so GetForeignJoinPaths gets called; the FDW retains full control over whether to actually generate a path. deparseRangeTblRef and deparseColumnRef gain a FUNCTION-RTE branch that emits the function expression and resolves Vars to the generated column aliases. --- contrib/postgres_fdw/deparse.c | 77 +++++++- .../postgres_fdw/expected/postgres_fdw.out | 168 ++++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 136 +++++++++++++- contrib/postgres_fdw/postgres_fdw.h | 10 ++ contrib/postgres_fdw/sql/postgres_fdw.sql | 57 ++++++ src/backend/optimizer/util/relnode.c | 24 +++ 6 files changed, 462 insertions(+), 10 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 2dcc6c8af1b..e8449569ef8 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -112,6 +112,7 @@ typedef struct deparse_expr_cxt appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno)) #define SUBQUERY_REL_ALIAS_PREFIX "s" #define SUBQUERY_COL_ALIAS_PREFIX "c" +#define FUNCTION_REL_ALIAS_PREFIX "f" /* * Functions to determine whether an expression can be evaluated safely on @@ -2030,6 +2031,51 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, } } +/* + * Deparse a FUNCTION RTE that is being absorbed into a foreign join. The + * function expression is emitted as the FROM-list item, with a generated + * alias and column-name list. + */ +static void +deparseFunctionRangeTblRef(StringInfo buf, PlannerInfo *root, + RelOptInfo *foreignrel, RelOptInfo *scanrel, + List **params_list) +{ + RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); + RangeTblFunction *rtfunc; + deparse_expr_cxt context; + int i; + + Assert(rte->rtekind == RTE_FUNCTION); + Assert(list_length(rte->functions) == 1); + Assert(!rte->funcordinality); + + rtfunc = (RangeTblFunction *) linitial(rte->functions); + + context.buf = buf; + context.root = root; + context.foreignrel = scanrel; + context.scanrel = scanrel; + context.params_list = params_list; + + /* Emit the function expression itself. */ + deparseExpr((Expr *) rtfunc->funcexpr, &context); + + /* Emit alias and generated column names. */ + appendStringInfo(buf, " %s%d", FUNCTION_REL_ALIAS_PREFIX, foreignrel->relid); + if (rtfunc->funccolcount > 0) + { + appendStringInfoChar(buf, '('); + for (i = 1; i <= rtfunc->funccolcount; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + } +} + /* * Append FROM clause entry for the given relation into buf. * Conditions from lower-level SEMI-JOINs are appended to additional_conds @@ -2040,7 +2086,22 @@ deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **additional_conds, List **params_list) { - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + PgFdwRelationInfo *fpinfo; + + /* + * For a function RTE absorbed into a foreign join, deparse the function + * expression as a FROM-list item and return. The stub fpinfo set up by + * foreign_join_ok() may or may not be present here. + */ + if (foreignrel->rtekind == RTE_FUNCTION) + { + Assert(!make_subquery); + deparseFunctionRangeTblRef(buf, root, foreignrel, foreignrel, + params_list); + return; + } + + fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; /* Should only be called in these cases. */ Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel)); @@ -2712,6 +2773,20 @@ static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col) { + /* + * Function RTE columns: emit as f<varno>.c<varattno>, matching the + * aliases generated by deparseFunctionRangeTblRef(). Note that ctid + * and other system attributes are not meaningful for function RTEs. + */ + if (rte->rtekind == RTE_FUNCTION) + { + Assert(varattno > 0); + if (qualify_col) + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, varattno); + return; + } + /* We support fetching the remote side's CTID and OID. */ if (varattno == SelfItemPointerAttributeNumber) { diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index aaffcf31271..db8d0103340 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2885,6 +2885,174 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c (10 rows) ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: t1.c1, t1.c3 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1, t1.c3 + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", r1.c3 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{1,5,10,100}'::integer[]) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + c1 | c3 +-----+------- + 1 | 00001 + 5 | 00005 + 10 | 00010 + 100 | 00100 +(4 rows) + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Sort + Output: t1.c1 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1 + Relations: (public.ft1 t1) INNER JOIN (Function g) + Remote SQL: SELECT r1."C 1" FROM ("S 1"."T 1" r1 INNER JOIN generate_series(1, 4) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + c1 +---- + 1 + 2 + 3 + 4 +(4 rows) + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on pg_catalog.generate_series g + Output: g.id + Function Call: generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + QUERY PLAN +------------------------------------------------------------ + Hash Join + Output: t1.c1, u.ord + Hash Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" + -> Hash + Output: u.ord, u.id + -> Function Scan on pg_catalog.unnest u + Output: u.ord, u.id + Function Call: unnest('{1,5,10}'::integer[]) +(11 rows) + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: t1.c1, t2.c1 + Merge Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST + -> Sort + Output: t2.c1, u.id + Sort Key: t2.c1 + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{1,5,10,100}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(13 rows) + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: t1.c1, t2.c1 + Hash Cond: (t1.c1 = t2.c1) + -> Foreign Scan + Output: t1.c1, u.id + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", f3.c1 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r1."C 1" = f3.c1)))) + -> Hash + Output: t2.c1 + -> Foreign Scan on public.ft6 t2 + Output: t2.c1 + Remote SQL: SELECT c1 FROM "S 1"."T 4" +(12 rows) + +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: t1.c1, t2.c1 + Join Filter: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE ((c3 < '00010')) + -> Materialize + Output: t2.c1, u.id + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(12 rows) + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 0ff4ec23164..57708bf0baa 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -3104,6 +3104,21 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); + + /* + * If a function RTE was absorbed into the foreign join, render + * it as "Function <alias>" since we have no foreign relid. + */ + if (rte->rtekind == RTE_FUNCTION) + { + refname = (char *) list_nth(es->rtable_names, rti - 1); + if (refname == NULL) + refname = rte->eref->aliasname; + appendStringInfo(&relations, "Function %s", + quote_identifier(refname)); + continue; + } + Assert(rte->rtekind == RTE_RELATION); /* This logic should agree with explain.c's ExplainTargetRel */ relname = get_rel_name(rte->relid); @@ -3479,8 +3494,17 @@ estimate_path_cost_size(PlannerInfo *root, /* For join we expect inner and outer relations set */ Assert(fpinfo->innerrel && fpinfo->outerrel); - fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; + /* + * For a FUNCTION RTE absorbed into the join, use the stub + * fpinfo we built in foreign_join_ok(), since the function + * rel itself has no fdw_private. + */ + fpinfo_i = fpinfo->inner_func_fpinfo ? + fpinfo->inner_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; + fpinfo_o = fpinfo->outer_func_fpinfo ? + fpinfo->outer_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; /* Estimate of number of rows in cross product */ nrows = fpinfo_i->rows * fpinfo_o->rows; @@ -6619,6 +6643,42 @@ semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, return ok; } +/* + * Check if a relation is a FUNCTION RTE that can be absorbed into a remote + * join. Sets *funcexpr_p to the function expression on success. We only + * accept function RTEs with a single function and no WITH ORDINALITY, and we + * leave the volatility/shippability check to is_foreign_expr(). + */ +static bool +function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel, RelOptInfo *fdwrel, + Expr **funcexpr_p) +{ + RangeTblEntry *rte; + RangeTblFunction *rtfunc; + + if (rel->rtekind != RTE_FUNCTION) + return false; + rte = planner_rt_fetch(rel->relid, root); + if (rte->rtekind != RTE_FUNCTION) + return false; + if (list_length(rte->functions) != 1) + return false; + if (rte->funcordinality) + return false; + + rtfunc = (RangeTblFunction *) linitial(rte->functions); + + /* + * is_foreign_expr() rejects volatile expressions and checks shippability + * of every node, so it suffices for the IMMUTABLE-and-shippable test. + */ + if (!is_foreign_expr(root, fdwrel, (Expr *) rtfunc->funcexpr)) + return false; + + *funcexpr_p = (Expr *) rtfunc->funcexpr; + return true; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -6634,6 +6694,9 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; + Expr *funcexpr = NULL; + bool outer_is_function = false; + bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -6652,15 +6715,70 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, return false; /* - * If either of the joining relations is marked as unsafe to pushdown, the - * join can not be pushed down. + * Detect mixed (foreign x function-RTE) cases. Only INNER joins are + * supported initially. We dispatch on rtekind here so that the same + * function RTE can be absorbed into joins on multiple foreign servers + * (each call gets its own stub fpinfo and rechecks shippability for the + * specific server). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && + (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && + fpinfo_o->pushdown_safe && + function_rte_pushdown_ok(root, innerrel, outerrel, &funcexpr)) + { + inner_is_function = true; + } + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel, &funcexpr)) + { + outer_is_function = true; + } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } + + /* + * If one side is a function RTE, allocate a stub fpinfo so the rest of + * this function and the cost estimator can treat it uniformly. We hand + * the stub to the joinrel's deparser via the same path the foreign side + * uses, but we never permanently attach it to the function rel's + * fdw_private (different joinrels may pair the same function RTE with + * different foreign servers). + */ + if (inner_is_function) + { + fpinfo_i = palloc0_object(PgFdwRelationInfo); + fpinfo_i->pushdown_safe = true; + fpinfo_i->server = fpinfo_o->server; + fpinfo_i->relation_name = psprintf("%u", innerrel->relid); + fpinfo_i->rows = innerrel->rows; + fpinfo_i->width = innerrel->reltarget->width; + fpinfo_i->retrieved_rows = innerrel->rows; + fpinfo_i->rel_startup_cost = 0; + fpinfo_i->rel_total_cost = 0; + fpinfo->inner_func_fpinfo = fpinfo_i; + } + else if (outer_is_function) + { + fpinfo_o = palloc0_object(PgFdwRelationInfo); + fpinfo_o->pushdown_safe = true; + fpinfo_o->server = fpinfo_i->server; + fpinfo_o->relation_name = psprintf("%u", outerrel->relid); + fpinfo_o->rows = outerrel->rows; + fpinfo_o->width = outerrel->reltarget->width; + fpinfo_o->retrieved_rows = outerrel->rows; + fpinfo_o->rel_startup_cost = 0; + fpinfo_o->rel_total_cost = 0; + fpinfo->outer_func_fpinfo = fpinfo_o; + } /* * If joining relations have local conditions, those conditions are diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..b3f1dc0d2b2 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -106,6 +106,16 @@ typedef struct PgFdwRelationInfo /* joinclauses contains only JOIN/ON conditions for an outer join */ List *joinclauses; /* List of RestrictInfo */ + /* + * If a FUNCTION RTE was absorbed into this join, these point at the + * stub PgFdwRelationInfo for the function side (paired with the + * outerrel/innerrel), so the cost estimator and deparser can find it + * without consulting the function rel's fdw_private. At most one of + * outer_func_fpinfo/inner_func_fpinfo is set. + */ + struct PgFdwRelationInfo *outer_func_fpinfo; + struct PgFdwRelationInfo *inner_func_fpinfo; + /* Upper relation information */ UpperRelationKind stage; diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 267d3c1a7e7..a468b564b72 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -790,6 +790,63 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 3fc2c2f71d0..f21ae1baeb2 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -746,6 +746,30 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if (OidIsValid(outer_rel->serverid) && + inner_rel->rtekind == RTE_FUNCTION) + { + /* + * One side is a foreign relation, the other side is a function RTE. + * If the function is IMMUTABLE, the FDW can absorb the function call + * into the remote query (the result is identical regardless of which + * server evaluates it). Let the FDW decide whether the join is + * actually shippable; here we just propagate the FDW routine so the + * FDW gets a chance. + */ + joinrel->serverid = outer_rel->serverid; + joinrel->userid = outer_rel->userid; + joinrel->useridiscurrent = outer_rel->useridiscurrent; + joinrel->fdwroutine = outer_rel->fdwroutine; + } + else if (OidIsValid(inner_rel->serverid) && + outer_rel->rtekind == RTE_FUNCTION) + { + joinrel->serverid = inner_rel->serverid; + joinrel->userid = inner_rel->userid; + joinrel->useridiscurrent = inner_rel->useridiscurrent; + joinrel->fdwroutine = inner_rel->fdwroutine; + } } /* -- 2.39.5 (Apple Git-154)
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
@ 2026-05-11 06:01         ` solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-11 12:02           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  1 sibling, 1 reply; 36+ messages in thread

From: solaimurugan vellaipandiyan @ 2026-05-11 06:01 UTC (permalink / raw)
  To: Alexander Korotkov <aekorotkov@gmail.com>; +Cc: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

Thanks for the detailed explanation and the example queries. That
helped me better understand the costing behavior behind the pushdown
decisions.

I tested the new v4 patch on current master using a postgres_fdw
loopback setup with local table t1 and foreign table ft1.

Here’s what I observed:
- Before ANALYZE, the planner chose a local Hash Join with separate
Foreign Scan and Function  Scan nodes.
- After running ANALYZE on the empty table, it still preferred local
execution, which makes sense based on the costing explanation.
- I then inserted 1000 rows into t1, ran ANALYZE again, and repeated the test.

Even after that, I still got a local Hash Join plan like:
Hash Join
 - Foreign Scan on ft1
 - Function Scan on generate_series
I wasn’t able to observe the pushed-down Foreign Scan plan shown in
the example from the thread.

The patch itself applied and built successfully on my side, so this
may just be due to planner cost differences or environment-specific
behavior on current master.

Regards,
Solaimurugan V





^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-11 06:01         ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
@ 2026-05-11 12:02           ` Alexander Korotkov <aekorotkov@gmail.com>
  0 siblings, 0 replies; 36+ messages in thread

From: Alexander Korotkov @ 2026-05-11 12:02 UTC (permalink / raw)
  To: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; +Cc: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Mon, May 11, 2026 at 9:01 AM solaimurugan vellaipandiyan <
drsolaimurugan.v@gmail.com> wrote:
> Thanks for the detailed explanation and the example queries. That
> helped me better understand the costing behavior behind the pushdown
> decisions.
>
> I tested the new v4 patch on current master using a postgres_fdw
> loopback setup with local table t1 and foreign table ft1.
>
> Here’s what I observed:
> - Before ANALYZE, the planner chose a local Hash Join with separate
> Foreign Scan and Function  Scan nodes.
> - After running ANALYZE on the empty table, it still preferred local
> execution, which makes sense based on the costing explanation.
> - I then inserted 1000 rows into t1, ran ANALYZE again, and repeated the
test.
>
> Even after that, I still got a local Hash Join plan like:
> Hash Join
>  - Foreign Scan on ft1
>  - Function Scan on generate_series
> I wasn’t able to observe the pushed-down Foreign Scan plan shown in
> the example from the thread.
>
> The patch itself applied and built successfully on my side, so this
> may just be due to planner cost differences or environment-specific
> behavior on current master.

This also comes from the cost model.  Check this example.

# CREATE TABLE t1 (id int);
# INSERT INTO t1 SELECT g FROM generate_series(1, 1000) g;
# CREATE FOREIGN TABLE ft1 (id int) SERVER loopback OPTIONS (table_name
't1');
# ANALYZE t1;
# ANALYZE ft1;

By default the local join is selected.

# EXPLAIN (VERBOSE, COSTS ON)
SELECT * FROM ft1, generate_series(1, 100) AS g(id)
WHERE ft1.id = g.id;
                                          QUERY PLAN

-----------------------------------------------------------------------------------------------
 Hash Join  (cost=102.25..332.00 rows=100 width=8)
   Output: ft1.id, g.id
   Hash Cond: (ft1.id = g.id)
   ->  Foreign Scan on public.ft1  (cost=100.00..325.00 rows=1000 width=4)
         Output: ft1.id
         Remote SQL: SELECT id FROM public.t1
   ->  Hash  (cost=1.00..1.00 rows=100 width=4)
         Output: g.id
         ->  Function Scan on pg_catalog.generate_series g
 (cost=0.00..1.00 rows=100 width=4)
               Output: g.id
               Function Call: generate_series(1, 100)
(11 rows)

However, we can force remote join using enable_* options. You can see it
has higher cost.  This is because estimate_path_cost_size() expects join
operator to be applied to the whole cross-product.

# SET enable_hashjoin = off;
# SET enable_mergejoin = off;
# SET enable_nestloop = off;
# EXPLAIN (VERBOSE, COSTS ON)
SELECT * FROM ft1, generate_series(1, 100) AS g(id)
WHERE ft1.id = g.id;
                                          QUERY PLAN

-----------------------------------------------------------------------------------------------
 Hash Join  (cost=102.25..332.00 rows=100 width=8)
   Output: ft1.id, g.id
   Hash Cond: (ft1.id = g.id)
   ->  Foreign Scan on public.ft1  (cost=100.00..325.00 rows=1000 width=4)
         Output: ft1.id
         Remote SQL: SELECT id FROM public.t1
   ->  Hash  (cost=1.00..1.00 rows=100 width=4)
         Output: g.id
         ->  Function Scan on pg_catalog.generate_series g
 (cost=0.00..1.00 rows=100 width=4)
               Output: g.id
               Function Call: generate_series(1, 100)
(11 rows)
# RESET enable_hashjoin;
# RESET enable_mergejoin;
# RESET enable_nestloop;

Also, this can be fixed using remote estimate.  You also can check that v3
regression tests by Pyhalov use this approach as well.

# ALTER FOREIGN TABLE ft1 OPTIONS (ADD use_remote_estimate 'true');
# EXPLAIN (VERBOSE, COSTS ON)
SELECT * FROM ft1, generate_series(1, 100) AS g(id)
WHERE ft1.id = g.id;
                                                       QUERY PLAN

------------------------------------------------------------------------------------------------------------------------
 Foreign Scan  (cost=102.25..143.00 rows=100 width=8)
   Output: ft1.id, g.id
   Relations: (public.ft1) INNER JOIN (Function g)
   Remote SQL: SELECT r1.id, f2.c1 FROM (public.t1 r1 INNER JOIN
generate_series(1, 100) f2(c1) ON (((r1.id = f2.c1))))
(4 rows)

Thus, I don't see it to be a problem of this specific patch.  I think this
is general inaccuracy of postgres_fdw cost model.

------
Regards,
Alexander Korotkov
Supabase

^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
@ 2026-05-12 08:09         ` Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  1 sibling, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2026-05-12 08:09 UTC (permalink / raw)
  To: Alexander Korotkov <aekorotkov@gmail.com>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Alexander Korotkov писал(а) 2026-05-11 01:22:
> Hi!
> 
> On Fri, May 8, 2026 at 9:03 AM Alexander Pyhalov
> <a.pyhalov@postgrespro.ru> wrote:
>> 
>> solaimurugan vellaipandiyan писал(а) 2026-05-08 08:17:
>> > Hi,
>> >
>> > I tested the v3 patch on current master using a postgres_fdw loopback
>> > setup.
>> >
>> > The patch mostly applied cleanly for me, with only a small manual
>> > conflict resolution needed in postgres_fdw.c (missing
>> > optimizer/clauses.h include). PostgreSQL built and started
>> > successfully after that.
>> >
>> > For testing, I used queries involving generate_series() together with
>> > a foreign table, for example:
>> >
>> > SELECT *
>> > FROM ft
>> > JOIN generate_series(1,3) g
>> > ON ft.id = g;
>> >
>> > I also tried:
>> > 1. implicit join syntax
>> > 2. LATERAL usage
>> > 3. disabling hashjoin/mergejoin to force different join paths
>> >
>> > In all cases, the plans still showed a local Function Scan and local
>> > join execution. The Remote SQL remained:
>> > SELECT id FROM public.localtab
>> > So I wasn't able to observe function scan pushdown with these
>> > testcases.
>> > Maybe I'm missing a query shape or planner condition required to
>> > trigger the new functionality. It would help to know which cases are
>> > currently expected to be pushed down.
>> >
>> > Regards,
>> > Solaimurugan V
>> 
>> 
>> Hi. Of course, this depends on foreign scan cost. Foreign join should 
>> be
>> cheaper than local one.
>> The cost of foreign join consists from
>> 1) cost of evaluating inner and outer part of the join,
>> 2) total costs of retreiving rows (nrows * cost of qual evaluation),
>> 3) cost of preparing to evaluate quals (remote and local),
>> 4) fdw_startup_cost
>> 5) (fdw_tuple_cost + cpu_tuple_cost) * retrieved_rows.
>> Look at estimate_path_cost_size().
>> 
>> The cost of retreiving foreign rows consists from
>> 1) cost of estimating baserestrictinfos
>> 2) cost of remote sequential scan
>> 3) cost of evaluating foreign relation target list
>> 4) fdw_startup_cost
>> 5) (fdw_tuple_cost + cpu_tuple_cost) * retrieved_rows.
>> 
>> If we compare function scan pushdown for foreign table and function 
>> with
>> foreign join pushdown of two foreign tables, we don't have  two
>> penalties from fdw_startup_cost here. So, for function scan pushdown 
>> to
>> be chosen, it should filter out significant part of data, as data
>> transfer cost likely dominates in foreign scan costs estimation. You 
>> can
>> see this on the following toy example.
>> 
>> 
>> CREATE EXTENSION postgres_fdw;
>> 
>> SELECT current_database() AS current_database,
>>    current_setting('port') AS current_port \gset
>> CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw
>>          OPTIONS (dbname :'current_database', port :'current_port');
>> CREATE USER MAPPING FOR current_user SERVER loopback;
>> CREATE table t1 (i int, j text);
>> create foreign table ft1 (i int, j text) server loopback options
>> (table_name 't1');
>> 
>> -- No adequate data about relation, we assume 1000+ rows in table, so
>> foreign join is chosen.
>> 
>> #  explain select * from ft1 , generate_series(1,10) g where i=g;
>>                        QUERY PLAN
>> ------------------------------------------------------
>>   Foreign Scan  (cost=100.00..172.16 rows=68 width=40)
>>     Relations: (ft1) INNER JOIN (generate_series() g)
>> (2 rows)
>> 
>> -- We have actual data, there's no use to push down foreign join
>> postgres=# analyze ft1;
>> ANALYZE
>> postgres=# explain select * from ft1 , generate_series(1,10) g where
>> i=g;
>>                                   QUERY PLAN
>> -----------------------------------------------------------------------------
>>   Hash Join  (cost=100.02..100.16 rows=1 width=40)
>>     Hash Cond: (g.g = ft1.i)
>>     ->  Function Scan on generate_series g  (cost=0.00..0.10 rows=10
>> width=4)
>>     ->  Hash  (cost=100.00..100.00 rows=1 width=36)
>>           ->  Foreign Scan on ft1  (cost=100.00..100.00 rows=1 
>> width=36)
>> 
>> -- If we had two foreign scans below join here, its startup cost would
>> be more than 2*100.
>> -- But evaluating function locally saves us from such great penalty.
>> -- Let's add some actual data.
>> 
>> postgres=# insert into ft1 select i, 'test'||i from
>> generate_series(1,1000) i;
>> INSERT 0 1000
>> postgres=# analyze ft1;
>> ANALYZE
>> 
>> -- Now we have actual data, transfering 1000 rows (plain foreign scan
>> costs ~ 410) and joining locally is more expensive than doing
>> -- remote join and transfering 10 rows.
>> 
>> postgres=# explain select * from ft1 , generate_series(1,10) g where
>> i=g;
>>                        QUERY PLAN
>> ------------------------------------------------------
>>   Foreign Scan  (cost=100.00..143.20 rows=10 width=15)
>>     Relations: (ft1) INNER JOIN (generate_series() g)
>> (2 rows)
> 
> Thank you for your work on improving this matter.  I've updated the
> patch attempting to address major concerns raised in this thread.
> 
> 1) Limit the support of the pushdown with immutable functions.  This
> must eliminate the risk of different evaluation results on different
> servers (as long as immutable is set correctly).
> 2) Store pointer to stub fpinfo for the function in the absorbing
> foreign table.  Thus, if there are multiple foreign tables, which
> could absorb the function, both ways can be considered.  This is
> illustrated in the regression tests: the decision on which foreign
> table would absorb the function can be changed depending on clause
> selectivity.
> 
> ------
> Regards,
> Alexander Korotkov
> Supabase

Hi.
I've tested updated patch a bit.

1) deparseColumnRef() doesn't account for whole row vars.
In queries like

UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS 
t (bx) WHERE r.a = area(t.bx)

it fails with assert that varattno should be > 0. When we lock 
non-relation RTE, we select whole row var, and we have to deparse it for 
function RTE.

You've removed check for function return type. This seems to be 
dangerous. Old example

CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ SELECT 
(1,2)::record $$ language SQL IMMUTABLE;
ALTER EXTENSION postgres_fdw ADD function f_ret_record();
EXPLAIN (VERBOSE, COSTS OFF)
SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int)
WHERE s.a = rt.a;

fails with

ERROR:  a column definition list is required for functions returning 
"record"

2) postgresBeginForeignScan() can step on function RTE, and doesn't know 
what to do with it:
SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n;
ERROR:  cache lookup failed for foreign table 0

So, we need to look for the first RTE_RELATION, as in older patch 
version.

3) A lot of complexity in the old patch version was in making it 
possible to find out RTE_FUNCTION attribute types after planing, as it's 
necessary to correctly handle joins. In this version 
get_tupdesc_for_join_scan_tuples() doesn't handle function RTEs.  This 
means, when we try to find out type for attribute types for joins, we'll 
get errors. This can be seen in queries like

UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM 
UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx)
  RETURNING a,b;

Now it fails on earlier stages (with "column f2.c0 does not exist"), but 
if we fix it, we'll get something like
"ERROR:  input of anonymous composite types is not implemented"

Overall, function_rte_pushdown_ok() now allows more strange 
constructions. Could it skip Vars from outside of joinrel->relids? Can 
we safely ship function with parameters in arguments? I'm not sure.

4) Why do we restrict list_length(rte->functions) to 1? The main reason 
for supporting several rte->functions was to allow pushdown of UNNEST() 
with several arrays, which is used by HammerDB tproc-c test.

5) We can support pushing down joins of foreign tables and another RTE 
types, for example, VALUES. But with new specific way of handling 
RTE_FUNCTIONS in core, this requires both changes to 
set_foreign_rel_properties() and postgres_fdw. Not sure, if this is a 
big problem, but at least is worth mentioning .

-- 
Best regards,
Alexander Pyhalov,
Postgres Professional





^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-05-18 10:34           ` Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Korotkov @ 2026-05-18 10:34 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi, Alexander!

The revised patch is attached.

On Tue, May 12, 2026 at 11:09 AM Alexander Pyhalov
<a.pyhalov@postgrespro.ru> wrote:
> 1) deparseColumnRef() doesn't account for whole row vars.
> In queries like
>
> UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS
> t (bx) WHERE r.a = area(t.bx)
>
> it fails with assert that varattno should be > 0. When we lock
> non-relation RTE, we select whole row var, and we have to deparse it for
> function RTE.
>
> You've removed check for function return type. This seems to be
> dangerous. Old example
>
> CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ SELECT
> (1,2)::record $$ language SQL IMMUTABLE;
> ALTER EXTENSION postgres_fdw ADD function f_ret_record();
> EXPLAIN (VERBOSE, COSTS OFF)
> SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int)
> WHERE s.a = rt.a;
>
> fails with
>
> ERROR:  a column definition list is required for functions returning
> "record"

function_rte_pushdown_ok() now calls get_expr_result_type() and
rejects anything that isn't TYPEFUNC_SCALAR (also RECORDOID/VOIDOID),
so f_ret_record() no longer reaches the remote side.
deparseColumnRef() now handles varattno == 0 for RTE_FUNCTION and
emits ROW(f<rti>.c1, ..., f<rti>.c<N>) from rte->eref->colnames.

> 2) postgresBeginForeignScan() can step on function RTE, and doesn't know
> what to do with it:
> SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n;
> ERROR:  cache lookup failed for foreign table 0
>
> So, we need to look for the first RTE_RELATION, as in older patch
> version.

The scanrelid == 0 branch in postgresBeginForeignScan() now scans
fs_base_relids until it finds an RTE_RELATION.  An explicit
elog(ERROR) guards the (theoretically impossible) case where no
foreign RTE is found.

> 3) A lot of complexity in the old patch version was in making it
> possible to find out RTE_FUNCTION attribute types after planing, as it's
> necessary to correctly handle joins. In this version
> get_tupdesc_for_join_scan_tuples() doesn't handle function RTEs.  This
> means, when we try to find out type for attribute types for joins, we'll
> get errors. This can be seen in queries like
>
> UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM
> UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx)
>   RETURNING a,b;
>
> Now it fails on earlier stages (with "column f2.c0 does not exist"), but
> if we fix it, we'll get something like
> "ERROR:  input of anonymous composite types is not implemented"
>
> Overall, function_rte_pushdown_ok() now allows more strange
> constructions. Could it skip Vars from outside of joinrel->relids? Can
> we safely ship function with parameters in arguments? I'm not sure.

Restored the per-function metadata you had in v2/v3.
FdwScanPrivateFunctions (list of (funcid, funcrettype, funccollation)
indexed by RTI-offset) and FdwScanPrivateMinRTIndex are now saved in
fdw_private by postgresGetForeignPlan().
get_tupdesc_for_join_scan_tuples() now has an RTE_FUNCTION branch that
rebuilds the tuple descriptor from this metadata, exactly as in your
patch.

> 4) Why do we restrict list_length(rte->functions) to 1? The main reason
> for supporting several rte->functions was to allow pushdown of UNNEST()
> with several arrays, which is used by HammerDB tproc-c test.

function_rte_pushdown_ok() now loops over rte->functions and applies
the same checks to every member.  deparseFunctionRangeTblRef() emits
ROWS FROM (f1(), f2(), ...) AS f<rti>(c1, c2, ...) with the
column-name list covering the concatenation of every function's
columns, in the order they appear.

> 5) We can support pushing down joins of foreign tables and another RTE
> types, for example, VALUES. But with new specific way of handling
> RTE_FUNCTIONS in core, this requires both changes to
> set_foreign_rel_properties() and postgres_fdw. Not sure, if this is a
> big problem, but at least is worth mentioning .

I've kept the planner-side change minimal:
set_foreign_rel_properties() propagates fdwroutine onto a joinrel
pairing a foreign rel with an RTE_FUNCTION rel, so the standard
GetForeignJoinPaths callback gets invoked.  No new FDW callback was
needed.  This is also the reason the planner-side fpinfo of the
function side lives on the joinrel
(outer_func_fpinfo/inner_func_fpinfo fields added to
PgFdwRelationInfo) rather than on the function
RelOptInfo->fdw_private: the same RTE_FUNCTION rel can be paired
independently with foreign rels from several servers.  Extending the
same scheme to RTE_VALUES / RTE_CTE is, I agree, worth doing late. It
would be a one branch addition to set_foreign_rel_properties() plus an
FDW-side shippability check analogous to function_rte_pushdown_ok().

A few extra changes to the patch:
- LATERAL function RTEs are explicitly rejected in
function_rte_pushdown_ok() (returns false when rel->lateral_relids is
non-empty).
- Outer joins (LEFT/RIGHT/FULL) and SEMI joins fall through to the
existing !fpinfo_o || !fpinfo_i rejection, since
inner_is_function/outer_is_function are only set for JOIN_INNER.
- Regression coverage in contrib/postgres_fdw/sql/postgres_fdw.sql now
reuses your examples.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

v5-0001-postgres_fdw-push-down-FUNCTION-RTE-into-foreign-.patch (application/octet-stream, 53.3K) download From c646befa316555ac7a2b10cf9f520f36496941cb Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Sun, 10 May 2026 17:15:21 +0300 Subject: [PATCH v5] postgres_fdw: push down FUNCTION RTE into foreign joins A foreign join planning hook now considers a (foreign-table x function-RTE) INNER join as a push-down candidate when the function expression is IMMUTABLE and otherwise shippable. The remote query absorbs the function call as a FROM-list item (e.g. unnest(...) AS f<rti>(c1, c2, ...)), so the foreign side returns only rows that match the function-produced set and the join executes entirely on the remote. An IMMUTABLE function gives the same result on any server, so the same function RTE can be a push-down candidate for several distinct foreign servers without semantic risk. To keep the planner state consistent across those independent attempts, the per-call stub fpinfo for the function side lives on the joinrel's PgFdwRelationInfo (new outer_func_fpinfo / inner_func_fpinfo), never on the function rel itself, and the function side is detected via rtekind rather than fdw_private. set_foreign_rel_properties() propagates fdwroutine onto a joinrel that pairs a foreign rel with an RTE_FUNCTION rel so GetForeignJoinPaths gets called; the FDW retains full control over whether to actually generate a path. deparseRangeTblRef and deparseColumnRef gain a FUNCTION-RTE branch that emits the function expression and resolves Vars to the generated column aliases. --- contrib/postgres_fdw/deparse.c | 122 ++++- .../postgres_fdw/expected/postgres_fdw.out | 402 ++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 431 +++++++++++++++++- contrib/postgres_fdw/postgres_fdw.h | 10 + contrib/postgres_fdw/sql/postgres_fdw.sql | 162 +++++++ src/backend/optimizer/util/relnode.c | 24 + 6 files changed, 1127 insertions(+), 24 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 2dcc6c8af1b..f40fe52ea5b 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -112,6 +112,7 @@ typedef struct deparse_expr_cxt appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno)) #define SUBQUERY_REL_ALIAS_PREFIX "s" #define SUBQUERY_COL_ALIAS_PREFIX "c" +#define FUNCTION_REL_ALIAS_PREFIX "f" /* * Functions to determine whether an expression can be evaluated safely on @@ -2030,6 +2031,72 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, } } +/* + * Deparse a FUNCTION RTE absorbed into a foreign join. The function call(s) + * are emitted as a FROM-list item: + * + * <funcexpr> AS f<rti>(c1, c2, ..., cN) + * + * For multi-function RTEs (SQL ROWS FROM (f1(), f2(), ...)), each + * function call appears comma-separated inside ROWS FROM(...). Column + * aliases c1..cN cover the union of every function's columns, in the + * order they appear; that matches the column ordering of the RTE. + */ +static void +deparseFunctionRangeTblRef(StringInfo buf, PlannerInfo *root, + RelOptInfo *foreignrel, RelOptInfo *scanrel, + List **params_list) +{ + RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); + deparse_expr_cxt context; + ListCell *lc; + bool multi_func; + int total_cols = 0; + int i; + + Assert(rte->rtekind == RTE_FUNCTION); + Assert(!rte->funcordinality); + Assert(list_length(rte->functions) >= 1); + + multi_func = list_length(rte->functions) > 1; + + context.buf = buf; + context.root = root; + context.foreignrel = scanrel; + context.scanrel = scanrel; + context.params_list = params_list; + + if (multi_func) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (foreach_current_index(lc) > 0) + appendStringInfoString(buf, ", "); + deparseExpr((Expr *) rtfunc->funcexpr, &context); + total_cols += rtfunc->funccolcount; + } + + if (multi_func) + appendStringInfoChar(buf, ')'); + + /* Alias + generated column-name list. */ + appendStringInfo(buf, " %s%d", FUNCTION_REL_ALIAS_PREFIX, foreignrel->relid); + if (total_cols > 0) + { + appendStringInfoChar(buf, '('); + for (i = 1; i <= total_cols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + } +} + /* * Append FROM clause entry for the given relation into buf. * Conditions from lower-level SEMI-JOINs are appended to additional_conds @@ -2040,7 +2107,22 @@ deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **additional_conds, List **params_list) { - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + PgFdwRelationInfo *fpinfo; + + /* + * For a function RTE absorbed into a foreign join, deparse the function + * expression as a FROM-list item and return. The stub fpinfo set up by + * foreign_join_ok() may or may not be present here. + */ + if (foreignrel->rtekind == RTE_FUNCTION) + { + Assert(!make_subquery); + deparseFunctionRangeTblRef(buf, root, foreignrel, foreignrel, + params_list); + return; + } + + fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; /* Should only be called in these cases. */ Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel)); @@ -2712,6 +2794,44 @@ static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col) { + /* + * Function RTE columns: emit as f<varno>.c<varattno>, matching the + * aliases generated by deparseFunctionRangeTblRef(). A whole-row Var + * (varattno == 0) is rendered as ROW(f<varno>.c1, ..., f<varno>.c<N>) + * where N is the total column count of the function RTE (including all + * ROWS FROM (...) members). System attributes such as ctid have no + * meaning for function RTEs and are rejected. + */ + if (rte->rtekind == RTE_FUNCTION) + { + if (varattno == 0) + { + int ncols = list_length(rte->eref->colnames); + int i; + + appendStringInfoString(buf, "ROW("); + for (i = 1; i <= ncols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d.%s%d", + FUNCTION_REL_ALIAS_PREFIX, varno, + SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + return; + } + + if (varattno < 0) + elog(ERROR, + "system attribute reference to a function RTE is not supported in foreign join pushdown"); + + if (qualify_col) + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, varattno); + return; + } + /* We support fetching the remote side's CTID and OID. */ if (varattno == SelfItemPointerAttributeNumber) { diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index aaffcf31271..ca158d5b84f 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2885,6 +2885,408 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c (10 rows) ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: t1.c1, t1.c3 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1, t1.c3 + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", r1.c3 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{1,5,10,100}'::integer[]) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + c1 | c3 +-----+------- + 1 | 00001 + 5 | 00005 + 10 | 00010 + 100 | 00100 +(4 rows) + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Sort + Output: t1.c1 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1 + Relations: (public.ft1 t1) INNER JOIN (Function g) + Remote SQL: SELECT r1."C 1" FROM ("S 1"."T 1" r1 INNER JOIN generate_series(1, 4) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + c1 +---- + 1 + 2 + 3 + 4 +(4 rows) + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on pg_catalog.generate_series g + Output: g.id + Function Call: generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + QUERY PLAN +------------------------------------------------------------ + Hash Join + Output: t1.c1, u.ord + Hash Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" + -> Hash + Output: u.ord, u.id + -> Function Scan on pg_catalog.unnest u + Output: u.ord, u.id + Function Call: unnest('{1,5,10}'::integer[]) +(11 rows) + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: t1.c1, t2.c1 + Merge Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST + -> Sort + Output: t2.c1, u.id + Sort Key: t2.c1 + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{1,5,10,100}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(13 rows) + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: t1.c1, t2.c1 + Hash Cond: (t1.c1 = t2.c1) + -> Foreign Scan + Output: t1.c1, u.id + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", f3.c1 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r1."C 1" = f3.c1)))) + -> Hash + Output: t2.c1 + -> Foreign Scan on public.ft6 t2 + Output: t2.c1 + Remote SQL: SELECT c1 FROM "S 1"."T 4" +(12 rows) + +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: t1.c1, t2.c1 + Join Filter: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE ((c3 < '00010')) + -> Materialize + Output: t2.c1, u.id + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(12 rows) + +-- The remaining scenarios mirror the reproducers from Pyhalov's +-- v4-patch review (postgr.es/m/7e2abeb3ea9bc7ca024f4e457dce33f5%40postgrespro.ru), +-- so the same dedicated foreign table is reused for each. +CREATE TABLE base_tbl_pyh (a int, b int); +INSERT INTO base_tbl_pyh + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_pyh'); +-- Pyhalov #3: function RTE appears first in FROM; the foreign relation +-- is found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: n.n, r.a, r.b + Relations: (Function n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_pyh r2 ON (((f1.c1 = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + n | a | b +---+---+----- + 2 | 2 | 102 + 3 | 3 | 103 + 4 | 4 | 104 +(3 rows) + +-- Pyhalov #2: function returning record (composite) is forbidden; +-- pushing it would yield a remote "column definition list is required" +-- error. function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +------------------------------------------------------- + Hash Join + Output: s.* + Hash Cond: (rt.a = s.a) + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl_pyh + -> Hash + Output: s.*, s.a + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() +(11 rows) + +DROP FUNCTION f_ret_record(); +-- Pyhalov #1: UPDATE ... FROM unnest() with a complex element type; +-- area(box) yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- now emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + a | b +----+----- + 23 | 123 + 24 | 999 + 25 | 125 +(3 rows) + +-- Pyhalov #4: same shape with CASE and RETURNING. Exercises the +-- DirectModify path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + a | b +----+--- + 24 | 5 +(1 row) + +-- Pyhalov #5: ROWS FROM (...) with several functions. We force +-- pushdown because the cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: r.a, t.n, t.s + Sort Key: r.a + -> Foreign Scan + Output: r.a, t.n, t.s + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT r1.a, f2.c1, f2.c2 FROM (public.base_tbl_pyh r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + a | n | s +---+---+---- + 3 | 3 | 11 + 6 | 6 | 12 + 9 | 9 | 13 +(3 rows) + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: ((t.*)::text), r.a + Sort Key: r.a + -> Foreign Scan + Output: (t.*)::text, r.a + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT ROW(f2.c1, f2.c2), r1.a FROM (public.base_tbl_pyh r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + t | a +--------+--- + (3,11) | 3 + (6,12) | 6 + (9,13) | 9 +(3 rows) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: r.a + Merge Cond: (t.n = r.a) + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]), generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Sort + Output: r.a + Sort Key: r.a + -> Foreign Scan on public.remote_tbl r + Output: r.a + Remote SQL: SELECT a FROM public.base_tbl_pyh +(15 rows) + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + QUERY PLAN +-------------------------------------------------------------------------------------------------- + Nested Loop + Output: r.a, t.x + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_pyh WHERE ((a <= 3)) ORDER BY a ASC NULLS LAST + -> Function Scan on pg_catalog.unnest t + Output: t.x + Function Call: unnest(ARRAY[r.a]) +(8 rows) + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + QUERY PLAN +-------------------------------------------------------------------------------------------------- + Merge Left Join + Output: r.a, t.n + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_pyh WHERE ((a <= 5)) ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{1,2,3}'::integer[]) +(12 rows) + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + QUERY PLAN +--------------------------------------------------------------------------------- + Merge Semi Join + Output: r.a + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_pyh ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]) +(12 rows) + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_pyh; -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 0ff4ec23164..1641ddd9ef9 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -31,6 +31,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/appendinfo.h" +#include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" #include "optimizer/optimizer.h" @@ -88,6 +89,22 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of per-RTE function metadata, indexed by base RTI offset. Each + * element is either NULL (for non-RTE_FUNCTION rels in this scan) or a + * list of three-element lists (funcid, funcrettype, funccollation) -- one + * inner list per function in the RTE. Allows the executor to rebuild + * TupleDesc entries for whole-row references to function RTEs. + */ + FdwScanPrivateFunctions, + + /* + * Integer node: minimum base RT index covered by the scan, used to + * translate scan-local indexes to estate-rtable indexes after setrefs.c + * flattens rtables. + */ + FdwScanPrivateMinRTIndex, }; /* @@ -740,6 +757,9 @@ static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, static List *get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel); static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, Path *epq_path, List *restrictlist); static void add_foreign_grouping_paths(PlannerInfo *root, @@ -1634,9 +1654,26 @@ postgresGetForeignPlan(PlannerInfo *root, fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(fpinfo->fetch_size)); + + /* + * Position FdwScanPrivateRelations: either the EXPLAIN relation string + * (joins/upper rels) or a NULL placeholder, so that subsequent indexes + * stay valid for the base-rel scan case. + */ if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + /* + * FdwScanPrivateFunctions / FdwScanPrivateMinRTIndex carry the metadata + * the executor needs to rebuild TupleDesc entries for whole-row Vars + * pointing at RTE_FUNCTION rels absorbed into the foreign scan. + */ + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + fdw_private = lappend(fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1657,9 +1694,15 @@ postgresGetForeignPlan(PlannerInfo *root, /* * Construct a tuple descriptor for the scan tuples handled by a foreign join. + * + * 'rtfuncdata' is the FdwScanPrivateFunctions list saved at plan time, and + * 'rtoffset' is the difference between the executor's RT indexes and the + * scan-local RT indexes captured in that list. Both may be 0/NIL when the + * scan has no RTE_FUNCTION dependents. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, + List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1695,13 +1738,62 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION && rtfuncdata != NIL) + { + /* + * A whole-row Var points at a FUNCTION RTE absorbed into the + * foreign join. Synthesize an anonymous composite TupleDesc from + * the per-function return-type metadata we saved at plan time; + * the deparser emits these as ROW(f<rti>.c1, f<rti>.c2, ...). + */ + List *funcdata; + TupleDesc rte_tupdesc; + int num_funcs; + int attnum; + ListCell *lc1, + *lc2; + + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + if (funcdata == NIL) + continue; + num_funcs = list_length(funcdata); + Assert(num_funcs == list_length(rte->eref->colnames)); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc1, funcdata, lc2, rte->eref->colnames) + { + List *fdata = lfirst_node(List, lc1); + char *colname = strVal(lfirst(lc2)); + Oid funcrettype; + Oid funccollation; + + funcrettype = lsecond_node(Integer, fdata)->ival; + funccollation = lthird_node(Integer, fdata)->ival; + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, + "could not determine return type for function in foreign scan"); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funccollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1737,14 +1829,30 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. For a join, scan the base relids until we + * find an RTE_RELATION (the foreign-table side); ignore any RTE_FUNCTION + * absorbed into the join, which contributes no relation OID to look up. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); + rte = NULL; if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte != NULL && rte->rtekind == RTE_RELATION) + break; + rte = NULL; + } + if (rte == NULL) + elog(ERROR, "could not locate a foreign relation RTE in foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1787,8 +1895,19 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwScanPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwScanPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, + rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2941,7 +3060,15 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + /* + * DirectModify on a foreign join: pass NIL/0 for the function + * metadata. We don't currently push function RTEs through the + * direct-modify path, so there are no whole-row Vars pointing at + * function-RTE tuples to reconstruct. + */ + tupdesc = get_tupdesc_for_join_scan_tuples(node, NIL, 0); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -3054,7 +3181,8 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_length(fdw_private) > FdwScanPrivateRelations && + list_nth(fdw_private, FdwScanPrivateRelations) != NULL) { StringInfoData relations; char *rawrelations; @@ -3104,6 +3232,22 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); + + /* + * If a function RTE was absorbed into the foreign join, + * render it as "Function <alias>" since we have no foreign + * relid. + */ + if (rte->rtekind == RTE_FUNCTION) + { + refname = (char *) list_nth(es->rtable_names, rti - 1); + if (refname == NULL) + refname = rte->eref->aliasname; + appendStringInfo(&relations, "Function %s", + quote_identifier(refname)); + continue; + } + Assert(rte->rtekind == RTE_RELATION); /* This logic should agree with explain.c's ExplainTargetRel */ relname = get_rel_name(rte->relid); @@ -3479,8 +3623,17 @@ estimate_path_cost_size(PlannerInfo *root, /* For join we expect inner and outer relations set */ Assert(fpinfo->innerrel && fpinfo->outerrel); - fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; + /* + * For a FUNCTION RTE absorbed into the join, use the stub fpinfo + * we built in foreign_join_ok(), since the function rel itself + * has no fdw_private. + */ + fpinfo_i = fpinfo->inner_func_fpinfo ? + fpinfo->inner_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; + fpinfo_o = fpinfo->outer_func_fpinfo ? + fpinfo->outer_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; /* Estimate of number of rows in cross product */ nrows = fpinfo_i->rows * fpinfo_o->rows; @@ -6619,6 +6772,181 @@ semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, return ok; } +/* + * get_base_relids + * Return the set of base relids referenced by a foreign scan rel. + * + * For an upper rel we use the all-query relids minus the outer joins; + * otherwise the rel's own relids minus the outer joins. The result matches + * the relids that create_foreignscan_plan() ultimately uses for + * ForeignScan.fs_base_relids, so it is suitable for any tagging we want to + * store via plan-private state. + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + return bms_difference(relids, root->outer_join_rels); +} + +/* + * get_min_base_rti + * Lowest base RT index in the foreign scan rel. + * + * After setrefs.c flattens the rtable, the scan-local indexes saved in + * plan-private data can be translated to estate indexes by adding + * (ForeignScan.fs_base_relids min - this value). Captured at plan time + * because create_foreignscan_plan() computes the same value internally. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + +/* + * get_functions_data + * Build the per-RTE function metadata list saved as + * FdwScanPrivateFunctions. + * + * The result list is indexed by base RT index relative to the lowest base + * RT index of the scan. Each element is either NULL (for non-RTE_FUNCTION + * base rels in this scan) or a List of List of three Integer nodes: + * (funcid, funcrettype, funccollation) -- one inner list per RangeTblFunction. + * + * Only RTE_FUNCTION relids actually appearing in the foreign scan's + * fs_base_relids contribute; others are placeholders so that the consumer + * can index into the result by RTI offset. + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + Relids fscan_relids = get_base_relids(root, rel); + int i; + + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + List *funcdata = NIL; + ListCell *lc; + + if (rte == NULL || i == 0 || + !bms_is_member(i, fscan_relids) || + rte->rtekind != RTE_FUNCTION) + { + rtfuncdata = lappend(rtfuncdata, NULL); + continue; + } + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + Oid funcrettype; + Oid funccollation; + TupleDesc tupdesc; + Oid funcid = InvalidOid; + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, + "could not determine return type for function in foreign scan"); + + funccollation = exprCollation(rtfunc->funcexpr); + + if (IsA(rtfunc->funcexpr, FuncExpr)) + funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid; + + funcdata = lappend(funcdata, + list_make3(makeInteger(funcid), + makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + + return rtfuncdata; +} + +/* + * Check if a relation is a FUNCTION RTE that can be absorbed into a remote + * join. Every function in the RTE must + * + * - return a well-defined scalar type -- we don't ship records/composite + * since the remote server cannot reconstruct a column definition list + * and our deparser does not emit one; + * - have a shippable expression with no mutable subnodes -- is_foreign_expr() + * rejects volatile/stable functions through contain_mutable_functions(), + * so the IMMUTABLE-only restriction is implicit; + * - not contain SubPlans -- we'd otherwise need to ship sub-results to + * the remote, which we do not implement. + * + * WITH ORDINALITY is not supported yet. + */ +static bool +function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel, + RelOptInfo *fdwrel) +{ + RangeTblEntry *rte; + ListCell *lc; + + if (rel->rtekind != RTE_FUNCTION) + return false; + rte = planner_rt_fetch(rel->relid, root); + if (rte->rtekind != RTE_FUNCTION) + return false; + if (rte->funcordinality) + return false; + + /* + * Reject up-front any function RTE that lateral-references another + * relation: foreign-join push-down would need to parameterise the remote + * query per outer row, which we don't support, and even considering the + * path is expensive on the planner side. The surrounding lateral_relids + * check in postgresGetForeignJoinPaths() would normally bail out for the + * joinrel, but doing the check here avoids walking the function + * expression entirely. + */ + if (!bms_is_empty(rel->lateral_relids)) + return false; + + Assert(list_length(rte->functions) >= 1); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + TypeFuncClass functypclass; + Oid funcrettype; + TupleDesc tupdesc; + + functypclass = get_expr_result_type(rtfunc->funcexpr, + &funcrettype, &tupdesc); + if (functypclass != TYPEFUNC_SCALAR) + return false; + if (!OidIsValid(funcrettype) || + funcrettype == RECORDOID || + funcrettype == VOIDOID) + return false; + + if (contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, fdwrel, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -6634,6 +6962,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; + bool outer_is_function = false; + bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -6652,15 +6982,70 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, return false; /* - * If either of the joining relations is marked as unsafe to pushdown, the - * join can not be pushed down. + * Detect mixed (foreign x function-RTE) cases. Only INNER joins are + * supported initially. We dispatch on rtekind here so that the same + * function RTE can be absorbed into joins on multiple foreign servers + * (each call gets its own stub fpinfo and rechecks shippability for the + * specific server). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && + (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && + fpinfo_o->pushdown_safe && + function_rte_pushdown_ok(root, innerrel, outerrel)) + { + inner_is_function = true; + } + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) + { + outer_is_function = true; + } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } + + /* + * If one side is a function RTE, allocate a stub fpinfo so the rest of + * this function and the cost estimator can treat it uniformly. We hand + * the stub to the joinrel's deparser via the same path the foreign side + * uses, but we never permanently attach it to the function rel's + * fdw_private (different joinrels may pair the same function RTE with + * different foreign servers). + */ + if (inner_is_function) + { + fpinfo_i = palloc0_object(PgFdwRelationInfo); + fpinfo_i->pushdown_safe = true; + fpinfo_i->server = fpinfo_o->server; + fpinfo_i->relation_name = psprintf("%u", innerrel->relid); + fpinfo_i->rows = innerrel->rows; + fpinfo_i->width = innerrel->reltarget->width; + fpinfo_i->retrieved_rows = innerrel->rows; + fpinfo_i->rel_startup_cost = 0; + fpinfo_i->rel_total_cost = 0; + fpinfo->inner_func_fpinfo = fpinfo_i; + } + else if (outer_is_function) + { + fpinfo_o = palloc0_object(PgFdwRelationInfo); + fpinfo_o->pushdown_safe = true; + fpinfo_o->server = fpinfo_i->server; + fpinfo_o->relation_name = psprintf("%u", outerrel->relid); + fpinfo_o->rows = outerrel->rows; + fpinfo_o->width = outerrel->reltarget->width; + fpinfo_o->retrieved_rows = outerrel->rows; + fpinfo_o->rel_startup_cost = 0; + fpinfo_o->rel_total_cost = 0; + fpinfo->outer_func_fpinfo = fpinfo_o; + } /* * If joining relations have local conditions, those conditions are diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..5b2ffcf06f7 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -106,6 +106,16 @@ typedef struct PgFdwRelationInfo /* joinclauses contains only JOIN/ON conditions for an outer join */ List *joinclauses; /* List of RestrictInfo */ + /* + * If a FUNCTION RTE was absorbed into this join, these point at the stub + * PgFdwRelationInfo for the function side (paired with the + * outerrel/innerrel), so the cost estimator and deparser can find it + * without consulting the function rel's fdw_private. At most one of + * outer_func_fpinfo/inner_func_fpinfo is set. + */ + struct PgFdwRelationInfo *outer_func_fpinfo; + struct PgFdwRelationInfo *inner_func_fpinfo; + /* Upper relation information */ UpperRelationKind stage; diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 267d3c1a7e7..fbb0c3f2785 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -790,6 +790,168 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + +-- The remaining scenarios mirror the reproducers from Pyhalov's +-- v4-patch review (postgr.es/m/7e2abeb3ea9bc7ca024f4e457dce33f5%40postgrespro.ru), +-- so the same dedicated foreign table is reused for each. +CREATE TABLE base_tbl_pyh (a int, b int); +INSERT INTO base_tbl_pyh + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_pyh'); + +-- Pyhalov #3: function RTE appears first in FROM; the foreign relation +-- is found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + +-- Pyhalov #2: function returning record (composite) is forbidden; +-- pushing it would yield a remote "column definition list is required" +-- error. function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; +DROP FUNCTION f_ret_record(); + +-- Pyhalov #1: UPDATE ... FROM unnest() with a complex element type; +-- area(box) yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- now emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + +-- Pyhalov #4: same shape with CASE and RETURNING. Exercises the +-- DirectModify path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + +-- Pyhalov #5: ROWS FROM (...) with several functions. We force +-- pushdown because the cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; + +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_pyh; + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 3fc2c2f71d0..f21ae1baeb2 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -746,6 +746,30 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if (OidIsValid(outer_rel->serverid) && + inner_rel->rtekind == RTE_FUNCTION) + { + /* + * One side is a foreign relation, the other side is a function RTE. + * If the function is IMMUTABLE, the FDW can absorb the function call + * into the remote query (the result is identical regardless of which + * server evaluates it). Let the FDW decide whether the join is + * actually shippable; here we just propagate the FDW routine so the + * FDW gets a chance. + */ + joinrel->serverid = outer_rel->serverid; + joinrel->userid = outer_rel->userid; + joinrel->useridiscurrent = outer_rel->useridiscurrent; + joinrel->fdwroutine = outer_rel->fdwroutine; + } + else if (OidIsValid(inner_rel->serverid) && + outer_rel->rtekind == RTE_FUNCTION) + { + joinrel->serverid = inner_rel->serverid; + joinrel->userid = inner_rel->userid; + joinrel->useridiscurrent = inner_rel->useridiscurrent; + joinrel->fdwroutine = inner_rel->fdwroutine; + } } /* -- 2.39.5 (Apple Git-154)
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
@ 2026-05-18 20:06             ` Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2026-05-18 20:06 UTC (permalink / raw)
  To: Alexander Korotkov <aekorotkov@gmail.com>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Alexander Korotkov писал(а) 2026-05-18 13:34:
> Hi, Alexander!
> 
> The revised patch is attached.
> 
> On Tue, May 12, 2026 at 11:09 AM Alexander Pyhalov
> <a.pyhalov@postgrespro.ru> wrote:
>> 1) deparseColumnRef() doesn't account for whole row vars.
>> In queries like
>> 
>> UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) 
>> AS
>> t (bx) WHERE r.a = area(t.bx)
>> 
>> it fails with assert that varattno should be > 0. When we lock
>> non-relation RTE, we select whole row var, and we have to deparse it 
>> for
>> function RTE.
>> 
>> You've removed check for function return type. This seems to be
>> dangerous. Old example
>> 
>> CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ SELECT
>> (1,2)::record $$ language SQL IMMUTABLE;
>> ALTER EXTENSION postgres_fdw ADD function f_ret_record();
>> EXPLAIN (VERBOSE, COSTS OFF)
>> SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int)
>> WHERE s.a = rt.a;
>> 
>> fails with
>> 
>> ERROR:  a column definition list is required for functions returning
>> "record"
> 
> function_rte_pushdown_ok() now calls get_expr_result_type() and
> rejects anything that isn't TYPEFUNC_SCALAR (also RECORDOID/VOIDOID),
> so f_ret_record() no longer reaches the remote side.
> deparseColumnRef() now handles varattno == 0 for RTE_FUNCTION and
> emits ROW(f<rti>.c1, ..., f<rti>.c<N>) from rte->eref->colnames.
> 
>> 2) postgresBeginForeignScan() can step on function RTE, and doesn't 
>> know
>> what to do with it:
>> SELECT * FROM unnest(array[2,3,4]) n, remote_tbl r WHERE r.a = n;
>> ERROR:  cache lookup failed for foreign table 0
>> 
>> So, we need to look for the first RTE_RELATION, as in older patch
>> version.
> 
> The scanrelid == 0 branch in postgresBeginForeignScan() now scans
> fs_base_relids until it finds an RTE_RELATION.  An explicit
> elog(ERROR) guards the (theoretically impossible) case where no
> foreign RTE is found.
> 
>> 3) A lot of complexity in the old patch version was in making it
>> possible to find out RTE_FUNCTION attribute types after planing, as 
>> it's
>> necessary to correctly handle joins. In this version
>> get_tupdesc_for_join_scan_tuples() doesn't handle function RTEs.  This
>> means, when we try to find out type for attribute types for joins, 
>> we'll
>> get errors. This can be seen in queries like
>> 
>> UPDATE remote_tbl r SET b=CASE WHEN random()>=0 THEN 5 ELSE 0 END FROM
>> UNNEST(array[box '((2,3),(-2,-3))']) AS t (bx) WHERE r.a = area(t.bx)
>>   RETURNING a,b;
>> 
>> Now it fails on earlier stages (with "column f2.c0 does not exist"), 
>> but
>> if we fix it, we'll get something like
>> "ERROR:  input of anonymous composite types is not implemented"
>> 
>> Overall, function_rte_pushdown_ok() now allows more strange
>> constructions. Could it skip Vars from outside of joinrel->relids? Can
>> we safely ship function with parameters in arguments? I'm not sure.
> 
> Restored the per-function metadata you had in v2/v3.
> FdwScanPrivateFunctions (list of (funcid, funcrettype, funccollation)
> indexed by RTI-offset) and FdwScanPrivateMinRTIndex are now saved in
> fdw_private by postgresGetForeignPlan().
> get_tupdesc_for_join_scan_tuples() now has an RTE_FUNCTION branch that
> rebuilds the tuple descriptor from this metadata, exactly as in your
> patch.

Hi. I am a bit confused about this comment (and code):

                        /*
                         * DirectModify on a foreign join: pass NIL/0 for 
the function
                         * metadata.  We don't currently push function 
RTEs through the
                         * direct-modify path, so there are no whole-row 
Vars pointing at
                         * function-RTE tuples to reconstruct.
                         */
                        tupdesc = get_tupdesc_for_join_scan_tuples(node, 
NIL, 0);

We evidently go through this code path when executing example

UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS 
t (bx) WHERE r.a = area(t.bx)
  RETURNING a,b;

But don't need whole row var in returning list.... However, we still can 
step on this issue.

UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))'], 
array[int '1']) AS t (bx,  i) WHERE r.a = area(t.bx)
RETURNING a,b,t;

ERROR:  input of anonymous composite types is not implemented
CONTEXT:  whole-row reference to foreign table "t"

-- 
Best regards,
Alexander Pyhalov,
Postgres Professional





^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-05-19 13:00               ` Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Korotkov @ 2026-05-19 13:00 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi, Alexander.

On Mon, May 18, 2026 at 11:06 PM Alexander Pyhalov
<a.pyhalov@postgrespro.ru> wrote:
> Hi. I am a bit confused about this comment (and code):
>
>                         /*
>                          * DirectModify on a foreign join: pass NIL/0 for
> the function
>                          * metadata.  We don't currently push function
> RTEs through the
>                          * direct-modify path, so there are no whole-row
> Vars pointing at
>                          * function-RTE tuples to reconstruct.
>                          */
>                         tupdesc = get_tupdesc_for_join_scan_tuples(node,
> NIL, 0);
>
> We evidently go through this code path when executing example
>
> UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) AS
> t (bx) WHERE r.a = area(t.bx)
>   RETURNING a,b;
>
> But don't need whole row var in returning list.... However, we still can
> step on this issue.

Yes, we go through this code path, and it works as long as whole-row
var is not needed.

> UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))'],
> array[int '1']) AS t (bx,  i) WHERE r.a = area(t.bx)
> RETURNING a,b,t;
>
> ERROR:  input of anonymous composite types is not implemented
> CONTEXT:  whole-row reference to foreign table "t"

But if whole row var is actually used, then the assumption is broken.
So, we need to build a whole-row var anyway.  I've fixed this in the
attached patch, and added your sample query as a regression test case.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

v6-0001-postgres_fdw-push-down-FUNCTION-RTE-into-foreign-.patch (application/octet-stream, 56.1K) download From 039989553ee5dacb944839ffc7a92a19c6610f5c Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Sun, 10 May 2026 17:15:21 +0300 Subject: [PATCH v6] postgres_fdw: push down FUNCTION RTE into foreign joins A foreign join planning hook now considers a (foreign-table x function-RTE) INNER join as a push-down candidate when the function expression is IMMUTABLE and otherwise shippable. The remote query absorbs the function call as a FROM-list item (e.g. unnest(...) AS f<rti>(c1, c2, ...)), so the foreign side returns only rows that match the function-produced set and the join executes entirely on the remote. An IMMUTABLE function gives the same result on any server, so the same function RTE can be a push-down candidate for several distinct foreign servers without semantic risk. To keep the planner state consistent across those independent attempts, the per-call stub fpinfo for the function side lives on the joinrel's PgFdwRelationInfo (new outer_func_fpinfo / inner_func_fpinfo), never on the function rel itself, and the function side is detected via rtekind rather than fdw_private. set_foreign_rel_properties() propagates fdwroutine onto a joinrel that pairs a foreign rel with an RTE_FUNCTION rel so GetForeignJoinPaths gets called; the FDW retains full control over whether to actually generate a path. deparseRangeTblRef and deparseColumnRef gain a FUNCTION-RTE branch that emits the function expression and resolves Vars to the generated column aliases. --- contrib/postgres_fdw/deparse.c | 122 ++++- .../postgres_fdw/expected/postgres_fdw.out | 417 ++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 455 +++++++++++++++++- contrib/postgres_fdw/postgres_fdw.h | 10 + contrib/postgres_fdw/sql/postgres_fdw.sql | 173 +++++++ src/backend/optimizer/util/relnode.c | 24 + 6 files changed, 1177 insertions(+), 24 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 2dcc6c8af1b..f40fe52ea5b 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -112,6 +112,7 @@ typedef struct deparse_expr_cxt appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno)) #define SUBQUERY_REL_ALIAS_PREFIX "s" #define SUBQUERY_COL_ALIAS_PREFIX "c" +#define FUNCTION_REL_ALIAS_PREFIX "f" /* * Functions to determine whether an expression can be evaluated safely on @@ -2030,6 +2031,72 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, } } +/* + * Deparse a FUNCTION RTE absorbed into a foreign join. The function call(s) + * are emitted as a FROM-list item: + * + * <funcexpr> AS f<rti>(c1, c2, ..., cN) + * + * For multi-function RTEs (SQL ROWS FROM (f1(), f2(), ...)), each + * function call appears comma-separated inside ROWS FROM(...). Column + * aliases c1..cN cover the union of every function's columns, in the + * order they appear; that matches the column ordering of the RTE. + */ +static void +deparseFunctionRangeTblRef(StringInfo buf, PlannerInfo *root, + RelOptInfo *foreignrel, RelOptInfo *scanrel, + List **params_list) +{ + RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); + deparse_expr_cxt context; + ListCell *lc; + bool multi_func; + int total_cols = 0; + int i; + + Assert(rte->rtekind == RTE_FUNCTION); + Assert(!rte->funcordinality); + Assert(list_length(rte->functions) >= 1); + + multi_func = list_length(rte->functions) > 1; + + context.buf = buf; + context.root = root; + context.foreignrel = scanrel; + context.scanrel = scanrel; + context.params_list = params_list; + + if (multi_func) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (foreach_current_index(lc) > 0) + appendStringInfoString(buf, ", "); + deparseExpr((Expr *) rtfunc->funcexpr, &context); + total_cols += rtfunc->funccolcount; + } + + if (multi_func) + appendStringInfoChar(buf, ')'); + + /* Alias + generated column-name list. */ + appendStringInfo(buf, " %s%d", FUNCTION_REL_ALIAS_PREFIX, foreignrel->relid); + if (total_cols > 0) + { + appendStringInfoChar(buf, '('); + for (i = 1; i <= total_cols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + } +} + /* * Append FROM clause entry for the given relation into buf. * Conditions from lower-level SEMI-JOINs are appended to additional_conds @@ -2040,7 +2107,22 @@ deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **additional_conds, List **params_list) { - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + PgFdwRelationInfo *fpinfo; + + /* + * For a function RTE absorbed into a foreign join, deparse the function + * expression as a FROM-list item and return. The stub fpinfo set up by + * foreign_join_ok() may or may not be present here. + */ + if (foreignrel->rtekind == RTE_FUNCTION) + { + Assert(!make_subquery); + deparseFunctionRangeTblRef(buf, root, foreignrel, foreignrel, + params_list); + return; + } + + fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; /* Should only be called in these cases. */ Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel)); @@ -2712,6 +2794,44 @@ static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col) { + /* + * Function RTE columns: emit as f<varno>.c<varattno>, matching the + * aliases generated by deparseFunctionRangeTblRef(). A whole-row Var + * (varattno == 0) is rendered as ROW(f<varno>.c1, ..., f<varno>.c<N>) + * where N is the total column count of the function RTE (including all + * ROWS FROM (...) members). System attributes such as ctid have no + * meaning for function RTEs and are rejected. + */ + if (rte->rtekind == RTE_FUNCTION) + { + if (varattno == 0) + { + int ncols = list_length(rte->eref->colnames); + int i; + + appendStringInfoString(buf, "ROW("); + for (i = 1; i <= ncols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d.%s%d", + FUNCTION_REL_ALIAS_PREFIX, varno, + SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + return; + } + + if (varattno < 0) + elog(ERROR, + "system attribute reference to a function RTE is not supported in foreign join pushdown"); + + if (qualify_col) + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, varattno); + return; + } + /* We support fetching the remote side's CTID and OID. */ if (varattno == SelfItemPointerAttributeNumber) { diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index e90289e4ab1..342eefbb9cc 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2885,6 +2885,423 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c (10 rows) ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: t1.c1, t1.c3 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1, t1.c3 + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", r1.c3 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{1,5,10,100}'::integer[]) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + c1 | c3 +-----+------- + 1 | 00001 + 5 | 00005 + 10 | 00010 + 100 | 00100 +(4 rows) + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Sort + Output: t1.c1 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1 + Relations: (public.ft1 t1) INNER JOIN (Function g) + Remote SQL: SELECT r1."C 1" FROM ("S 1"."T 1" r1 INNER JOIN generate_series(1, 4) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + c1 +---- + 1 + 2 + 3 + 4 +(4 rows) + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on pg_catalog.generate_series g + Output: g.id + Function Call: generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + QUERY PLAN +------------------------------------------------------------ + Hash Join + Output: t1.c1, u.ord + Hash Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" + -> Hash + Output: u.ord, u.id + -> Function Scan on pg_catalog.unnest u + Output: u.ord, u.id + Function Call: unnest('{1,5,10}'::integer[]) +(11 rows) + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: t1.c1, t2.c1 + Merge Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST + -> Sort + Output: t2.c1, u.id + Sort Key: t2.c1 + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{1,5,10,100}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(13 rows) + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: t1.c1, t2.c1 + Hash Cond: (t1.c1 = t2.c1) + -> Foreign Scan + Output: t1.c1, u.id + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", f3.c1 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r1."C 1" = f3.c1)))) + -> Hash + Output: t2.c1 + -> Foreign Scan on public.ft6 t2 + Output: t2.c1 + Remote SQL: SELECT c1 FROM "S 1"."T 4" +(12 rows) + +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: t1.c1, t2.c1 + Join Filter: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE ((c3 < '00010')) + -> Materialize + Output: t2.c1, u.id + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(12 rows) + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (Function n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + n | a | b +---+---+----- + 2 | 2 | 102 + 3 | 3 | 103 + 4 | 4 | 104 +(3 rows) + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: s.* + Hash Cond: (rt.a = s.a) + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl_fn + -> Hash + Output: s.*, s.a + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() +(11 rows) + +DROP FUNCTION f_ret_record(); +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + a | b +----+----- + 23 | 123 + 24 | 999 + 25 | 125 +(3 rows) + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + a | b +----+--- + 24 | 5 +(1 row) + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + a | b | t +----+---+--------------------- + 24 | 7 | ("(2,3),(-2,-3)",1) +(1 row) + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: r.a, t.n, t.s + Sort Key: r.a + -> Foreign Scan + Output: r.a, t.n, t.s + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT r1.a, f2.c1, f2.c2 FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + a | n | s +---+---+---- + 3 | 3 | 11 + 6 | 6 | 12 + 9 | 9 | 13 +(3 rows) + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: ((t.*)::text), r.a + Sort Key: r.a + -> Foreign Scan + Output: (t.*)::text, r.a + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT ROW(f2.c1, f2.c2), r1.a FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + t | a +--------+--- + (3,11) | 3 + (6,12) | 6 + (9,13) | 9 +(3 rows) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: r.a + Merge Cond: (t.n = r.a) + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]), generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Sort + Output: r.a + Sort Key: r.a + -> Foreign Scan on public.remote_tbl r + Output: r.a + Remote SQL: SELECT a FROM public.base_tbl_fn +(15 rows) + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Nested Loop + Output: r.a, t.x + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 3)) ORDER BY a ASC NULLS LAST + -> Function Scan on pg_catalog.unnest t + Output: t.x + Function Call: unnest(ARRAY[r.a]) +(8 rows) + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Merge Left Join + Output: r.a, t.n + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 5)) ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{1,2,3}'::integer[]) +(12 rows) + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + QUERY PLAN +-------------------------------------------------------------------------------- + Merge Semi Join + Output: r.a + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]) +(12 rows) + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 0a589f8db74..9cb6a1772d9 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -31,6 +31,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/appendinfo.h" +#include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" #include "optimizer/optimizer.h" @@ -88,6 +89,22 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of per-RTE function metadata, indexed by base RTI offset. Each + * element is either NULL (for non-RTE_FUNCTION rels in this scan) or a + * list of three-element lists (funcid, funcrettype, funccollation) -- one + * inner list per function in the RTE. Allows the executor to rebuild + * TupleDesc entries for whole-row references to function RTEs. + */ + FdwScanPrivateFunctions, + + /* + * Integer node: minimum base RT index covered by the scan, used to + * translate scan-local indexes to estate-rtable indexes after setrefs.c + * flattens rtables. + */ + FdwScanPrivateMinRTIndex, }; /* @@ -124,6 +141,11 @@ enum FdwModifyPrivateIndex * 2) Boolean flag showing if the remote query has a RETURNING clause * 3) Integer list of attribute numbers retrieved by RETURNING, if any * 4) Boolean flag showing if we set the command es_processed + * 5) Per-RTE function metadata (mirrors FdwScanPrivateFunctions; lets + * the executor rebuild TupleDesc entries for whole-row Vars over + * function RTEs absorbed into a foreign join) + * 6) Integer node: minimum base RT index of the scan (mirrors + * FdwScanPrivateMinRTIndex) */ enum FdwDirectModifyPrivateIndex { @@ -135,6 +157,10 @@ enum FdwDirectModifyPrivateIndex FdwDirectModifyPrivateRetrievedAttrs, /* set-processed flag (as a Boolean node) */ FdwDirectModifyPrivateSetProcessed, + /* Per-RTE function metadata, indexed by base RTI offset */ + FdwDirectModifyPrivateFunctions, + /* Integer node: minimum base RT index in the scan */ + FdwDirectModifyPrivateMinRTIndex, }; /* @@ -741,6 +767,9 @@ static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, static List *get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel); static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, Path *epq_path, List *restrictlist); static void add_foreign_grouping_paths(PlannerInfo *root, @@ -1635,9 +1664,26 @@ postgresGetForeignPlan(PlannerInfo *root, fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(fpinfo->fetch_size)); + + /* + * Position FdwScanPrivateRelations: either the EXPLAIN relation string + * (joins/upper rels) or a NULL placeholder, so that subsequent indexes + * stay valid for the base-rel scan case. + */ if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + /* + * FdwScanPrivateFunctions / FdwScanPrivateMinRTIndex carry the metadata + * the executor needs to rebuild TupleDesc entries for whole-row Vars + * pointing at RTE_FUNCTION rels absorbed into the foreign scan. + */ + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + fdw_private = lappend(fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1658,9 +1704,15 @@ postgresGetForeignPlan(PlannerInfo *root, /* * Construct a tuple descriptor for the scan tuples handled by a foreign join. + * + * 'rtfuncdata' is the FdwScanPrivateFunctions list saved at plan time, and + * 'rtoffset' is the difference between the executor's RT indexes and the + * scan-local RT indexes captured in that list. Both may be 0/NIL when the + * scan has no RTE_FUNCTION dependents. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, + List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1696,13 +1748,62 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION && rtfuncdata != NIL) + { + /* + * A whole-row Var points at a FUNCTION RTE absorbed into the + * foreign join. Synthesize an anonymous composite TupleDesc from + * the per-function return-type metadata we saved at plan time; + * the deparser emits these as ROW(f<rti>.c1, f<rti>.c2, ...). + */ + List *funcdata; + TupleDesc rte_tupdesc; + int num_funcs; + int attnum; + ListCell *lc1, + *lc2; + + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + if (funcdata == NIL) + continue; + num_funcs = list_length(funcdata); + Assert(num_funcs == list_length(rte->eref->colnames)); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc1, funcdata, lc2, rte->eref->colnames) + { + List *fdata = lfirst_node(List, lc1); + char *colname = strVal(lfirst(lc2)); + Oid funcrettype; + Oid funccollation; + + funcrettype = lsecond_node(Integer, fdata)->ival; + funccollation = lthird_node(Integer, fdata)->ival; + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, + "could not determine return type for function in foreign scan"); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funccollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1738,14 +1839,30 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. For a join, scan the base relids until we + * find an RTE_RELATION (the foreign-table side); ignore any RTE_FUNCTION + * absorbed into the join, which contributes no relation OID to look up. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); + rte = NULL; if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte != NULL && rte->rtekind == RTE_RELATION) + break; + rte = NULL; + } + if (rte == NULL) + elog(ERROR, "could not locate a foreign relation RTE in foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1788,8 +1905,19 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwScanPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwScanPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, + rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2829,6 +2957,10 @@ postgresPlanDirectModify(PlannerInfo *root, makeBoolean((retrieved_attrs != NIL)), retrieved_attrs, makeBoolean(plan->canSetTag)); + fscan->fdw_private = lappend(fscan->fdw_private, + get_functions_data(root, foreignrel)); + fscan->fdw_private = lappend(fscan->fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Update the foreign-join-related fields. @@ -2942,7 +3074,26 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + /* + * DirectModify on a foreign join: use the per-RTE function + * metadata saved at plan time so a whole-row Var pointing at a + * function RTE absorbed into the join can be rebuilt into a + * usable TupleDesc (e.g. RETURNING t for a join with UNNEST(..., + * ...) AS t(bx, i)). + */ + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + + tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -3055,7 +3206,8 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_length(fdw_private) > FdwScanPrivateRelations && + list_nth(fdw_private, FdwScanPrivateRelations) != NULL) { StringInfoData relations; char *rawrelations; @@ -3105,6 +3257,22 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); + + /* + * If a function RTE was absorbed into the foreign join, + * render it as "Function <alias>" since we have no foreign + * relid. + */ + if (rte->rtekind == RTE_FUNCTION) + { + refname = (char *) list_nth(es->rtable_names, rti - 1); + if (refname == NULL) + refname = rte->eref->aliasname; + appendStringInfo(&relations, "Function %s", + quote_identifier(refname)); + continue; + } + Assert(rte->rtekind == RTE_RELATION); /* This logic should agree with explain.c's ExplainTargetRel */ relname = get_rel_name(rte->relid); @@ -3480,8 +3648,17 @@ estimate_path_cost_size(PlannerInfo *root, /* For join we expect inner and outer relations set */ Assert(fpinfo->innerrel && fpinfo->outerrel); - fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; + /* + * For a FUNCTION RTE absorbed into the join, use the stub fpinfo + * we built in foreign_join_ok(), since the function rel itself + * has no fdw_private. + */ + fpinfo_i = fpinfo->inner_func_fpinfo ? + fpinfo->inner_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; + fpinfo_o = fpinfo->outer_func_fpinfo ? + fpinfo->outer_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; /* Estimate of number of rows in cross product */ nrows = fpinfo_i->rows * fpinfo_o->rows; @@ -6639,6 +6816,181 @@ semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, return ok; } +/* + * get_base_relids + * Return the set of base relids referenced by a foreign scan rel. + * + * For an upper rel we use the all-query relids minus the outer joins; + * otherwise the rel's own relids minus the outer joins. The result matches + * the relids that create_foreignscan_plan() ultimately uses for + * ForeignScan.fs_base_relids, so it is suitable for any tagging we want to + * store via plan-private state. + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + return bms_difference(relids, root->outer_join_rels); +} + +/* + * get_min_base_rti + * Lowest base RT index in the foreign scan rel. + * + * After setrefs.c flattens the rtable, the scan-local indexes saved in + * plan-private data can be translated to estate indexes by adding + * (ForeignScan.fs_base_relids min - this value). Captured at plan time + * because create_foreignscan_plan() computes the same value internally. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + +/* + * get_functions_data + * Build the per-RTE function metadata list saved as + * FdwScanPrivateFunctions. + * + * The result list is indexed by base RT index relative to the lowest base + * RT index of the scan. Each element is either NULL (for non-RTE_FUNCTION + * base rels in this scan) or a List of List of three Integer nodes: + * (funcid, funcrettype, funccollation) -- one inner list per RangeTblFunction. + * + * Only RTE_FUNCTION relids actually appearing in the foreign scan's + * fs_base_relids contribute; others are placeholders so that the consumer + * can index into the result by RTI offset. + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + Relids fscan_relids = get_base_relids(root, rel); + int i; + + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + List *funcdata = NIL; + ListCell *lc; + + if (rte == NULL || i == 0 || + !bms_is_member(i, fscan_relids) || + rte->rtekind != RTE_FUNCTION) + { + rtfuncdata = lappend(rtfuncdata, NULL); + continue; + } + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + Oid funcrettype; + Oid funccollation; + TupleDesc tupdesc; + Oid funcid = InvalidOid; + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, + "could not determine return type for function in foreign scan"); + + funccollation = exprCollation(rtfunc->funcexpr); + + if (IsA(rtfunc->funcexpr, FuncExpr)) + funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid; + + funcdata = lappend(funcdata, + list_make3(makeInteger(funcid), + makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + + return rtfuncdata; +} + +/* + * Check if a relation is a FUNCTION RTE that can be absorbed into a remote + * join. Every function in the RTE must + * + * - return a well-defined scalar type -- we don't ship records/composite + * since the remote server cannot reconstruct a column definition list + * and our deparser does not emit one; + * - have a shippable expression with no mutable subnodes -- is_foreign_expr() + * rejects volatile/stable functions through contain_mutable_functions(), + * so the IMMUTABLE-only restriction is implicit; + * - not contain SubPlans -- we'd otherwise need to ship sub-results to + * the remote, which we do not implement. + * + * WITH ORDINALITY is not supported yet. + */ +static bool +function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel, + RelOptInfo *fdwrel) +{ + RangeTblEntry *rte; + ListCell *lc; + + if (rel->rtekind != RTE_FUNCTION) + return false; + rte = planner_rt_fetch(rel->relid, root); + if (rte->rtekind != RTE_FUNCTION) + return false; + if (rte->funcordinality) + return false; + + /* + * Reject up-front any function RTE that lateral-references another + * relation: foreign-join push-down would need to parameterise the remote + * query per outer row, which we don't support, and even considering the + * path is expensive on the planner side. The surrounding lateral_relids + * check in postgresGetForeignJoinPaths() would normally bail out for the + * joinrel, but doing the check here avoids walking the function + * expression entirely. + */ + if (!bms_is_empty(rel->lateral_relids)) + return false; + + Assert(list_length(rte->functions) >= 1); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + TypeFuncClass functypclass; + Oid funcrettype; + TupleDesc tupdesc; + + functypclass = get_expr_result_type(rtfunc->funcexpr, + &funcrettype, &tupdesc); + if (functypclass != TYPEFUNC_SCALAR) + return false; + if (!OidIsValid(funcrettype) || + funcrettype == RECORDOID || + funcrettype == VOIDOID) + return false; + + if (contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, fdwrel, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -6654,6 +7006,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; + bool outer_is_function = false; + bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -6672,15 +7026,70 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, return false; /* - * If either of the joining relations is marked as unsafe to pushdown, the - * join can not be pushed down. + * Detect mixed (foreign x function-RTE) cases. Only INNER joins are + * supported initially. We dispatch on rtekind here so that the same + * function RTE can be absorbed into joins on multiple foreign servers + * (each call gets its own stub fpinfo and rechecks shippability for the + * specific server). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && + (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && + fpinfo_o->pushdown_safe && + function_rte_pushdown_ok(root, innerrel, outerrel)) + { + inner_is_function = true; + } + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) + { + outer_is_function = true; + } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } + + /* + * If one side is a function RTE, allocate a stub fpinfo so the rest of + * this function and the cost estimator can treat it uniformly. We hand + * the stub to the joinrel's deparser via the same path the foreign side + * uses, but we never permanently attach it to the function rel's + * fdw_private (different joinrels may pair the same function RTE with + * different foreign servers). + */ + if (inner_is_function) + { + fpinfo_i = palloc0_object(PgFdwRelationInfo); + fpinfo_i->pushdown_safe = true; + fpinfo_i->server = fpinfo_o->server; + fpinfo_i->relation_name = psprintf("%u", innerrel->relid); + fpinfo_i->rows = innerrel->rows; + fpinfo_i->width = innerrel->reltarget->width; + fpinfo_i->retrieved_rows = innerrel->rows; + fpinfo_i->rel_startup_cost = 0; + fpinfo_i->rel_total_cost = 0; + fpinfo->inner_func_fpinfo = fpinfo_i; + } + else if (outer_is_function) + { + fpinfo_o = palloc0_object(PgFdwRelationInfo); + fpinfo_o->pushdown_safe = true; + fpinfo_o->server = fpinfo_i->server; + fpinfo_o->relation_name = psprintf("%u", outerrel->relid); + fpinfo_o->rows = outerrel->rows; + fpinfo_o->width = outerrel->reltarget->width; + fpinfo_o->retrieved_rows = outerrel->rows; + fpinfo_o->rel_startup_cost = 0; + fpinfo_o->rel_total_cost = 0; + fpinfo->outer_func_fpinfo = fpinfo_o; + } /* * If joining relations have local conditions, those conditions are diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..5b2ffcf06f7 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -106,6 +106,16 @@ typedef struct PgFdwRelationInfo /* joinclauses contains only JOIN/ON conditions for an outer join */ List *joinclauses; /* List of RestrictInfo */ + /* + * If a FUNCTION RTE was absorbed into this join, these point at the stub + * PgFdwRelationInfo for the function side (paired with the + * outerrel/innerrel), so the cost estimator and deparser can find it + * without consulting the function rel's fdw_private. At most one of + * outer_func_fpinfo/inner_func_fpinfo is set. + */ + struct PgFdwRelationInfo *outer_func_fpinfo; + struct PgFdwRelationInfo *inner_func_fpinfo; + /* Upper relation information */ UpperRelationKind stage; diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index dfc58beb0d2..95b4d7646fa 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -790,6 +790,179 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); + +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; +DROP FUNCTION f_ret_record(); + +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; + +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 3fc2c2f71d0..f21ae1baeb2 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -746,6 +746,30 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if (OidIsValid(outer_rel->serverid) && + inner_rel->rtekind == RTE_FUNCTION) + { + /* + * One side is a foreign relation, the other side is a function RTE. + * If the function is IMMUTABLE, the FDW can absorb the function call + * into the remote query (the result is identical regardless of which + * server evaluates it). Let the FDW decide whether the join is + * actually shippable; here we just propagate the FDW routine so the + * FDW gets a chance. + */ + joinrel->serverid = outer_rel->serverid; + joinrel->userid = outer_rel->userid; + joinrel->useridiscurrent = outer_rel->useridiscurrent; + joinrel->fdwroutine = outer_rel->fdwroutine; + } + else if (OidIsValid(inner_rel->serverid) && + outer_rel->rtekind == RTE_FUNCTION) + { + joinrel->serverid = inner_rel->serverid; + joinrel->userid = inner_rel->userid; + joinrel->useridiscurrent = inner_rel->useridiscurrent; + joinrel->fdwroutine = inner_rel->fdwroutine; + } } /* -- 2.39.5 (Apple Git-154)
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
@ 2026-05-19 15:25                 ` Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2026-05-19 15:25 UTC (permalink / raw)
  To: Alexander Korotkov <aekorotkov@gmail.com>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Alexander Korotkov писал(а) 2026-05-19 16:00:
> Hi, Alexander.
> 
> On Mon, May 18, 2026 at 11:06 PM Alexander Pyhalov
> <a.pyhalov@postgrespro.ru> wrote:
>> Hi. I am a bit confused about this comment (and code):
>> 
>>                         /*
>>                          * DirectModify on a foreign join: pass NIL/0 
>> for
>> the function
>>                          * metadata.  We don't currently push function
>> RTEs through the
>>                          * direct-modify path, so there are no 
>> whole-row
>> Vars pointing at
>>                          * function-RTE tuples to reconstruct.
>>                          */
>>                         tupdesc = 
>> get_tupdesc_for_join_scan_tuples(node,
>> NIL, 0);
>> 
>> We evidently go through this code path when executing example
>> 
>> UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))']) 
>> AS
>> t (bx) WHERE r.a = area(t.bx)
>>   RETURNING a,b;
>> 
>> But don't need whole row var in returning list.... However, we still 
>> can
>> step on this issue.
> 
> Yes, we go through this code path, and it works as long as whole-row
> var is not needed.
> 
>> UPDATE remote_tbl r SET b=5 FROM UNNEST(array[box '((2,3),(-2,-3))'],
>> array[int '1']) AS t (bx,  i) WHERE r.a = area(t.bx)
>> RETURNING a,b,t;
>> 
>> ERROR:  input of anonymous composite types is not implemented
>> CONTEXT:  whole-row reference to foreign table "t"
> 
> But if whole row var is actually used, then the assumption is broken.
> So, we need to build a whole-row var anyway.  I've fixed this in the
> attached patch, and added your sample query as a regression test case.
> 

Good evening.

Found one more issue in whole row var deparsing. It can appear on a 
nullable outer side, and we should use the same logic as when deparsing 
table column reference. Otherwise we get records from nulls instead of 
nulls (for example, "(NULL, NULL)" instead of NULL).

Also I wonder if it is possible for get_tupdesc_for_join_scan_tuples() 
to get NULL rtfuncdata when it looks at RTE_FUNCTION RTE here:

1759                 else if (rte->rtekind == RTE_FUNCTION && rtfuncdata 
!= NIL)
1760                 {
1761                         /*
1762                          * A whole-row Var points at a FUNCTION RTE 
absorbed into the
1763                          * foreign join.  Synthesize an anonymous 
composite TupleDesc from
1764                          * the per-function return-type metadata we 
saved at plan time;
1765                          * the deparser emits these as 
ROW(f<rti>.c1, f<rti>.c2, ...).
1766                          */
1767                         List       *funcdata;
1768                         TupleDesc       rte_tupdesc;
1769                         int                     num_funcs;
1770                         int                     attnum;
1771                         ListCell   *lc1,

?

-- 
Best regards,
Alexander Pyhalov,
Postgres Professional

Attachments:

v7-0001-postgres_fdw-push-down-FUNCTION-RTE-into-foreign-.patch (text/x-diff, 58.7K) download From 2b78decae1c0d333ca04bd1394012f43cb14aea3 Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Tue, 19 May 2026 16:28:22 +0300 Subject: [PATCH] postgres_fdw: push down FUNCTION RTE into foreign joins A foreign join planning hook now considers a (foreign-table x function-RTE) INNER join as a push-down candidate when the function expression is IMMUTABLE and otherwise shippable. The remote query absorbs the function call as a FROM-list item (e.g. unnest(...) AS f<rti>(c1, c2, ...)), so the foreign side returns only rows that match the function-produced set and the join executes entirely on the remote. An IMMUTABLE function gives the same result on any server, so the same function RTE can be a push-down candidate for several distinct foreign servers without semantic risk. To keep the planner state consistent across those independent attempts, the per-call stub fpinfo for the function side lives on the joinrel's PgFdwRelationInfo (new outer_func_fpinfo / inner_func_fpinfo), never on the function rel itself, and the function side is detected via rtekind rather than fdw_private. set_foreign_rel_properties() propagates fdwroutine onto a joinrel that pairs a foreign rel with an RTE_FUNCTION rel so GetForeignJoinPaths gets called; the FDW retains full control over whether to actually generate a path. deparseRangeTblRef and deparseColumnRef gain a FUNCTION-RTE branch that emits the function expression and resolves Vars to the generated column aliases. --- contrib/postgres_fdw/deparse.c | 132 ++++- .../postgres_fdw/expected/postgres_fdw.out | 441 +++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 455 +++++++++++++++++- contrib/postgres_fdw/postgres_fdw.h | 10 + contrib/postgres_fdw/sql/postgres_fdw.sql | 183 +++++++ src/backend/optimizer/util/relnode.c | 24 + 6 files changed, 1221 insertions(+), 24 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 2dcc6c8af1b..5567fdb8ed9 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -112,6 +112,7 @@ typedef struct deparse_expr_cxt appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno)) #define SUBQUERY_REL_ALIAS_PREFIX "s" #define SUBQUERY_COL_ALIAS_PREFIX "c" +#define FUNCTION_REL_ALIAS_PREFIX "f" /* * Functions to determine whether an expression can be evaluated safely on @@ -2030,6 +2031,72 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, } } +/* + * Deparse a FUNCTION RTE absorbed into a foreign join. The function call(s) + * are emitted as a FROM-list item: + * + * <funcexpr> AS f<rti>(c1, c2, ..., cN) + * + * For multi-function RTEs (SQL ROWS FROM (f1(), f2(), ...)), each + * function call appears comma-separated inside ROWS FROM(...). Column + * aliases c1..cN cover the union of every function's columns, in the + * order they appear; that matches the column ordering of the RTE. + */ +static void +deparseFunctionRangeTblRef(StringInfo buf, PlannerInfo *root, + RelOptInfo *foreignrel, RelOptInfo *scanrel, + List **params_list) +{ + RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); + deparse_expr_cxt context; + ListCell *lc; + bool multi_func; + int total_cols = 0; + int i; + + Assert(rte->rtekind == RTE_FUNCTION); + Assert(!rte->funcordinality); + Assert(list_length(rte->functions) >= 1); + + multi_func = list_length(rte->functions) > 1; + + context.buf = buf; + context.root = root; + context.foreignrel = scanrel; + context.scanrel = scanrel; + context.params_list = params_list; + + if (multi_func) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (foreach_current_index(lc) > 0) + appendStringInfoString(buf, ", "); + deparseExpr((Expr *) rtfunc->funcexpr, &context); + total_cols += rtfunc->funccolcount; + } + + if (multi_func) + appendStringInfoChar(buf, ')'); + + /* Alias + generated column-name list. */ + appendStringInfo(buf, " %s%d", FUNCTION_REL_ALIAS_PREFIX, foreignrel->relid); + if (total_cols > 0) + { + appendStringInfoChar(buf, '('); + for (i = 1; i <= total_cols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + } +} + /* * Append FROM clause entry for the given relation into buf. * Conditions from lower-level SEMI-JOINs are appended to additional_conds @@ -2040,7 +2107,22 @@ deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **additional_conds, List **params_list) { - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + PgFdwRelationInfo *fpinfo; + + /* + * For a function RTE absorbed into a foreign join, deparse the function + * expression as a FROM-list item and return. The stub fpinfo set up by + * foreign_join_ok() may or may not be present here. + */ + if (foreignrel->rtekind == RTE_FUNCTION) + { + Assert(!make_subquery); + deparseFunctionRangeTblRef(buf, root, foreignrel, foreignrel, + params_list); + return; + } + + fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; /* Should only be called in these cases. */ Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel)); @@ -2712,6 +2794,54 @@ static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col) { + /* + * Function RTE columns: emit as f<varno>.c<varattno>, matching the + * aliases generated by deparseFunctionRangeTblRef(). A whole-row Var + * (varattno == 0) is rendered as ROW(f<varno>.c1, ..., f<varno>.c<N>) + * where N is the total column count of the function RTE (including all + * ROWS FROM (...) members). System attributes such as ctid have no + * meaning for function RTEs and are rejected. + */ + if (rte->rtekind == RTE_FUNCTION) + { + if (varattno == 0) + { + int ncols = list_length(rte->eref->colnames); + int i; + + if (qualify_col) + { + appendStringInfoString(buf, "CASE WHEN ("); + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfoString(buf, "*)::text IS NOT NULL THEN "); + } + + appendStringInfoString(buf, "ROW("); + for (i = 1; i <= ncols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d.%s%d", + FUNCTION_REL_ALIAS_PREFIX, varno, + SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + + if (qualify_col) + appendStringInfoString(buf, " END"); + return; + } + + if (varattno < 0) + elog(ERROR, + "system attribute reference to a function RTE is not supported in foreign join pushdown"); + + if (qualify_col) + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, varattno); + return; + } + /* We support fetching the remote side's CTID and OID. */ if (varattno == SelfItemPointerAttributeNumber) { diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index aaffcf31271..c21d0876d39 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2885,6 +2885,447 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c (10 rows) ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: t1.c1, t1.c3 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1, t1.c3 + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", r1.c3 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{1,5,10,100}'::integer[]) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + c1 | c3 +-----+------- + 1 | 00001 + 5 | 00005 + 10 | 00010 + 100 | 00100 +(4 rows) + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Sort + Output: t1.c1 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1 + Relations: (public.ft1 t1) INNER JOIN (Function g) + Remote SQL: SELECT r1."C 1" FROM ("S 1"."T 1" r1 INNER JOIN generate_series(1, 4) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + c1 +---- + 1 + 2 + 3 + 4 +(4 rows) + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on pg_catalog.generate_series g + Output: g.id + Function Call: generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + QUERY PLAN +------------------------------------------------------------ + Hash Join + Output: t1.c1, u.ord + Hash Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" + -> Hash + Output: u.ord, u.id + -> Function Scan on pg_catalog.unnest u + Output: u.ord, u.id + Function Call: unnest('{1,5,10}'::integer[]) +(11 rows) + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: t1.c1, t2.c1 + Merge Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST + -> Sort + Output: t2.c1, u.id + Sort Key: t2.c1 + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{1,5,10,100}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(13 rows) + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: t1.c1, t2.c1 + Hash Cond: (t1.c1 = t2.c1) + -> Foreign Scan + Output: t1.c1, u.id + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", f3.c1 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r1."C 1" = f3.c1)))) + -> Hash + Output: t2.c1 + -> Foreign Scan on public.ft6 t2 + Output: t2.c1 + Remote SQL: SELECT c1 FROM "S 1"."T 4" +(12 rows) + +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: t1.c1, t2.c1 + Join Filter: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE ((c3 < '00010')) + -> Materialize + Output: t2.c1, u.id + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(12 rows) + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (Function n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + n | a | b +---+---+----- + 2 | 2 | 102 + 3 | 3 | 103 + 4 | 4 | 104 +(3 rows) + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: s.* + Hash Cond: (rt.a = s.a) + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl_fn + -> Hash + Output: s.*, s.a + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() +(11 rows) + +DROP FUNCTION f_ret_record(); +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + a | b +----+----- + 23 | 123 + 24 | 999 + 25 | 125 +(3 rows) + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + a | b +----+--- + 24 | 5 +(1 row) + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + a | b | t +----+---+--------------------- + 24 | 7 | ("(2,3),(-2,-3)",1) +(1 row) + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: r.a, t.n, t.s + Sort Key: r.a + -> Foreign Scan + Output: r.a, t.n, t.s + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT r1.a, f2.c1, f2.c2 FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + a | n | s +---+---+---- + 3 | 3 | 11 + 6 | 6 | 12 + 9 | 9 | 13 +(3 rows) + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: ((t.*)::text), r.a + Sort Key: r.a + -> Foreign Scan + Output: (t.*)::text, r.a + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT CASE WHEN (f2.*)::text IS NOT NULL THEN ROW(f2.c1, f2.c2) END, r1.a FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + t | a +--------+--- + (3,11) | 3 + (6,12) | 6 + (9,13) | 9 +(3 rows) + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: u.*, ft5.c1, ft5.c2, ft4.c1, ft4.c2 + Relations: (public.ft5) LEFT JOIN ((public.ft4) INNER JOIN (Function u)) + Remote SQL: SELECT CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END, r1.c1, r1.c2, r2.c1, r2.c2 FROM ("S 1"."T 4" r1 LEFT JOIN ("S 1"."T 3" r2 INNER JOIN ROWS FROM (unnest('{1,2}'::integer[]), unnest('{3,4}'::integer[])) f3(c1, c2) ON (((r2.c1 = f3.c1)))) ON (((r1.c1 = r2.c1)))) WHERE ((r1.c1 < 10)) ORDER BY r1.c1 ASC NULLS LAST +(4 rows) + +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + u | c1 | c2 | c1 | c2 +---+----+----+----+---- + | 3 | 4 | | + | 6 | 7 | | + | 9 | 10 | | +(3 rows) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: r.a + Merge Cond: (t.n = r.a) + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]), generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Sort + Output: r.a + Sort Key: r.a + -> Foreign Scan on public.remote_tbl r + Output: r.a + Remote SQL: SELECT a FROM public.base_tbl_fn +(15 rows) + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Nested Loop + Output: r.a, t.x + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 3)) ORDER BY a ASC NULLS LAST + -> Function Scan on pg_catalog.unnest t + Output: t.x + Function Call: unnest(ARRAY[r.a]) +(8 rows) + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Merge Left Join + Output: r.a, t.n + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 5)) ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{1,2,3}'::integer[]) +(12 rows) + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + QUERY PLAN +-------------------------------------------------------------------------------- + Merge Semi Join + Output: r.a + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]) +(12 rows) + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 0ff4ec23164..dc552a847d8 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -31,6 +31,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/appendinfo.h" +#include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" #include "optimizer/optimizer.h" @@ -88,6 +89,22 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of per-RTE function metadata, indexed by base RTI offset. Each + * element is either NULL (for non-RTE_FUNCTION rels in this scan) or a + * list of three-element lists (funcid, funcrettype, funccollation) -- one + * inner list per function in the RTE. Allows the executor to rebuild + * TupleDesc entries for whole-row references to function RTEs. + */ + FdwScanPrivateFunctions, + + /* + * Integer node: minimum base RT index covered by the scan, used to + * translate scan-local indexes to estate-rtable indexes after setrefs.c + * flattens rtables. + */ + FdwScanPrivateMinRTIndex, }; /* @@ -124,6 +141,11 @@ enum FdwModifyPrivateIndex * 2) Boolean flag showing if the remote query has a RETURNING clause * 3) Integer list of attribute numbers retrieved by RETURNING, if any * 4) Boolean flag showing if we set the command es_processed + * 5) Per-RTE function metadata (mirrors FdwScanPrivateFunctions; lets + * the executor rebuild TupleDesc entries for whole-row Vars over + * function RTEs absorbed into a foreign join) + * 6) Integer node: minimum base RT index of the scan (mirrors + * FdwScanPrivateMinRTIndex) */ enum FdwDirectModifyPrivateIndex { @@ -135,6 +157,10 @@ enum FdwDirectModifyPrivateIndex FdwDirectModifyPrivateRetrievedAttrs, /* set-processed flag (as a Boolean node) */ FdwDirectModifyPrivateSetProcessed, + /* Per-RTE function metadata, indexed by base RTI offset */ + FdwDirectModifyPrivateFunctions, + /* Integer node: minimum base RT index in the scan */ + FdwDirectModifyPrivateMinRTIndex, }; /* @@ -740,6 +766,9 @@ static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, static List *get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel); static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, Path *epq_path, List *restrictlist); static void add_foreign_grouping_paths(PlannerInfo *root, @@ -1634,9 +1663,26 @@ postgresGetForeignPlan(PlannerInfo *root, fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(fpinfo->fetch_size)); + + /* + * Position FdwScanPrivateRelations: either the EXPLAIN relation string + * (joins/upper rels) or a NULL placeholder, so that subsequent indexes + * stay valid for the base-rel scan case. + */ if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + /* + * FdwScanPrivateFunctions / FdwScanPrivateMinRTIndex carry the metadata + * the executor needs to rebuild TupleDesc entries for whole-row Vars + * pointing at RTE_FUNCTION rels absorbed into the foreign scan. + */ + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + fdw_private = lappend(fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1657,9 +1703,15 @@ postgresGetForeignPlan(PlannerInfo *root, /* * Construct a tuple descriptor for the scan tuples handled by a foreign join. + * + * 'rtfuncdata' is the FdwScanPrivateFunctions list saved at plan time, and + * 'rtoffset' is the difference between the executor's RT indexes and the + * scan-local RT indexes captured in that list. Both may be 0/NIL when the + * scan has no RTE_FUNCTION dependents. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, + List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1695,13 +1747,62 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION && rtfuncdata != NIL) + { + /* + * A whole-row Var points at a FUNCTION RTE absorbed into the + * foreign join. Synthesize an anonymous composite TupleDesc from + * the per-function return-type metadata we saved at plan time; + * the deparser emits these as ROW(f<rti>.c1, f<rti>.c2, ...). + */ + List *funcdata; + TupleDesc rte_tupdesc; + int num_funcs; + int attnum; + ListCell *lc1, + *lc2; + + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + if (funcdata == NIL) + continue; + num_funcs = list_length(funcdata); + Assert(num_funcs == list_length(rte->eref->colnames)); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc1, funcdata, lc2, rte->eref->colnames) + { + List *fdata = lfirst_node(List, lc1); + char *colname = strVal(lfirst(lc2)); + Oid funcrettype; + Oid funccollation; + + funcrettype = lsecond_node(Integer, fdata)->ival; + funccollation = lthird_node(Integer, fdata)->ival; + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, + "could not determine return type for function in foreign scan"); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funccollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1737,14 +1838,30 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. For a join, scan the base relids until we + * find an RTE_RELATION (the foreign-table side); ignore any RTE_FUNCTION + * absorbed into the join, which contributes no relation OID to look up. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); + rte = NULL; if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte != NULL && rte->rtekind == RTE_RELATION) + break; + rte = NULL; + } + if (rte == NULL) + elog(ERROR, "could not locate a foreign relation RTE in foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1787,8 +1904,19 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwScanPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwScanPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, + rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2828,6 +2956,10 @@ postgresPlanDirectModify(PlannerInfo *root, makeBoolean((retrieved_attrs != NIL)), retrieved_attrs, makeBoolean(plan->canSetTag)); + fscan->fdw_private = lappend(fscan->fdw_private, + get_functions_data(root, foreignrel)); + fscan->fdw_private = lappend(fscan->fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Update the foreign-join-related fields. @@ -2941,7 +3073,26 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + /* + * DirectModify on a foreign join: use the per-RTE function + * metadata saved at plan time so a whole-row Var pointing at a + * function RTE absorbed into the join can be rebuilt into a + * usable TupleDesc (e.g. RETURNING t for a join with UNNEST(..., + * ...) AS t(bx, i)). + */ + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + + tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -3054,7 +3205,8 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_length(fdw_private) > FdwScanPrivateRelations && + list_nth(fdw_private, FdwScanPrivateRelations) != NULL) { StringInfoData relations; char *rawrelations; @@ -3104,6 +3256,22 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); + + /* + * If a function RTE was absorbed into the foreign join, + * render it as "Function <alias>" since we have no foreign + * relid. + */ + if (rte->rtekind == RTE_FUNCTION) + { + refname = (char *) list_nth(es->rtable_names, rti - 1); + if (refname == NULL) + refname = rte->eref->aliasname; + appendStringInfo(&relations, "Function %s", + quote_identifier(refname)); + continue; + } + Assert(rte->rtekind == RTE_RELATION); /* This logic should agree with explain.c's ExplainTargetRel */ relname = get_rel_name(rte->relid); @@ -3479,8 +3647,17 @@ estimate_path_cost_size(PlannerInfo *root, /* For join we expect inner and outer relations set */ Assert(fpinfo->innerrel && fpinfo->outerrel); - fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; + /* + * For a FUNCTION RTE absorbed into the join, use the stub fpinfo + * we built in foreign_join_ok(), since the function rel itself + * has no fdw_private. + */ + fpinfo_i = fpinfo->inner_func_fpinfo ? + fpinfo->inner_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; + fpinfo_o = fpinfo->outer_func_fpinfo ? + fpinfo->outer_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; /* Estimate of number of rows in cross product */ nrows = fpinfo_i->rows * fpinfo_o->rows; @@ -6619,6 +6796,181 @@ semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, return ok; } +/* + * get_base_relids + * Return the set of base relids referenced by a foreign scan rel. + * + * For an upper rel we use the all-query relids minus the outer joins; + * otherwise the rel's own relids minus the outer joins. The result matches + * the relids that create_foreignscan_plan() ultimately uses for + * ForeignScan.fs_base_relids, so it is suitable for any tagging we want to + * store via plan-private state. + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + return bms_difference(relids, root->outer_join_rels); +} + +/* + * get_min_base_rti + * Lowest base RT index in the foreign scan rel. + * + * After setrefs.c flattens the rtable, the scan-local indexes saved in + * plan-private data can be translated to estate indexes by adding + * (ForeignScan.fs_base_relids min - this value). Captured at plan time + * because create_foreignscan_plan() computes the same value internally. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + +/* + * get_functions_data + * Build the per-RTE function metadata list saved as + * FdwScanPrivateFunctions. + * + * The result list is indexed by base RT index relative to the lowest base + * RT index of the scan. Each element is either NULL (for non-RTE_FUNCTION + * base rels in this scan) or a List of List of three Integer nodes: + * (funcid, funcrettype, funccollation) -- one inner list per RangeTblFunction. + * + * Only RTE_FUNCTION relids actually appearing in the foreign scan's + * fs_base_relids contribute; others are placeholders so that the consumer + * can index into the result by RTI offset. + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + Relids fscan_relids = get_base_relids(root, rel); + int i; + + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + List *funcdata = NIL; + ListCell *lc; + + if (rte == NULL || i == 0 || + !bms_is_member(i, fscan_relids) || + rte->rtekind != RTE_FUNCTION) + { + rtfuncdata = lappend(rtfuncdata, NULL); + continue; + } + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + Oid funcrettype; + Oid funccollation; + TupleDesc tupdesc; + Oid funcid = InvalidOid; + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, + "could not determine return type for function in foreign scan"); + + funccollation = exprCollation(rtfunc->funcexpr); + + if (IsA(rtfunc->funcexpr, FuncExpr)) + funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid; + + funcdata = lappend(funcdata, + list_make3(makeInteger(funcid), + makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + + return rtfuncdata; +} + +/* + * Check if a relation is a FUNCTION RTE that can be absorbed into a remote + * join. Every function in the RTE must + * + * - return a well-defined scalar type -- we don't ship records/composite + * since the remote server cannot reconstruct a column definition list + * and our deparser does not emit one; + * - have a shippable expression with no mutable subnodes -- is_foreign_expr() + * rejects volatile/stable functions through contain_mutable_functions(), + * so the IMMUTABLE-only restriction is implicit; + * - not contain SubPlans -- we'd otherwise need to ship sub-results to + * the remote, which we do not implement. + * + * WITH ORDINALITY is not supported yet. + */ +static bool +function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel, + RelOptInfo *fdwrel) +{ + RangeTblEntry *rte; + ListCell *lc; + + if (rel->rtekind != RTE_FUNCTION) + return false; + rte = planner_rt_fetch(rel->relid, root); + if (rte->rtekind != RTE_FUNCTION) + return false; + if (rte->funcordinality) + return false; + + /* + * Reject up-front any function RTE that lateral-references another + * relation: foreign-join push-down would need to parameterise the remote + * query per outer row, which we don't support, and even considering the + * path is expensive on the planner side. The surrounding lateral_relids + * check in postgresGetForeignJoinPaths() would normally bail out for the + * joinrel, but doing the check here avoids walking the function + * expression entirely. + */ + if (!bms_is_empty(rel->lateral_relids)) + return false; + + Assert(list_length(rte->functions) >= 1); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + TypeFuncClass functypclass; + Oid funcrettype; + TupleDesc tupdesc; + + functypclass = get_expr_result_type(rtfunc->funcexpr, + &funcrettype, &tupdesc); + if (functypclass != TYPEFUNC_SCALAR) + return false; + if (!OidIsValid(funcrettype) || + funcrettype == RECORDOID || + funcrettype == VOIDOID) + return false; + + if (contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, fdwrel, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -6634,6 +6986,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; + bool outer_is_function = false; + bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -6652,15 +7006,70 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, return false; /* - * If either of the joining relations is marked as unsafe to pushdown, the - * join can not be pushed down. + * Detect mixed (foreign x function-RTE) cases. Only INNER joins are + * supported initially. We dispatch on rtekind here so that the same + * function RTE can be absorbed into joins on multiple foreign servers + * (each call gets its own stub fpinfo and rechecks shippability for the + * specific server). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && + (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && + fpinfo_o->pushdown_safe && + function_rte_pushdown_ok(root, innerrel, outerrel)) + { + inner_is_function = true; + } + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) + { + outer_is_function = true; + } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } + + /* + * If one side is a function RTE, allocate a stub fpinfo so the rest of + * this function and the cost estimator can treat it uniformly. We hand + * the stub to the joinrel's deparser via the same path the foreign side + * uses, but we never permanently attach it to the function rel's + * fdw_private (different joinrels may pair the same function RTE with + * different foreign servers). + */ + if (inner_is_function) + { + fpinfo_i = palloc0_object(PgFdwRelationInfo); + fpinfo_i->pushdown_safe = true; + fpinfo_i->server = fpinfo_o->server; + fpinfo_i->relation_name = psprintf("%u", innerrel->relid); + fpinfo_i->rows = innerrel->rows; + fpinfo_i->width = innerrel->reltarget->width; + fpinfo_i->retrieved_rows = innerrel->rows; + fpinfo_i->rel_startup_cost = 0; + fpinfo_i->rel_total_cost = 0; + fpinfo->inner_func_fpinfo = fpinfo_i; + } + else if (outer_is_function) + { + fpinfo_o = palloc0_object(PgFdwRelationInfo); + fpinfo_o->pushdown_safe = true; + fpinfo_o->server = fpinfo_i->server; + fpinfo_o->relation_name = psprintf("%u", outerrel->relid); + fpinfo_o->rows = outerrel->rows; + fpinfo_o->width = outerrel->reltarget->width; + fpinfo_o->retrieved_rows = outerrel->rows; + fpinfo_o->rel_startup_cost = 0; + fpinfo_o->rel_total_cost = 0; + fpinfo->outer_func_fpinfo = fpinfo_o; + } /* * If joining relations have local conditions, those conditions are diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..5b2ffcf06f7 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -106,6 +106,16 @@ typedef struct PgFdwRelationInfo /* joinclauses contains only JOIN/ON conditions for an outer join */ List *joinclauses; /* List of RestrictInfo */ + /* + * If a FUNCTION RTE was absorbed into this join, these point at the stub + * PgFdwRelationInfo for the function side (paired with the + * outerrel/innerrel), so the cost estimator and deparser can find it + * without consulting the function rel's fdw_private. At most one of + * outer_func_fpinfo/inner_func_fpinfo is set. + */ + struct PgFdwRelationInfo *outer_func_fpinfo; + struct PgFdwRelationInfo *inner_func_fpinfo; + /* Upper relation information */ UpperRelationKind stage; diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 267d3c1a7e7..f49fbc9317e 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -790,6 +790,189 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); + +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; +DROP FUNCTION f_ret_record(); + +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; + +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 3fc2c2f71d0..f21ae1baeb2 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -746,6 +746,30 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if (OidIsValid(outer_rel->serverid) && + inner_rel->rtekind == RTE_FUNCTION) + { + /* + * One side is a foreign relation, the other side is a function RTE. + * If the function is IMMUTABLE, the FDW can absorb the function call + * into the remote query (the result is identical regardless of which + * server evaluates it). Let the FDW decide whether the join is + * actually shippable; here we just propagate the FDW routine so the + * FDW gets a chance. + */ + joinrel->serverid = outer_rel->serverid; + joinrel->userid = outer_rel->userid; + joinrel->useridiscurrent = outer_rel->useridiscurrent; + joinrel->fdwroutine = outer_rel->fdwroutine; + } + else if (OidIsValid(inner_rel->serverid) && + outer_rel->rtekind == RTE_FUNCTION) + { + joinrel->serverid = inner_rel->serverid; + joinrel->userid = inner_rel->userid; + joinrel->useridiscurrent = inner_rel->useridiscurrent; + joinrel->fdwroutine = inner_rel->fdwroutine; + } } /* -- 2.43.0
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-05-19 18:21                   ` Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Korotkov @ 2026-05-19 18:21 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Good evening!

On Tue, May 19, 2026 at 6:25 PM Alexander Pyhalov
<a.pyhalov@postgrespro.ru> wrote:
>
> Found one more issue in whole row var deparsing. It can appear on a
> nullable outer side, and we should use the same logic as when deparsing
> table column reference. Otherwise we get records from nulls instead of
> nulls (for example, "(NULL, NULL)" instead of NULL).


Good catch, accepted.

> Also I wonder if it is possible for get_tupdesc_for_join_scan_tuples()
> to get NULL rtfuncdata when it looks at RTE_FUNCTION RTE here:
>
> 1759                 else if (rte->rtekind == RTE_FUNCTION && rtfuncdata
> != NIL)
> 1760                 {
> 1761                         /*
> 1762                          * A whole-row Var points at a FUNCTION RTE
> absorbed into the
> 1763                          * foreign join.  Synthesize an anonymous
> composite TupleDesc from
> 1764                          * the per-function return-type metadata we
> saved at plan time;
> 1765                          * the deparser emits these as
> ROW(f<rti>.c1, f<rti>.c2, ...).
> 1766                          */
> 1767                         List       *funcdata;
> 1768                         TupleDesc       rte_tupdesc;
> 1769                         int                     num_funcs;
> 1770                         int                     attnum;
> 1771                         ListCell   *lc1,
>
> ?

I don't see how that's possible.  I think it would be safer to just
assert rtfuncdata/funcdata are not NULL.  Revised patch is attached.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

v8-0001-postgres_fdw-push-down-FUNCTION-RTE-into-foreign-.patch (application/octet-stream, 59.0K) download From fa6e090e600acf527dc2e8877c4e61c698258409 Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Tue, 19 May 2026 16:28:22 +0300 Subject: [PATCH v8] postgres_fdw: push down FUNCTION RTE into foreign joins A foreign join planning hook now considers a (foreign-table x function-RTE) INNER join as a push-down candidate when the function expression is IMMUTABLE and otherwise shippable. The remote query absorbs the function call as a FROM-list item (e.g. unnest(...) AS f<rti>(c1, c2, ...)), so the foreign side returns only rows that match the function-produced set and the join executes entirely on the remote. An IMMUTABLE function gives the same result on any server, so the same function RTE can be a push-down candidate for several distinct foreign servers without semantic risk. To keep the planner state consistent across those independent attempts, the per-call stub fpinfo for the function side lives on the joinrel's PgFdwRelationInfo (new outer_func_fpinfo / inner_func_fpinfo), never on the function rel itself, and the function side is detected via rtekind rather than fdw_private. set_foreign_rel_properties() propagates fdwroutine onto a joinrel that pairs a foreign rel with an RTE_FUNCTION rel so GetForeignJoinPaths gets called; the FDW retains full control over whether to actually generate a path. deparseRangeTblRef and deparseColumnRef gain a FUNCTION-RTE branch that emits the function expression and resolves Vars to the generated column aliases. --- contrib/postgres_fdw/deparse.c | 132 ++++- .../postgres_fdw/expected/postgres_fdw.out | 441 +++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 461 +++++++++++++++++- contrib/postgres_fdw/postgres_fdw.h | 10 + contrib/postgres_fdw/sql/postgres_fdw.sql | 183 +++++++ src/backend/optimizer/util/relnode.c | 24 + 6 files changed, 1227 insertions(+), 24 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 2dcc6c8af1b..5567fdb8ed9 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -112,6 +112,7 @@ typedef struct deparse_expr_cxt appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno)) #define SUBQUERY_REL_ALIAS_PREFIX "s" #define SUBQUERY_COL_ALIAS_PREFIX "c" +#define FUNCTION_REL_ALIAS_PREFIX "f" /* * Functions to determine whether an expression can be evaluated safely on @@ -2030,6 +2031,72 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, } } +/* + * Deparse a FUNCTION RTE absorbed into a foreign join. The function call(s) + * are emitted as a FROM-list item: + * + * <funcexpr> AS f<rti>(c1, c2, ..., cN) + * + * For multi-function RTEs (SQL ROWS FROM (f1(), f2(), ...)), each + * function call appears comma-separated inside ROWS FROM(...). Column + * aliases c1..cN cover the union of every function's columns, in the + * order they appear; that matches the column ordering of the RTE. + */ +static void +deparseFunctionRangeTblRef(StringInfo buf, PlannerInfo *root, + RelOptInfo *foreignrel, RelOptInfo *scanrel, + List **params_list) +{ + RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); + deparse_expr_cxt context; + ListCell *lc; + bool multi_func; + int total_cols = 0; + int i; + + Assert(rte->rtekind == RTE_FUNCTION); + Assert(!rte->funcordinality); + Assert(list_length(rte->functions) >= 1); + + multi_func = list_length(rte->functions) > 1; + + context.buf = buf; + context.root = root; + context.foreignrel = scanrel; + context.scanrel = scanrel; + context.params_list = params_list; + + if (multi_func) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (foreach_current_index(lc) > 0) + appendStringInfoString(buf, ", "); + deparseExpr((Expr *) rtfunc->funcexpr, &context); + total_cols += rtfunc->funccolcount; + } + + if (multi_func) + appendStringInfoChar(buf, ')'); + + /* Alias + generated column-name list. */ + appendStringInfo(buf, " %s%d", FUNCTION_REL_ALIAS_PREFIX, foreignrel->relid); + if (total_cols > 0) + { + appendStringInfoChar(buf, '('); + for (i = 1; i <= total_cols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + } +} + /* * Append FROM clause entry for the given relation into buf. * Conditions from lower-level SEMI-JOINs are appended to additional_conds @@ -2040,7 +2107,22 @@ deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **additional_conds, List **params_list) { - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + PgFdwRelationInfo *fpinfo; + + /* + * For a function RTE absorbed into a foreign join, deparse the function + * expression as a FROM-list item and return. The stub fpinfo set up by + * foreign_join_ok() may or may not be present here. + */ + if (foreignrel->rtekind == RTE_FUNCTION) + { + Assert(!make_subquery); + deparseFunctionRangeTblRef(buf, root, foreignrel, foreignrel, + params_list); + return; + } + + fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; /* Should only be called in these cases. */ Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel)); @@ -2712,6 +2794,54 @@ static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col) { + /* + * Function RTE columns: emit as f<varno>.c<varattno>, matching the + * aliases generated by deparseFunctionRangeTblRef(). A whole-row Var + * (varattno == 0) is rendered as ROW(f<varno>.c1, ..., f<varno>.c<N>) + * where N is the total column count of the function RTE (including all + * ROWS FROM (...) members). System attributes such as ctid have no + * meaning for function RTEs and are rejected. + */ + if (rte->rtekind == RTE_FUNCTION) + { + if (varattno == 0) + { + int ncols = list_length(rte->eref->colnames); + int i; + + if (qualify_col) + { + appendStringInfoString(buf, "CASE WHEN ("); + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfoString(buf, "*)::text IS NOT NULL THEN "); + } + + appendStringInfoString(buf, "ROW("); + for (i = 1; i <= ncols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d.%s%d", + FUNCTION_REL_ALIAS_PREFIX, varno, + SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + + if (qualify_col) + appendStringInfoString(buf, " END"); + return; + } + + if (varattno < 0) + elog(ERROR, + "system attribute reference to a function RTE is not supported in foreign join pushdown"); + + if (qualify_col) + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, varattno); + return; + } + /* We support fetching the remote side's CTID and OID. */ if (varattno == SelfItemPointerAttributeNumber) { diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index e90289e4ab1..a626b5e5ace 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2885,6 +2885,447 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c (10 rows) ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: t1.c1, t1.c3 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1, t1.c3 + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", r1.c3 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{1,5,10,100}'::integer[]) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + c1 | c3 +-----+------- + 1 | 00001 + 5 | 00005 + 10 | 00010 + 100 | 00100 +(4 rows) + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Sort + Output: t1.c1 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1 + Relations: (public.ft1 t1) INNER JOIN (Function g) + Remote SQL: SELECT r1."C 1" FROM ("S 1"."T 1" r1 INNER JOIN generate_series(1, 4) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + c1 +---- + 1 + 2 + 3 + 4 +(4 rows) + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on pg_catalog.generate_series g + Output: g.id + Function Call: generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + QUERY PLAN +------------------------------------------------------------ + Hash Join + Output: t1.c1, u.ord + Hash Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" + -> Hash + Output: u.ord, u.id + -> Function Scan on pg_catalog.unnest u + Output: u.ord, u.id + Function Call: unnest('{1,5,10}'::integer[]) +(11 rows) + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: t1.c1, t2.c1 + Merge Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST + -> Sort + Output: t2.c1, u.id + Sort Key: t2.c1 + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{1,5,10,100}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(13 rows) + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: t1.c1, t2.c1 + Hash Cond: (t1.c1 = t2.c1) + -> Foreign Scan + Output: t1.c1, u.id + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", f3.c1 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r1."C 1" = f3.c1)))) + -> Hash + Output: t2.c1 + -> Foreign Scan on public.ft6 t2 + Output: t2.c1 + Remote SQL: SELECT c1 FROM "S 1"."T 4" +(12 rows) + +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: t1.c1, t2.c1 + Join Filter: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE ((c3 < '00010')) + -> Materialize + Output: t2.c1, u.id + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(12 rows) + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (Function n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + n | a | b +---+---+----- + 2 | 2 | 102 + 3 | 3 | 103 + 4 | 4 | 104 +(3 rows) + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: s.* + Hash Cond: (rt.a = s.a) + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl_fn + -> Hash + Output: s.*, s.a + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() +(11 rows) + +DROP FUNCTION f_ret_record(); +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + a | b +----+----- + 23 | 123 + 24 | 999 + 25 | 125 +(3 rows) + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + a | b +----+--- + 24 | 5 +(1 row) + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + a | b | t +----+---+--------------------- + 24 | 7 | ("(2,3),(-2,-3)",1) +(1 row) + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: r.a, t.n, t.s + Sort Key: r.a + -> Foreign Scan + Output: r.a, t.n, t.s + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT r1.a, f2.c1, f2.c2 FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + a | n | s +---+---+---- + 3 | 3 | 11 + 6 | 6 | 12 + 9 | 9 | 13 +(3 rows) + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: ((t.*)::text), r.a + Sort Key: r.a + -> Foreign Scan + Output: (t.*)::text, r.a + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT CASE WHEN (f2.*)::text IS NOT NULL THEN ROW(f2.c1, f2.c2) END, r1.a FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + t | a +--------+--- + (3,11) | 3 + (6,12) | 6 + (9,13) | 9 +(3 rows) + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: u.*, ft5.c1, ft5.c2, ft4.c1, ft4.c2 + Relations: (public.ft5) LEFT JOIN ((public.ft4) INNER JOIN (Function u)) + Remote SQL: SELECT CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END, r1.c1, r1.c2, r2.c1, r2.c2 FROM ("S 1"."T 4" r1 LEFT JOIN ("S 1"."T 3" r2 INNER JOIN ROWS FROM (unnest('{1,2}'::integer[]), unnest('{3,4}'::integer[])) f3(c1, c2) ON (((r2.c1 = f3.c1)))) ON (((r1.c1 = r2.c1)))) WHERE ((r1.c1 < 10)) ORDER BY r1.c1 ASC NULLS LAST +(4 rows) + +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + u | c1 | c2 | c1 | c2 +---+----+----+----+---- + | 3 | 4 | | + | 6 | 7 | | + | 9 | 10 | | +(3 rows) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: r.a + Merge Cond: (t.n = r.a) + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]), generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Sort + Output: r.a + Sort Key: r.a + -> Foreign Scan on public.remote_tbl r + Output: r.a + Remote SQL: SELECT a FROM public.base_tbl_fn +(15 rows) + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Nested Loop + Output: r.a, t.x + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 3)) ORDER BY a ASC NULLS LAST + -> Function Scan on pg_catalog.unnest t + Output: t.x + Function Call: unnest(ARRAY[r.a]) +(8 rows) + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Merge Left Join + Output: r.a, t.n + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 5)) ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{1,2,3}'::integer[]) +(12 rows) + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + QUERY PLAN +-------------------------------------------------------------------------------- + Merge Semi Join + Output: r.a + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]) +(12 rows) + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 0a589f8db74..90d24ac4d56 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -31,6 +31,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/appendinfo.h" +#include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" #include "optimizer/optimizer.h" @@ -88,6 +89,22 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of per-RTE function metadata, indexed by base RTI offset. Each + * element is either NULL (for non-RTE_FUNCTION rels in this scan) or a + * list of three-element lists (funcid, funcrettype, funccollation) -- one + * inner list per function in the RTE. Allows the executor to rebuild + * TupleDesc entries for whole-row references to function RTEs. + */ + FdwScanPrivateFunctions, + + /* + * Integer node: minimum base RT index covered by the scan, used to + * translate scan-local indexes to estate-rtable indexes after setrefs.c + * flattens rtables. + */ + FdwScanPrivateMinRTIndex, }; /* @@ -124,6 +141,11 @@ enum FdwModifyPrivateIndex * 2) Boolean flag showing if the remote query has a RETURNING clause * 3) Integer list of attribute numbers retrieved by RETURNING, if any * 4) Boolean flag showing if we set the command es_processed + * 5) Per-RTE function metadata (mirrors FdwScanPrivateFunctions; lets + * the executor rebuild TupleDesc entries for whole-row Vars over + * function RTEs absorbed into a foreign join) + * 6) Integer node: minimum base RT index of the scan (mirrors + * FdwScanPrivateMinRTIndex) */ enum FdwDirectModifyPrivateIndex { @@ -135,6 +157,10 @@ enum FdwDirectModifyPrivateIndex FdwDirectModifyPrivateRetrievedAttrs, /* set-processed flag (as a Boolean node) */ FdwDirectModifyPrivateSetProcessed, + /* Per-RTE function metadata, indexed by base RTI offset */ + FdwDirectModifyPrivateFunctions, + /* Integer node: minimum base RT index in the scan */ + FdwDirectModifyPrivateMinRTIndex, }; /* @@ -741,6 +767,9 @@ static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, static List *get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel); static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, Path *epq_path, List *restrictlist); static void add_foreign_grouping_paths(PlannerInfo *root, @@ -1635,9 +1664,26 @@ postgresGetForeignPlan(PlannerInfo *root, fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(fpinfo->fetch_size)); + + /* + * Position FdwScanPrivateRelations: either the EXPLAIN relation string + * (joins/upper rels) or a NULL placeholder, so that subsequent indexes + * stay valid for the base-rel scan case. + */ if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + /* + * FdwScanPrivateFunctions / FdwScanPrivateMinRTIndex carry the metadata + * the executor needs to rebuild TupleDesc entries for whole-row Vars + * pointing at RTE_FUNCTION rels absorbed into the foreign scan. + */ + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + fdw_private = lappend(fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1658,9 +1704,15 @@ postgresGetForeignPlan(PlannerInfo *root, /* * Construct a tuple descriptor for the scan tuples handled by a foreign join. + * + * 'rtfuncdata' is the FdwScanPrivateFunctions list saved at plan time, and + * 'rtoffset' is the difference between the executor's RT indexes and the + * scan-local RT indexes captured in that list. Both may be 0/NIL when the + * scan has no RTE_FUNCTION dependents. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, + List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1696,13 +1748,68 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * A whole-row Var points at a FUNCTION RTE absorbed into the + * foreign join. Synthesize an anonymous composite TupleDesc from + * the per-function return-type metadata we saved at plan time; + * the deparser emits these as ROW(f<rti>.c1, f<rti>.c2, ...). + * + * For an upperrel scan (the only path that reaches here) + * postgresGetForeignPlan always builds rtfuncdata via + * get_functions_data(), so it is never NIL; the per-RTE slot for + * the function RTE referenced by this Var must likewise be + * populated. + */ + List *funcdata; + TupleDesc rte_tupdesc; + int num_funcs; + int attnum; + ListCell *lc1, + *lc2; + + Assert(rtfuncdata != NIL); + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + Assert(funcdata != NIL); + num_funcs = list_length(funcdata); + Assert(num_funcs == list_length(rte->eref->colnames)); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc1, funcdata, lc2, rte->eref->colnames) + { + List *fdata = lfirst_node(List, lc1); + char *colname = strVal(lfirst(lc2)); + Oid funcrettype; + Oid funccollation; + + funcrettype = lsecond_node(Integer, fdata)->ival; + funccollation = lthird_node(Integer, fdata)->ival; + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, + "could not determine return type for function in foreign scan"); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funccollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1738,14 +1845,30 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. For a join, scan the base relids until we + * find an RTE_RELATION (the foreign-table side); ignore any RTE_FUNCTION + * absorbed into the join, which contributes no relation OID to look up. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); + rte = NULL; if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte != NULL && rte->rtekind == RTE_RELATION) + break; + rte = NULL; + } + if (rte == NULL) + elog(ERROR, "could not locate a foreign relation RTE in foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1788,8 +1911,19 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwScanPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwScanPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, + rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2829,6 +2963,10 @@ postgresPlanDirectModify(PlannerInfo *root, makeBoolean((retrieved_attrs != NIL)), retrieved_attrs, makeBoolean(plan->canSetTag)); + fscan->fdw_private = lappend(fscan->fdw_private, + get_functions_data(root, foreignrel)); + fscan->fdw_private = lappend(fscan->fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Update the foreign-join-related fields. @@ -2942,7 +3080,26 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + /* + * DirectModify on a foreign join: use the per-RTE function + * metadata saved at plan time so a whole-row Var pointing at a + * function RTE absorbed into the join can be rebuilt into a + * usable TupleDesc (e.g. RETURNING t for a join with UNNEST(..., + * ...) AS t(bx, i)). + */ + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + + tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -3055,7 +3212,8 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_length(fdw_private) > FdwScanPrivateRelations && + list_nth(fdw_private, FdwScanPrivateRelations) != NULL) { StringInfoData relations; char *rawrelations; @@ -3105,6 +3263,22 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); + + /* + * If a function RTE was absorbed into the foreign join, + * render it as "Function <alias>" since we have no foreign + * relid. + */ + if (rte->rtekind == RTE_FUNCTION) + { + refname = (char *) list_nth(es->rtable_names, rti - 1); + if (refname == NULL) + refname = rte->eref->aliasname; + appendStringInfo(&relations, "Function %s", + quote_identifier(refname)); + continue; + } + Assert(rte->rtekind == RTE_RELATION); /* This logic should agree with explain.c's ExplainTargetRel */ relname = get_rel_name(rte->relid); @@ -3480,8 +3654,17 @@ estimate_path_cost_size(PlannerInfo *root, /* For join we expect inner and outer relations set */ Assert(fpinfo->innerrel && fpinfo->outerrel); - fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; + /* + * For a FUNCTION RTE absorbed into the join, use the stub fpinfo + * we built in foreign_join_ok(), since the function rel itself + * has no fdw_private. + */ + fpinfo_i = fpinfo->inner_func_fpinfo ? + fpinfo->inner_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; + fpinfo_o = fpinfo->outer_func_fpinfo ? + fpinfo->outer_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; /* Estimate of number of rows in cross product */ nrows = fpinfo_i->rows * fpinfo_o->rows; @@ -6639,6 +6822,181 @@ semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, return ok; } +/* + * get_base_relids + * Return the set of base relids referenced by a foreign scan rel. + * + * For an upper rel we use the all-query relids minus the outer joins; + * otherwise the rel's own relids minus the outer joins. The result matches + * the relids that create_foreignscan_plan() ultimately uses for + * ForeignScan.fs_base_relids, so it is suitable for any tagging we want to + * store via plan-private state. + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + return bms_difference(relids, root->outer_join_rels); +} + +/* + * get_min_base_rti + * Lowest base RT index in the foreign scan rel. + * + * After setrefs.c flattens the rtable, the scan-local indexes saved in + * plan-private data can be translated to estate indexes by adding + * (ForeignScan.fs_base_relids min - this value). Captured at plan time + * because create_foreignscan_plan() computes the same value internally. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + +/* + * get_functions_data + * Build the per-RTE function metadata list saved as + * FdwScanPrivateFunctions. + * + * The result list is indexed by base RT index relative to the lowest base + * RT index of the scan. Each element is either NULL (for non-RTE_FUNCTION + * base rels in this scan) or a List of List of three Integer nodes: + * (funcid, funcrettype, funccollation) -- one inner list per RangeTblFunction. + * + * Only RTE_FUNCTION relids actually appearing in the foreign scan's + * fs_base_relids contribute; others are placeholders so that the consumer + * can index into the result by RTI offset. + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + Relids fscan_relids = get_base_relids(root, rel); + int i; + + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + List *funcdata = NIL; + ListCell *lc; + + if (rte == NULL || i == 0 || + !bms_is_member(i, fscan_relids) || + rte->rtekind != RTE_FUNCTION) + { + rtfuncdata = lappend(rtfuncdata, NULL); + continue; + } + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + Oid funcrettype; + Oid funccollation; + TupleDesc tupdesc; + Oid funcid = InvalidOid; + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, + "could not determine return type for function in foreign scan"); + + funccollation = exprCollation(rtfunc->funcexpr); + + if (IsA(rtfunc->funcexpr, FuncExpr)) + funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid; + + funcdata = lappend(funcdata, + list_make3(makeInteger(funcid), + makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + + return rtfuncdata; +} + +/* + * Check if a relation is a FUNCTION RTE that can be absorbed into a remote + * join. Every function in the RTE must + * + * - return a well-defined scalar type -- we don't ship records/composite + * since the remote server cannot reconstruct a column definition list + * and our deparser does not emit one; + * - have a shippable expression with no mutable subnodes -- is_foreign_expr() + * rejects volatile/stable functions through contain_mutable_functions(), + * so the IMMUTABLE-only restriction is implicit; + * - not contain SubPlans -- we'd otherwise need to ship sub-results to + * the remote, which we do not implement. + * + * WITH ORDINALITY is not supported yet. + */ +static bool +function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel, + RelOptInfo *fdwrel) +{ + RangeTblEntry *rte; + ListCell *lc; + + if (rel->rtekind != RTE_FUNCTION) + return false; + rte = planner_rt_fetch(rel->relid, root); + if (rte->rtekind != RTE_FUNCTION) + return false; + if (rte->funcordinality) + return false; + + /* + * Reject up-front any function RTE that lateral-references another + * relation: foreign-join push-down would need to parameterise the remote + * query per outer row, which we don't support, and even considering the + * path is expensive on the planner side. The surrounding lateral_relids + * check in postgresGetForeignJoinPaths() would normally bail out for the + * joinrel, but doing the check here avoids walking the function + * expression entirely. + */ + if (!bms_is_empty(rel->lateral_relids)) + return false; + + Assert(list_length(rte->functions) >= 1); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + TypeFuncClass functypclass; + Oid funcrettype; + TupleDesc tupdesc; + + functypclass = get_expr_result_type(rtfunc->funcexpr, + &funcrettype, &tupdesc); + if (functypclass != TYPEFUNC_SCALAR) + return false; + if (!OidIsValid(funcrettype) || + funcrettype == RECORDOID || + funcrettype == VOIDOID) + return false; + + if (contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, fdwrel, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -6654,6 +7012,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; + bool outer_is_function = false; + bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -6672,15 +7032,70 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, return false; /* - * If either of the joining relations is marked as unsafe to pushdown, the - * join can not be pushed down. + * Detect mixed (foreign x function-RTE) cases. Only INNER joins are + * supported initially. We dispatch on rtekind here so that the same + * function RTE can be absorbed into joins on multiple foreign servers + * (each call gets its own stub fpinfo and rechecks shippability for the + * specific server). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && + (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && + fpinfo_o->pushdown_safe && + function_rte_pushdown_ok(root, innerrel, outerrel)) + { + inner_is_function = true; + } + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) + { + outer_is_function = true; + } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } + + /* + * If one side is a function RTE, allocate a stub fpinfo so the rest of + * this function and the cost estimator can treat it uniformly. We hand + * the stub to the joinrel's deparser via the same path the foreign side + * uses, but we never permanently attach it to the function rel's + * fdw_private (different joinrels may pair the same function RTE with + * different foreign servers). + */ + if (inner_is_function) + { + fpinfo_i = palloc0_object(PgFdwRelationInfo); + fpinfo_i->pushdown_safe = true; + fpinfo_i->server = fpinfo_o->server; + fpinfo_i->relation_name = psprintf("%u", innerrel->relid); + fpinfo_i->rows = innerrel->rows; + fpinfo_i->width = innerrel->reltarget->width; + fpinfo_i->retrieved_rows = innerrel->rows; + fpinfo_i->rel_startup_cost = 0; + fpinfo_i->rel_total_cost = 0; + fpinfo->inner_func_fpinfo = fpinfo_i; + } + else if (outer_is_function) + { + fpinfo_o = palloc0_object(PgFdwRelationInfo); + fpinfo_o->pushdown_safe = true; + fpinfo_o->server = fpinfo_i->server; + fpinfo_o->relation_name = psprintf("%u", outerrel->relid); + fpinfo_o->rows = outerrel->rows; + fpinfo_o->width = outerrel->reltarget->width; + fpinfo_o->retrieved_rows = outerrel->rows; + fpinfo_o->rel_startup_cost = 0; + fpinfo_o->rel_total_cost = 0; + fpinfo->outer_func_fpinfo = fpinfo_o; + } /* * If joining relations have local conditions, those conditions are diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..5b2ffcf06f7 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -106,6 +106,16 @@ typedef struct PgFdwRelationInfo /* joinclauses contains only JOIN/ON conditions for an outer join */ List *joinclauses; /* List of RestrictInfo */ + /* + * If a FUNCTION RTE was absorbed into this join, these point at the stub + * PgFdwRelationInfo for the function side (paired with the + * outerrel/innerrel), so the cost estimator and deparser can find it + * without consulting the function rel's fdw_private. At most one of + * outer_func_fpinfo/inner_func_fpinfo is set. + */ + struct PgFdwRelationInfo *outer_func_fpinfo; + struct PgFdwRelationInfo *inner_func_fpinfo; + /* Upper relation information */ UpperRelationKind stage; diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index dfc58beb0d2..ec791e2127d 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -790,6 +790,189 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); + +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; +DROP FUNCTION f_ret_record(); + +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; + +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 3fc2c2f71d0..f21ae1baeb2 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -746,6 +746,30 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if (OidIsValid(outer_rel->serverid) && + inner_rel->rtekind == RTE_FUNCTION) + { + /* + * One side is a foreign relation, the other side is a function RTE. + * If the function is IMMUTABLE, the FDW can absorb the function call + * into the remote query (the result is identical regardless of which + * server evaluates it). Let the FDW decide whether the join is + * actually shippable; here we just propagate the FDW routine so the + * FDW gets a chance. + */ + joinrel->serverid = outer_rel->serverid; + joinrel->userid = outer_rel->userid; + joinrel->useridiscurrent = outer_rel->useridiscurrent; + joinrel->fdwroutine = outer_rel->fdwroutine; + } + else if (OidIsValid(inner_rel->serverid) && + outer_rel->rtekind == RTE_FUNCTION) + { + joinrel->serverid = inner_rel->serverid; + joinrel->userid = inner_rel->userid; + joinrel->useridiscurrent = inner_rel->useridiscurrent; + joinrel->fdwroutine = inner_rel->fdwroutine; + } } /* -- 2.39.5 (Apple Git-154)
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
@ 2026-05-20 10:17                     ` Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2026-05-20 10:17 UTC (permalink / raw)
  To: Alexander Korotkov <aekorotkov@gmail.com>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Alexander Korotkov писал(а) 2026-05-19 21:21:
> Good evening!
> 
> On Tue, May 19, 2026 at 6:25 PM Alexander Pyhalov
> <a.pyhalov@postgrespro.ru> wrote:
>> 
>> Found one more issue in whole row var deparsing. It can appear on a
>> nullable outer side, and we should use the same logic as when 
>> deparsing
>> table column reference. Otherwise we get records from nulls instead of
>> nulls (for example, "(NULL, NULL)" instead of NULL).
> 
> 
> Good catch, accepted.
> 

Hi.

I've found another issue. The fact that in the new versions of the patch 
RTE RelOptInfo misses fdw_private seems to be unfortunate. For example, 
in the last version we haven't thought about classifying 
baserestrictinfo. And if we do, we should pass fdw_private down to 
foreign_expr_walker. Perhaps, we could attach it to RTE_FUNCTION rel 
prior to calling classifyConditions(), but should we later set it back 
to NULL? Another problem comes if we try to handle joins,  which can 
crearte subqueries (like INNER/OUTER UNIQUE). In this case we should 
somehow cook fpinfo for get_relation_column_alias_ids(). Attaching patch 
which tries to handle baserestrictinfos by passing fpinfo down to 
foreign_expr_walker().

One more interesting example (included in the patch) is

EXPLAIN (VERBOSE, COSTS OFF)
WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1
JOIN LATERAL
(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s
ON true)
SELECT * FROM s ORDER BY 1;

We get the following plan:

  Sort
    Output: s.a, s.b
    Sort Key: s.a
    CTE s
      ->  Nested Loop
            Output: r1.a, r1.b
            ->  Foreign Scan on public.remote_tbl r1
                  Output: r1.a, r1.b
                  Remote SQL: SELECT a, b FROM public.base_tbl_fn
            ->  Foreign Scan
                  Output: NULL::integer
                  Relations: (public.remote_tbl r2) INNER JOIN (Function 
f)
                  Remote SQL: SELECT NULL FROM (public.base_tbl_fn r1 
INNER JOIN public.f($1::integer) f2(c1) ON (TRUE)) LIMIT 1::bigint
    ->  CTE Scan on s
          Output: s.a, s.b

Here you can see that we use parameter in function argument. Don't know 
if it's a real problem, but at least looks suspicious. In v3 patch used 
contain_param_walker() in is_nonrel_relinfo_ok() (which mutated to 
function_rte_pushdown_ok()) to avoid such plans.

One minor issue I've noticed is in function_rte_pushdown_ok():
+       if (rel->rtekind != RTE_FUNCTION)
+               return false;
+       rte = planner_rt_fetch(rel->relid, root);
+       if (rte->rtekind != RTE_FUNCTION)
+               return false;

Is the second rtekind check necessary?
-- 
Best regards,
Alexander Pyhalov,
Postgres Professional

Attachments:

v9-0001-postgres_fdw-push-down-FUNCTION-RTE-into-foreign-joi.patch (text/x-diff, 72.4K) download From 80684442324aa12a6004da40f09e34b573130cb2 Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Wed, 20 May 2026 09:22:51 +0300 Subject: [PATCH] postgres_fdw: push down FUNCTION RTE into foreign joins A foreign join planning hook now considers a (foreign-table x function-RTE) INNER join as a push-down candidate when the function expression is IMMUTABLE and otherwise shippable. The remote query absorbs the function call as a FROM-list item (e.g. unnest(...) AS f<rti>(c1, c2, ...)), so the foreign side returns only rows that match the function-produced set and the join executes entirely on the remote. An IMMUTABLE function gives the same result on any server, so the same function RTE can be a push-down candidate for several distinct foreign servers without semantic risk. To keep the planner state consistent across those independent attempts, the per-call stub fpinfo for the function side lives on the joinrel's PgFdwRelationInfo (new outer_func_fpinfo / inner_func_fpinfo), never on the function rel itself, and the function side is detected via rtekind rather than fdw_private. set_foreign_rel_properties() propagates fdwroutine onto a joinrel that pairs a foreign rel with an RTE_FUNCTION rel so GetForeignJoinPaths gets called; the FDW retains full control over whether to actually generate a path. deparseRangeTblRef and deparseColumnRef gain a FUNCTION-RTE branch that emits the function expression and resolves Vars to the generated --- contrib/postgres_fdw/deparse.c | 143 ++++- .../postgres_fdw/expected/postgres_fdw.out | 560 ++++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 499 ++++++++++++++-- contrib/postgres_fdw/postgres_fdw.h | 12 + contrib/postgres_fdw/sql/postgres_fdw.sql | 222 +++++++ src/backend/optimizer/util/relnode.c | 24 + 6 files changed, 1416 insertions(+), 44 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 2dcc6c8af1b..a2e9301fb65 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -68,6 +68,7 @@ typedef struct foreign_glob_cxt { PlannerInfo *root; /* global planner state */ RelOptInfo *foreignrel; /* the foreign relation we are planning for */ + PgFdwRelationInfo *fpinfo; /* the foreign server info we should rely on */ Relids relids; /* relids of base relations in the underlying * scan */ } foreign_glob_cxt; @@ -112,6 +113,7 @@ typedef struct deparse_expr_cxt appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno)) #define SUBQUERY_REL_ALIAS_PREFIX "s" #define SUBQUERY_COL_ALIAS_PREFIX "c" +#define FUNCTION_REL_ALIAS_PREFIX "f" /* * Functions to determine whether an expression can be evaluated safely on @@ -217,6 +219,7 @@ static void get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel, void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds) @@ -230,7 +233,7 @@ classifyConditions(PlannerInfo *root, { RestrictInfo *ri = lfirst_node(RestrictInfo, lc); - if (is_foreign_expr(root, baserel, ri->clause)) + if (is_foreign_expr(root, baserel, fpinfo, ri->clause)) *remote_conds = lappend(*remote_conds, ri); else *local_conds = lappend(*local_conds, ri); @@ -243,11 +246,11 @@ classifyConditions(PlannerInfo *root, bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr) { foreign_glob_cxt glob_cxt; foreign_loc_cxt loc_cxt; - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private); /* * Check that the expression consists of nodes that are safe to execute @@ -255,6 +258,7 @@ is_foreign_expr(PlannerInfo *root, */ glob_cxt.root = root; glob_cxt.foreignrel = baserel; + glob_cxt.fpinfo = fpinfo; /* * For an upper relation, use relids from its underneath scan relation, @@ -324,8 +328,8 @@ foreign_expr_walker(Node *node, if (node == NULL) return true; - /* May need server info from baserel's fdw_private struct */ - fpinfo = (PgFdwRelationInfo *) (glob_cxt->foreignrel->fdw_private); + /* May need server info from global context */ + fpinfo = glob_cxt->fpinfo; /* Set up inner_cxt for possible recursion to child nodes */ inner_cxt.collation = InvalidOid; @@ -2030,6 +2034,72 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, } } +/* + * Deparse a FUNCTION RTE absorbed into a foreign join. The function call(s) + * are emitted as a FROM-list item: + * + * <funcexpr> AS f<rti>(c1, c2, ..., cN) + * + * For multi-function RTEs (SQL ROWS FROM (f1(), f2(), ...)), each + * function call appears comma-separated inside ROWS FROM(...). Column + * aliases c1..cN cover the union of every function's columns, in the + * order they appear; that matches the column ordering of the RTE. + */ +static void +deparseFunctionRangeTblRef(StringInfo buf, PlannerInfo *root, + RelOptInfo *foreignrel, RelOptInfo *scanrel, + List **params_list) +{ + RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); + deparse_expr_cxt context; + ListCell *lc; + bool multi_func; + int total_cols = 0; + int i; + + Assert(rte->rtekind == RTE_FUNCTION); + Assert(!rte->funcordinality); + Assert(list_length(rte->functions) >= 1); + + multi_func = list_length(rte->functions) > 1; + + context.buf = buf; + context.root = root; + context.foreignrel = scanrel; + context.scanrel = scanrel; + context.params_list = params_list; + + if (multi_func) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (foreach_current_index(lc) > 0) + appendStringInfoString(buf, ", "); + deparseExpr((Expr *) rtfunc->funcexpr, &context); + total_cols += rtfunc->funccolcount; + } + + if (multi_func) + appendStringInfoChar(buf, ')'); + + /* Alias + generated column-name list. */ + appendStringInfo(buf, " %s%d", FUNCTION_REL_ALIAS_PREFIX, foreignrel->relid); + if (total_cols > 0) + { + appendStringInfoChar(buf, '('); + for (i = 1; i <= total_cols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + } +} + /* * Append FROM clause entry for the given relation into buf. * Conditions from lower-level SEMI-JOINs are appended to additional_conds @@ -2040,7 +2110,22 @@ deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **additional_conds, List **params_list) { - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + PgFdwRelationInfo *fpinfo; + + /* + * For a function RTE absorbed into a foreign join, deparse the function + * expression as a FROM-list item and return. The stub fpinfo set up by + * foreign_join_ok() may or may not be present here. + */ + if (foreignrel->rtekind == RTE_FUNCTION) + { + Assert(!make_subquery); + deparseFunctionRangeTblRef(buf, root, foreignrel, foreignrel, + params_list); + return; + } + + fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; /* Should only be called in these cases. */ Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel)); @@ -2712,6 +2797,54 @@ static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col) { + /* + * Function RTE columns: emit as f<varno>.c<varattno>, matching the + * aliases generated by deparseFunctionRangeTblRef(). A whole-row Var + * (varattno == 0) is rendered as ROW(f<varno>.c1, ..., f<varno>.c<N>) + * where N is the total column count of the function RTE (including all + * ROWS FROM (...) members). System attributes such as ctid have no + * meaning for function RTEs and are rejected. + */ + if (rte->rtekind == RTE_FUNCTION) + { + if (varattno == 0) + { + int ncols = list_length(rte->eref->colnames); + int i; + + if (qualify_col) + { + appendStringInfoString(buf, "CASE WHEN ("); + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfoString(buf, "*)::text IS NOT NULL THEN "); + } + + appendStringInfoString(buf, "ROW("); + for (i = 1; i <= ncols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d.%s%d", + FUNCTION_REL_ALIAS_PREFIX, varno, + SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + + if (qualify_col) + appendStringInfoString(buf, " END"); + return; + } + + if (varattno < 0) + elog(ERROR, + "system attribute reference to a function RTE is not supported in foreign join pushdown"); + + if (qualify_col) + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, varattno); + return; + } + /* We support fetching the remote side's CTID and OID. */ if (varattno == SelfItemPointerAttributeNumber) { diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index aaffcf31271..04a47dc03ed 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2885,6 +2885,566 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c (10 rows) ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: t1.c1, t1.c3 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1, t1.c3 + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", r1.c3 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{1,5,10,100}'::integer[]) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + c1 | c3 +-----+------- + 1 | 00001 + 5 | 00005 + 10 | 00010 + 100 | 00100 +(4 rows) + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Sort + Output: t1.c1 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1 + Relations: (public.ft1 t1) INNER JOIN (Function g) + Remote SQL: SELECT r1."C 1" FROM ("S 1"."T 1" r1 INNER JOIN generate_series(1, 4) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + c1 +---- + 1 + 2 + 3 + 4 +(4 rows) + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on pg_catalog.generate_series g + Output: g.id + Function Call: generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + QUERY PLAN +------------------------------------------------------------ + Hash Join + Output: t1.c1, u.ord + Hash Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" + -> Hash + Output: u.ord, u.id + -> Function Scan on pg_catalog.unnest u + Output: u.ord, u.id + Function Call: unnest('{1,5,10}'::integer[]) +(11 rows) + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: t1.c1, t2.c1 + Merge Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST + -> Sort + Output: t2.c1, u.id + Sort Key: t2.c1 + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{1,5,10,100}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(13 rows) + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: t1.c1, t2.c1 + Hash Cond: (t1.c1 = t2.c1) + -> Foreign Scan + Output: t1.c1, u.id + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", f3.c1 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r1."C 1" = f3.c1)))) + -> Hash + Output: t2.c1 + -> Foreign Scan on public.ft6 t2 + Output: t2.c1 + Remote SQL: SELECT c1 FROM "S 1"."T 4" +(12 rows) + +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: t1.c1, t2.c1 + Join Filter: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE ((c3 < '00010')) + -> Materialize + Output: t2.c1, u.id + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(12 rows) + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (Function n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + n | a | b +---+---+----- + 2 | 2 | 102 + 3 | 3 | 103 + 4 | 4 | 104 +(3 rows) + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (Function n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)) AND ((f1.c1 > 3)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); + QUERY PLAN +----------------------------------------------------------- + Hash Join + Output: n.n, r.a, r.b + Hash Cond: (r.a = n.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a, b FROM public.base_tbl_fn + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4}'::integer[]) + Filter: (n.n > f_local(3)) +(12 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +DROP FUNCTION f_local(int); +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: s.* + Hash Cond: (rt.a = s.a) + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl_fn + -> Hash + Output: s.*, s.a + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() +(11 rows) + +DROP FUNCTION f_ret_record(); +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + a | b +----+----- + 23 | 123 + 24 | 999 + 25 | 125 +(3 rows) + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + a | b +----+--- + 24 | 5 +(1 row) + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + a | b | t +----+---+--------------------- + 24 | 7 | ("(2,3),(-2,-3)",1) +(1 row) + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: r.a, t.n, t.s + Sort Key: r.a + -> Foreign Scan + Output: r.a, t.n, t.s + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT r1.a, f2.c1, f2.c2 FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + a | n | s +---+---+---- + 3 | 3 | 11 + 6 | 6 | 12 + 9 | 9 | 13 +(3 rows) + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: ((t.*)::text), r.a + Sort Key: r.a + -> Foreign Scan + Output: (t.*)::text, r.a + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT CASE WHEN (f2.*)::text IS NOT NULL THEN ROW(f2.c1, f2.c2) END, r1.a FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + t | a +--------+--- + (3,11) | 3 + (6,12) | 6 + (9,13) | 9 +(3 rows) + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: u.*, ft5.c1, ft5.c2, ft4.c1, ft4.c2 + Relations: (public.ft5) LEFT JOIN ((public.ft4) INNER JOIN (Function u)) + Remote SQL: SELECT CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END, r1.c1, r1.c2, r2.c1, r2.c2 FROM ("S 1"."T 4" r1 LEFT JOIN ("S 1"."T 3" r2 INNER JOIN ROWS FROM (unnest('{1,2}'::integer[]), unnest('{3,4}'::integer[])) f3(c1, c2) ON (((r2.c1 = f3.c1)))) ON (((r1.c1 = r2.c1)))) WHERE ((r1.c1 < 10)) ORDER BY r1.c1 ASC NULLS LAST +(4 rows) + +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + u | c1 | c2 | c1 | c2 +---+----+----+----+---- + | 3 | 4 | | + | 6 | 7 | | + | 9 | 10 | | +(3 rows) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: s.a, s.b + Sort Key: s.a + CTE s + -> Nested Loop + Output: r1.a, r1.b + -> Foreign Scan on public.remote_tbl r1 + Output: r1.a, r1.b + Remote SQL: SELECT a, b FROM public.base_tbl_fn + -> Foreign Scan + Output: NULL::integer + Relations: (public.remote_tbl r2) INNER JOIN (Function f) + Remote SQL: SELECT NULL FROM (public.base_tbl_fn r1 INNER JOIN public.f($1::integer) f2(c1) ON (TRUE)) LIMIT 1::bigint + -> CTE Scan on s + Output: s.a, s.b +(15 rows) + +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + a | b +----+----- + 1 | 101 + 2 | 102 + 3 | 103 + 4 | 104 + 5 | 105 + 6 | 106 + 7 | 107 + 8 | 108 + 9 | 109 + 10 | 110 + 11 | 111 + 12 | 112 + 13 | 113 + 14 | 114 + 15 | 115 + 16 | 116 + 17 | 117 + 18 | 118 + 19 | 119 + 20 | 120 + 21 | 121 + 22 | 122 + 23 | 123 + 24 | 7 + 25 | 125 + 26 | 126 + 27 | 127 + 28 | 128 + 29 | 129 + 30 | 130 +(30 rows) + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: r.a + Merge Cond: (t.n = r.a) + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]), generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Sort + Output: r.a + Sort Key: r.a + -> Foreign Scan on public.remote_tbl r + Output: r.a + Remote SQL: SELECT a FROM public.base_tbl_fn +(15 rows) + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Nested Loop + Output: r.a, t.x + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 3)) ORDER BY a ASC NULLS LAST + -> Function Scan on pg_catalog.unnest t + Output: t.x + Function Call: unnest(ARRAY[r.a]) +(8 rows) + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Merge Left Join + Output: r.a, t.n + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 5)) ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{1,2,3}'::integer[]) +(12 rows) + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + QUERY PLAN +-------------------------------------------------------------------------------- + Merge Semi Join + Output: r.a + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]) +(12 rows) + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 0ff4ec23164..cd7046db46d 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -31,6 +31,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/appendinfo.h" +#include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" #include "optimizer/optimizer.h" @@ -88,6 +89,22 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of per-RTE function metadata, indexed by base RTI offset. Each + * element is either NULL (for non-RTE_FUNCTION rels in this scan) or a + * list of three-element lists (funcid, funcrettype, funccollation) -- one + * inner list per function in the RTE. Allows the executor to rebuild + * TupleDesc entries for whole-row references to function RTEs. + */ + FdwScanPrivateFunctions, + + /* + * Integer node: minimum base RT index covered by the scan, used to + * translate scan-local indexes to estate-rtable indexes after setrefs.c + * flattens rtables. + */ + FdwScanPrivateMinRTIndex, }; /* @@ -124,6 +141,11 @@ enum FdwModifyPrivateIndex * 2) Boolean flag showing if the remote query has a RETURNING clause * 3) Integer list of attribute numbers retrieved by RETURNING, if any * 4) Boolean flag showing if we set the command es_processed + * 5) Per-RTE function metadata (mirrors FdwScanPrivateFunctions; lets + * the executor rebuild TupleDesc entries for whole-row Vars over + * function RTEs absorbed into a foreign join) + * 6) Integer node: minimum base RT index of the scan (mirrors + * FdwScanPrivateMinRTIndex) */ enum FdwDirectModifyPrivateIndex { @@ -135,6 +157,10 @@ enum FdwDirectModifyPrivateIndex FdwDirectModifyPrivateRetrievedAttrs, /* set-processed flag (as a Boolean node) */ FdwDirectModifyPrivateSetProcessed, + /* Per-RTE function metadata, indexed by base RTI offset */ + FdwDirectModifyPrivateFunctions, + /* Integer node: minimum base RT index in the scan */ + FdwDirectModifyPrivateMinRTIndex, }; /* @@ -740,6 +766,9 @@ static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, static List *get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel); static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, Path *epq_path, List *restrictlist); static void add_foreign_grouping_paths(PlannerInfo *root, @@ -893,7 +922,7 @@ postgresGetForeignRelSize(PlannerInfo *root, * Identify which baserestrictinfo clauses can be sent to the remote * server and which can't. */ - classifyConditions(root, baserel, baserel->baserestrictinfo, + classifyConditions(root, baserel, fpinfo, baserel->baserestrictinfo, &fpinfo->remote_conds, &fpinfo->local_conds); /* @@ -1297,7 +1326,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1373,7 +1402,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1513,7 +1542,7 @@ postgresGetForeignPlan(PlannerInfo *root, remote_exprs = lappend(remote_exprs, rinfo->clause); else if (list_member_ptr(fpinfo->local_conds, rinfo)) local_exprs = lappend(local_exprs, rinfo->clause); - else if (is_foreign_expr(root, foreignrel, rinfo->clause)) + else if (is_foreign_expr(root, foreignrel, fpinfo, rinfo->clause)) remote_exprs = lappend(remote_exprs, rinfo->clause); else local_exprs = lappend(local_exprs, rinfo->clause); @@ -1634,9 +1663,26 @@ postgresGetForeignPlan(PlannerInfo *root, fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(fpinfo->fetch_size)); + + /* + * Position FdwScanPrivateRelations: either the EXPLAIN relation string + * (joins/upper rels) or a NULL placeholder, so that subsequent indexes + * stay valid for the base-rel scan case. + */ if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + /* + * FdwScanPrivateFunctions / FdwScanPrivateMinRTIndex carry the metadata + * the executor needs to rebuild TupleDesc entries for whole-row Vars + * pointing at RTE_FUNCTION rels absorbed into the foreign scan. + */ + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + fdw_private = lappend(fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1657,9 +1703,15 @@ postgresGetForeignPlan(PlannerInfo *root, /* * Construct a tuple descriptor for the scan tuples handled by a foreign join. + * + * 'rtfuncdata' is the FdwScanPrivateFunctions list saved at plan time, and + * 'rtoffset' is the difference between the executor's RT indexes and the + * scan-local RT indexes captured in that list. Both may be 0/NIL when the + * scan has no RTE_FUNCTION dependents. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, + List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1695,13 +1747,68 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * A whole-row Var points at a FUNCTION RTE absorbed into the + * foreign join. Synthesize an anonymous composite TupleDesc from + * the per-function return-type metadata we saved at plan time; + * the deparser emits these as ROW(f<rti>.c1, f<rti>.c2, ...). + * + * For an upperrel scan (the only path that reaches here) + * postgresGetForeignPlan always builds rtfuncdata via + * get_functions_data(), so it is never NIL; the per-RTE slot for + * the function RTE referenced by this Var must likewise be + * populated. + */ + List *funcdata; + TupleDesc rte_tupdesc; + int num_funcs; + int attnum; + ListCell *lc1, + *lc2; + + Assert(rtfuncdata != NIL); + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + Assert(funcdata != NIL); + num_funcs = list_length(funcdata); + Assert(num_funcs == list_length(rte->eref->colnames)); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc1, funcdata, lc2, rte->eref->colnames) + { + List *fdata = lfirst_node(List, lc1); + char *colname = strVal(lfirst(lc2)); + Oid funcrettype; + Oid funccollation; + + funcrettype = lsecond_node(Integer, fdata)->ival; + funccollation = lthird_node(Integer, fdata)->ival; + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, + "could not determine return type for function in foreign scan"); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funccollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1737,14 +1844,30 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. For a join, scan the base relids until we + * find an RTE_RELATION (the foreign-table side); ignore any RTE_FUNCTION + * absorbed into the join, which contributes no relation OID to look up. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); + rte = NULL; if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte != NULL && rte->rtekind == RTE_RELATION) + break; + rte = NULL; + } + if (rte == NULL) + elog(ERROR, "could not locate a foreign relation RTE in foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1787,8 +1910,19 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwScanPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwScanPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, + rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2741,7 +2875,7 @@ postgresPlanDirectModify(PlannerInfo *root, if (attno <= InvalidAttrNumber) /* shouldn't happen */ elog(ERROR, "system-column update is not supported"); - if (!is_foreign_expr(root, foreignrel, (Expr *) tle->expr)) + if (!is_foreign_expr(root, foreignrel, fpinfo, (Expr *) tle->expr)) return false; } } @@ -2828,6 +2962,10 @@ postgresPlanDirectModify(PlannerInfo *root, makeBoolean((retrieved_attrs != NIL)), retrieved_attrs, makeBoolean(plan->canSetTag)); + fscan->fdw_private = lappend(fscan->fdw_private, + get_functions_data(root, foreignrel)); + fscan->fdw_private = lappend(fscan->fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Update the foreign-join-related fields. @@ -2941,7 +3079,26 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + /* + * DirectModify on a foreign join: use the per-RTE function + * metadata saved at plan time so a whole-row Var pointing at a + * function RTE absorbed into the join can be rebuilt into a + * usable TupleDesc (e.g. RETURNING t for a join with UNNEST(..., + * ...) AS t(bx, i)). + */ + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + + tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -3054,7 +3211,8 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_length(fdw_private) > FdwScanPrivateRelations && + list_nth(fdw_private, FdwScanPrivateRelations) != NULL) { StringInfoData relations; char *rawrelations; @@ -3104,6 +3262,22 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); + + /* + * If a function RTE was absorbed into the foreign join, + * render it as "Function <alias>" since we have no foreign + * relid. + */ + if (rte->rtekind == RTE_FUNCTION) + { + refname = (char *) list_nth(es->rtable_names, rti - 1); + if (refname == NULL) + refname = rte->eref->aliasname; + appendStringInfo(&relations, "Function %s", + quote_identifier(refname)); + continue; + } + Assert(rte->rtekind == RTE_RELATION); /* This logic should agree with explain.c's ExplainTargetRel */ relname = get_rel_name(rte->relid); @@ -3346,7 +3520,7 @@ estimate_path_cost_size(PlannerInfo *root, * param_join_conds might contain both clauses that are safe to send * across, and clauses that aren't. */ - classifyConditions(root, foreignrel, param_join_conds, + classifyConditions(root, foreignrel, fpinfo, param_join_conds, &remote_param_join_conds, &local_param_join_conds); /* Build the list of columns to be fetched from the foreign server. */ @@ -3479,8 +3653,17 @@ estimate_path_cost_size(PlannerInfo *root, /* For join we expect inner and outer relations set */ Assert(fpinfo->innerrel && fpinfo->outerrel); - fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; + /* + * For a FUNCTION RTE absorbed into the join, use the stub fpinfo + * we built in foreign_join_ok(), since the function rel itself + * has no fdw_private. + */ + fpinfo_i = fpinfo->inner_func_fpinfo ? + fpinfo->inner_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; + fpinfo_o = fpinfo->outer_func_fpinfo ? + fpinfo->outer_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; /* Estimate of number of rows in cross product */ nrows = fpinfo_i->rows * fpinfo_o->rows; @@ -6619,6 +6802,181 @@ semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, return ok; } +/* + * get_base_relids + * Return the set of base relids referenced by a foreign scan rel. + * + * For an upper rel we use the all-query relids minus the outer joins; + * otherwise the rel's own relids minus the outer joins. The result matches + * the relids that create_foreignscan_plan() ultimately uses for + * ForeignScan.fs_base_relids, so it is suitable for any tagging we want to + * store via plan-private state. + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + return bms_difference(relids, root->outer_join_rels); +} + +/* + * get_min_base_rti + * Lowest base RT index in the foreign scan rel. + * + * After setrefs.c flattens the rtable, the scan-local indexes saved in + * plan-private data can be translated to estate indexes by adding + * (ForeignScan.fs_base_relids min - this value). Captured at plan time + * because create_foreignscan_plan() computes the same value internally. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + +/* + * get_functions_data + * Build the per-RTE function metadata list saved as + * FdwScanPrivateFunctions. + * + * The result list is indexed by base RT index relative to the lowest base + * RT index of the scan. Each element is either NULL (for non-RTE_FUNCTION + * base rels in this scan) or a List of List of three Integer nodes: + * (funcid, funcrettype, funccollation) -- one inner list per RangeTblFunction. + * + * Only RTE_FUNCTION relids actually appearing in the foreign scan's + * fs_base_relids contribute; others are placeholders so that the consumer + * can index into the result by RTI offset. + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + Relids fscan_relids = get_base_relids(root, rel); + int i; + + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + List *funcdata = NIL; + ListCell *lc; + + if (rte == NULL || i == 0 || + !bms_is_member(i, fscan_relids) || + rte->rtekind != RTE_FUNCTION) + { + rtfuncdata = lappend(rtfuncdata, NULL); + continue; + } + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + Oid funcrettype; + Oid funccollation; + TupleDesc tupdesc; + Oid funcid = InvalidOid; + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + if (!OidIsValid(funcrettype) || funcrettype == RECORDOID) + elog(ERROR, + "could not determine return type for function in foreign scan"); + + funccollation = exprCollation(rtfunc->funcexpr); + + if (IsA(rtfunc->funcexpr, FuncExpr)) + funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid; + + funcdata = lappend(funcdata, + list_make3(makeInteger(funcid), + makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + + return rtfuncdata; +} + +/* + * Check if a relation is a FUNCTION RTE that can be absorbed into a remote + * join. Every function in the RTE must + * + * - return a well-defined scalar type -- we don't ship records/composite + * since the remote server cannot reconstruct a column definition list + * and our deparser does not emit one; + * - have a shippable expression with no mutable subnodes -- is_foreign_expr() + * rejects volatile/stable functions through contain_mutable_functions(), + * so the IMMUTABLE-only restriction is implicit; + * - not contain SubPlans -- we'd otherwise need to ship sub-results to + * the remote, which we do not implement. + * + * WITH ORDINALITY is not supported yet. + */ +static bool +function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel, + RelOptInfo *fdwrel) +{ + RangeTblEntry *rte; + ListCell *lc; + + if (rel->rtekind != RTE_FUNCTION) + return false; + rte = planner_rt_fetch(rel->relid, root); + if (rte->rtekind != RTE_FUNCTION) + return false; + if (rte->funcordinality) + return false; + + /* + * Reject up-front any function RTE that lateral-references another + * relation: foreign-join push-down would need to parameterise the remote + * query per outer row, which we don't support, and even considering the + * path is expensive on the planner side. The surrounding lateral_relids + * check in postgresGetForeignJoinPaths() would normally bail out for the + * joinrel, but doing the check here avoids walking the function + * expression entirely. + */ + if (!bms_is_empty(rel->lateral_relids)) + return false; + + Assert(list_length(rte->functions) >= 1); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + TypeFuncClass functypclass; + Oid funcrettype; + TupleDesc tupdesc; + + functypclass = get_expr_result_type(rtfunc->funcexpr, + &funcrettype, &tupdesc); + if (functypclass != TYPEFUNC_SCALAR) + return false; + if (!OidIsValid(funcrettype) || + funcrettype == RECORDOID || + funcrettype == VOIDOID) + return false; + + if (contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, fdwrel, fdwrel->fdw_private, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -6634,6 +6992,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; + bool outer_is_function = false; + bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -6652,15 +7012,76 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, return false; /* - * If either of the joining relations is marked as unsafe to pushdown, the - * join can not be pushed down. + * Detect mixed (foreign x function-RTE) cases. Only INNER joins are + * supported initially. We dispatch on rtekind here so that the same + * function RTE can be absorbed into joins on multiple foreign servers + * (each call gets its own stub fpinfo and rechecks shippability for the + * specific server). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && + (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && + fpinfo_o->pushdown_safe && + function_rte_pushdown_ok(root, innerrel, outerrel)) + { + inner_is_function = true; + } + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) + { + outer_is_function = true; + } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } + + /* + * If one side is a function RTE, allocate a stub fpinfo so the rest of + * this function and the cost estimator can treat it uniformly. We hand + * the stub to the joinrel's deparser via the same path the foreign side + * uses, but we never permanently attach it to the function rel's + * fdw_private (different joinrels may pair the same function RTE with + * different foreign servers). + */ + if (inner_is_function) + { + fpinfo_i = palloc0_object(PgFdwRelationInfo); + fpinfo_i->pushdown_safe = true; + fpinfo_i->server = fpinfo_o->server; + fpinfo_i->relation_name = psprintf("%u", innerrel->relid); + fpinfo_i->rows = innerrel->rows; + fpinfo_i->width = innerrel->reltarget->width; + fpinfo_i->retrieved_rows = innerrel->rows; + fpinfo_i->rel_startup_cost = 0; + fpinfo_i->rel_total_cost = 0; + + classifyConditions(root, innerrel, fpinfo, innerrel->baserestrictinfo, + &fpinfo_i->remote_conds, &fpinfo_i->local_conds); + fpinfo->inner_func_fpinfo = fpinfo_i; + } + else if (outer_is_function) + { + fpinfo_o = palloc0_object(PgFdwRelationInfo); + fpinfo_o->pushdown_safe = true; + fpinfo_o->server = fpinfo_i->server; + fpinfo_o->relation_name = psprintf("%u", outerrel->relid); + fpinfo_o->rows = outerrel->rows; + fpinfo_o->width = outerrel->reltarget->width; + fpinfo_o->retrieved_rows = outerrel->rows; + fpinfo_o->rel_startup_cost = 0; + fpinfo_o->rel_total_cost = 0; + + classifyConditions(root, outerrel, fpinfo, outerrel->baserestrictinfo, + &fpinfo_o->remote_conds, &fpinfo_o->local_conds); + fpinfo->outer_func_fpinfo = fpinfo_o; + } /* * If joining relations have local conditions, those conditions are @@ -6698,7 +7119,7 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, foreach(lc, extra->restrictlist) { RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc); - bool is_remote_clause = is_foreign_expr(root, joinrel, + bool is_remote_clause = is_foreign_expr(root, joinrel, fpinfo, rinfo->clause); if (IS_OUTER_JOIN(jointype) && @@ -7396,7 +7817,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * If any GROUP BY expression is not shippable, then we cannot * push down aggregation to the foreign server. */ - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; /* @@ -7424,7 +7845,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * Non-grouping expression we need to compute. Can we ship it * as-is to the foreign server? */ - if (is_foreign_expr(root, grouped_rel, expr) && + if (is_foreign_expr(root, grouped_rel, fpinfo, expr) && !is_foreign_param(root, grouped_rel, expr)) { /* Yes, so add to tlist as-is; OK to suppress duplicates */ @@ -7444,7 +7865,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * don't have to check is_foreign_param, since that certainly * won't return true for any such expression.) */ - if (!is_foreign_expr(root, grouped_rel, (Expr *) aggvars)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, (Expr *) aggvars)) return false; /* @@ -7496,7 +7917,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, grouped_rel->relids, NULL, NULL); - if (is_foreign_expr(root, grouped_rel, expr)) + if (is_foreign_expr(root, grouped_rel, fpinfo, expr)) fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo); else fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo); @@ -7533,7 +7954,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, */ if (IsA(expr, Aggref)) { - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; tlist = add_to_flat_tlist(tlist, list_make1(expr)); @@ -8046,8 +8467,8 @@ add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel, * Also, the LIMIT/OFFSET cannot be pushed down, if their expressions are * not safe to remote. */ - if (!is_foreign_expr(root, input_rel, (Expr *) parse->limitOffset) || - !is_foreign_expr(root, input_rel, (Expr *) parse->limitCount)) + if (!is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitOffset) || + !is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitCount)) return; /* Safe to push down */ @@ -8693,7 +9114,7 @@ find_em_for_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel) if (bms_is_subset(em->em_relids, rel->relids) && !bms_is_empty(em->em_relids) && bms_is_empty(bms_intersect(em->em_relids, fpinfo->hidden_subquery_rels)) && - is_foreign_expr(root, rel, em->em_expr)) + is_foreign_expr(root, rel, fpinfo, em->em_expr)) return em; } @@ -8764,7 +9185,7 @@ find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, continue; /* Check that expression (including relabels!) is shippable */ - if (is_foreign_expr(root, rel, em->em_expr)) + if (is_foreign_expr(root, rel, rel->fdw_private, em->em_expr)) return em; } diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..da7da1c2ea9 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -106,6 +106,16 @@ typedef struct PgFdwRelationInfo /* joinclauses contains only JOIN/ON conditions for an outer join */ List *joinclauses; /* List of RestrictInfo */ + /* + * If a FUNCTION RTE was absorbed into this join, these point at the stub + * PgFdwRelationInfo for the function side (paired with the + * outerrel/innerrel), so the cost estimator and deparser can find it + * without consulting the function rel's fdw_private. At most one of + * outer_func_fpinfo/inner_func_fpinfo is set. + */ + struct PgFdwRelationInfo *outer_func_fpinfo; + struct PgFdwRelationInfo *inner_func_fpinfo; + /* Upper relation information */ UpperRelationKind stage; @@ -183,11 +193,13 @@ extern char *pgfdw_application_name; /* in deparse.c */ extern void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds); extern bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr); extern bool is_foreign_param(PlannerInfo *root, RelOptInfo *baserel, diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 267d3c1a7e7..7988bec4df7 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -790,6 +790,228 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); + +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + +DROP FUNCTION f_local(int); + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; +DROP FUNCTION f_ret_record(); + +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; + +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); + +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); + +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 3fc2c2f71d0..f21ae1baeb2 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -746,6 +746,30 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if (OidIsValid(outer_rel->serverid) && + inner_rel->rtekind == RTE_FUNCTION) + { + /* + * One side is a foreign relation, the other side is a function RTE. + * If the function is IMMUTABLE, the FDW can absorb the function call + * into the remote query (the result is identical regardless of which + * server evaluates it). Let the FDW decide whether the join is + * actually shippable; here we just propagate the FDW routine so the + * FDW gets a chance. + */ + joinrel->serverid = outer_rel->serverid; + joinrel->userid = outer_rel->userid; + joinrel->useridiscurrent = outer_rel->useridiscurrent; + joinrel->fdwroutine = outer_rel->fdwroutine; + } + else if (OidIsValid(inner_rel->serverid) && + outer_rel->rtekind == RTE_FUNCTION) + { + joinrel->serverid = inner_rel->serverid; + joinrel->userid = inner_rel->userid; + joinrel->useridiscurrent = inner_rel->useridiscurrent; + joinrel->fdwroutine = inner_rel->fdwroutine; + } } /* -- 2.43.0
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-07-06 14:11                       ` Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Korotkov @ 2026-07-06 14:11 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi, Alexander!

On Wed, May 20, 2026 at 1:17 PM Alexander Pyhalov
<a.pyhalov@postgrespro.ru> wrote:
> I've found another issue. The fact that in the new versions of the patch
> RTE RelOptInfo misses fdw_private seems to be unfortunate. For example,
> in the last version we haven't thought about classifying
> baserestrictinfo. And if we do, we should pass fdw_private down to
> foreign_expr_walker. Perhaps, we could attach it to RTE_FUNCTION rel
> prior to calling classifyConditions(), but should we later set it back
> to NULL? Another problem comes if we try to handle joins,  which can
> crearte subqueries (like INNER/OUTER UNIQUE). In this case we should
> somehow cook fpinfo for get_relation_column_alias_ids(). Attaching patch
> which tries to handle baserestrictinfos by passing fpinfo down to
> foreign_expr_walker().

I think passing fpinfo down to foreign_expr_walker() is the right
approach, thank you.  Attaching it to RTE_FUNCTION rel, and reseting
it back to NULL would create excessive state and potential source of
bugs.  The only advantage is saving existing function signatures, but
it doesn't worth it.

Also, I don't think we need to care bout
get_relation_column_alias_ids().  As we currently pushdown function
only for inner joins, make_outerrel_subquery/make_innerrel_subquery
are always false, lower_subquery_rels also wouldn't contain
RTE_FUNCTION relid.  Therefore:

 * In deparseFromExprForRel() for functional rel deparseRangeTblRef()
is always called with make_subquery=false.
 * is_subquery_var() returns false.

> One more interesting example (included in the patch) is
>
> EXPLAIN (VERBOSE, COSTS OFF)
> WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1
> JOIN LATERAL
> (SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s
> ON true)
> SELECT * FROM s ORDER BY 1;
>
> We get the following plan:
>
>   Sort
>     Output: s.a, s.b
>     Sort Key: s.a
>     CTE s
>       ->  Nested Loop
>             Output: r1.a, r1.b
>             ->  Foreign Scan on public.remote_tbl r1
>                   Output: r1.a, r1.b
>                   Remote SQL: SELECT a, b FROM public.base_tbl_fn
>             ->  Foreign Scan
>                   Output: NULL::integer
>                   Relations: (public.remote_tbl r2) INNER JOIN (Function
> f)
>                   Remote SQL: SELECT NULL FROM (public.base_tbl_fn r1
> INNER JOIN public.f($1::integer) f2(c1) ON (TRUE)) LIMIT 1::bigint
>     ->  CTE Scan on s
>           Output: s.a, s.b
>
> Here you can see that we use parameter in function argument. Don't know
> if it's a real problem, but at least looks suspicious. In v3 patch used
> contain_param_walker() in is_nonrel_relinfo_ok() (which mutated to
> function_rte_pushdown_ok()) to avoid such plans.

AFAICS, there is no correctness problem.

 * The bms_is_empty(rel->lateral_relids) check rejects a lateral
reference to a relation at the same query level.
 * In the example, f(r1.a) references r1 from an *outer* level. When
the subquery is planned, r1.a becomes a PARAM_EXEC, and the function
rel's lateral_relids inside the subquery is empty -- so the check
passes and funcexpr retains a Param.
 * foreign_expr_walker deliberately allows PARAM_EXEC
(deparse.c:486–505), and postgres_fdw's normal machinery (params_list
=> fdw_exprs) re-sends the param on each rescan.

So there's no need to bring back v3's contain_param_walker() — this is
actually a useful capability (a parameterized foreign scan). I only
add a comment in function_rte_pushdown_ok() noting that outer-level
Params are allowed intentionally and handled as an ordinary
parameterized foreign scan.

> One minor issue I've noticed is in function_rte_pushdown_ok():
> +       if (rel->rtekind != RTE_FUNCTION)
> +               return false;
> +       rte = planner_rt_fetch(rel->relid, root);
> +       if (rte->rtekind != RTE_FUNCTION)
> +               return false;
>
> Is the second rtekind check necessary?

The second check is not necessary, changed to an assert.

Other changes I made:

1. In foreign_join_ok(), the function side's baserestrictinfo was
classified against the joinrel fpinfo, whose
server/shippable_extensions aren't set until merge_fdw_options() runs
later — so extension-shippable quals would be misclassified as local
and silently kill the pushdown. Now it: (a) copies
shippable_extensions from the foreign side onto the stub, and (b)
classifies against the stub (fpinfo_i/fpinfo_o, which already has
server). Built-in quals like n > 3 were unaffected; this fixes the
extension case.  I've added the test case for this.

2. Dropped unused funcid. The per-RTE metadata was a 3-element list
(funcid, funcrettype, funccollation) but funcid was never read.
Reduced to list_make2(funcrettype, funccollation); updated the
consumer (linitial/lsecond) and both descriptive comments.

3. Changed redundant elog(ERROR) into Assert in get_functions_data()
and get_tupdesc_for_join_scan_tuples(). The return-type validity is
already guaranteed by function_rte_pushdown_ok(), so these are pure
cross-checks.

4. Style consistency in find_em_for_rel_target(): introduced a named
fpinfo local instead of passing rel->fdw_private inline, matching
find_em_for_rel().

5. Also added test for nullable-side whole-row Var, but with outer
rows that both match and miss the (foreign x function) inner join.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

v10-0001-postgres_fdw-push-down-FUNCTION-RTE-into-foreign.patch (application/octet-stream, 79.6K) download From 87e2bbb0e6554938d07a95c5f99e4afbb6f3e625 Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Wed, 20 May 2026 09:22:51 +0300 Subject: [PATCH v10] postgres_fdw: push down FUNCTION RTE into foreign joins A foreign join planning hook now considers a (foreign-table x function-RTE) INNER join as a push-down candidate when the function expression is IMMUTABLE and otherwise shippable. The remote query absorbs the function call as a FROM-list item (e.g. unnest(...) AS f<rti>(c1, c2, ...)), so the foreign side returns only rows that match the function-produced set and the join executes entirely on the remote. An IMMUTABLE function gives the same result on any server, so the same function RTE can be a push-down candidate for several distinct foreign servers without semantic risk. To keep the planner state consistent across those independent attempts, the per-call stub fpinfo for the function side lives on the joinrel's PgFdwRelationInfo (new outer_func_fpinfo / inner_func_fpinfo), never on the function rel itself, and the function side is detected via rtekind rather than fdw_private. set_foreign_rel_properties() propagates fdwroutine onto a joinrel that pairs a foreign rel with an RTE_FUNCTION rel so GetForeignJoinPaths gets called; the FDW retains full control over whether to actually generate a path. deparseRangeTblRef and deparseColumnRef gain a FUNCTION-RTE branch that emits the function expression and resolves Vars to the generated --- contrib/postgres_fdw/deparse.c | 143 +++- .../postgres_fdw/expected/postgres_fdw.out | 631 ++++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 522 +++++++++++++-- contrib/postgres_fdw/postgres_fdw.h | 12 + contrib/postgres_fdw/sql/postgres_fdw.sql | 265 ++++++++ src/backend/optimizer/util/relnode.c | 24 + 6 files changed, 1553 insertions(+), 44 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 2dcc6c8af1b..a2e9301fb65 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -68,6 +68,7 @@ typedef struct foreign_glob_cxt { PlannerInfo *root; /* global planner state */ RelOptInfo *foreignrel; /* the foreign relation we are planning for */ + PgFdwRelationInfo *fpinfo; /* the foreign server info we should rely on */ Relids relids; /* relids of base relations in the underlying * scan */ } foreign_glob_cxt; @@ -112,6 +113,7 @@ typedef struct deparse_expr_cxt appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno)) #define SUBQUERY_REL_ALIAS_PREFIX "s" #define SUBQUERY_COL_ALIAS_PREFIX "c" +#define FUNCTION_REL_ALIAS_PREFIX "f" /* * Functions to determine whether an expression can be evaluated safely on @@ -217,6 +219,7 @@ static void get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel, void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds) @@ -230,7 +233,7 @@ classifyConditions(PlannerInfo *root, { RestrictInfo *ri = lfirst_node(RestrictInfo, lc); - if (is_foreign_expr(root, baserel, ri->clause)) + if (is_foreign_expr(root, baserel, fpinfo, ri->clause)) *remote_conds = lappend(*remote_conds, ri); else *local_conds = lappend(*local_conds, ri); @@ -243,11 +246,11 @@ classifyConditions(PlannerInfo *root, bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr) { foreign_glob_cxt glob_cxt; foreign_loc_cxt loc_cxt; - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private); /* * Check that the expression consists of nodes that are safe to execute @@ -255,6 +258,7 @@ is_foreign_expr(PlannerInfo *root, */ glob_cxt.root = root; glob_cxt.foreignrel = baserel; + glob_cxt.fpinfo = fpinfo; /* * For an upper relation, use relids from its underneath scan relation, @@ -324,8 +328,8 @@ foreign_expr_walker(Node *node, if (node == NULL) return true; - /* May need server info from baserel's fdw_private struct */ - fpinfo = (PgFdwRelationInfo *) (glob_cxt->foreignrel->fdw_private); + /* May need server info from global context */ + fpinfo = glob_cxt->fpinfo; /* Set up inner_cxt for possible recursion to child nodes */ inner_cxt.collation = InvalidOid; @@ -2030,6 +2034,72 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, } } +/* + * Deparse a FUNCTION RTE absorbed into a foreign join. The function call(s) + * are emitted as a FROM-list item: + * + * <funcexpr> AS f<rti>(c1, c2, ..., cN) + * + * For multi-function RTEs (SQL ROWS FROM (f1(), f2(), ...)), each + * function call appears comma-separated inside ROWS FROM(...). Column + * aliases c1..cN cover the union of every function's columns, in the + * order they appear; that matches the column ordering of the RTE. + */ +static void +deparseFunctionRangeTblRef(StringInfo buf, PlannerInfo *root, + RelOptInfo *foreignrel, RelOptInfo *scanrel, + List **params_list) +{ + RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); + deparse_expr_cxt context; + ListCell *lc; + bool multi_func; + int total_cols = 0; + int i; + + Assert(rte->rtekind == RTE_FUNCTION); + Assert(!rte->funcordinality); + Assert(list_length(rte->functions) >= 1); + + multi_func = list_length(rte->functions) > 1; + + context.buf = buf; + context.root = root; + context.foreignrel = scanrel; + context.scanrel = scanrel; + context.params_list = params_list; + + if (multi_func) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (foreach_current_index(lc) > 0) + appendStringInfoString(buf, ", "); + deparseExpr((Expr *) rtfunc->funcexpr, &context); + total_cols += rtfunc->funccolcount; + } + + if (multi_func) + appendStringInfoChar(buf, ')'); + + /* Alias + generated column-name list. */ + appendStringInfo(buf, " %s%d", FUNCTION_REL_ALIAS_PREFIX, foreignrel->relid); + if (total_cols > 0) + { + appendStringInfoChar(buf, '('); + for (i = 1; i <= total_cols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + } +} + /* * Append FROM clause entry for the given relation into buf. * Conditions from lower-level SEMI-JOINs are appended to additional_conds @@ -2040,7 +2110,22 @@ deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **additional_conds, List **params_list) { - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + PgFdwRelationInfo *fpinfo; + + /* + * For a function RTE absorbed into a foreign join, deparse the function + * expression as a FROM-list item and return. The stub fpinfo set up by + * foreign_join_ok() may or may not be present here. + */ + if (foreignrel->rtekind == RTE_FUNCTION) + { + Assert(!make_subquery); + deparseFunctionRangeTblRef(buf, root, foreignrel, foreignrel, + params_list); + return; + } + + fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; /* Should only be called in these cases. */ Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel)); @@ -2712,6 +2797,54 @@ static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col) { + /* + * Function RTE columns: emit as f<varno>.c<varattno>, matching the + * aliases generated by deparseFunctionRangeTblRef(). A whole-row Var + * (varattno == 0) is rendered as ROW(f<varno>.c1, ..., f<varno>.c<N>) + * where N is the total column count of the function RTE (including all + * ROWS FROM (...) members). System attributes such as ctid have no + * meaning for function RTEs and are rejected. + */ + if (rte->rtekind == RTE_FUNCTION) + { + if (varattno == 0) + { + int ncols = list_length(rte->eref->colnames); + int i; + + if (qualify_col) + { + appendStringInfoString(buf, "CASE WHEN ("); + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfoString(buf, "*)::text IS NOT NULL THEN "); + } + + appendStringInfoString(buf, "ROW("); + for (i = 1; i <= ncols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d.%s%d", + FUNCTION_REL_ALIAS_PREFIX, varno, + SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + + if (qualify_col) + appendStringInfoString(buf, " END"); + return; + } + + if (varattno < 0) + elog(ERROR, + "system attribute reference to a function RTE is not supported in foreign join pushdown"); + + if (qualify_col) + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, varattno); + return; + } + /* We support fetching the remote side's CTID and OID. */ if (varattno == SelfItemPointerAttributeNumber) { diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index 0805c56cb1b..d1a9b82f32f 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2885,6 +2885,637 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c (10 rows) ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: t1.c1, t1.c3 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1, t1.c3 + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", r1.c3 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{1,5,10,100}'::integer[]) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + c1 | c3 +-----+------- + 1 | 00001 + 5 | 00005 + 10 | 00010 + 100 | 00100 +(4 rows) + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Sort + Output: t1.c1 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1 + Relations: (public.ft1 t1) INNER JOIN (Function g) + Remote SQL: SELECT r1."C 1" FROM ("S 1"."T 1" r1 INNER JOIN generate_series(1, 4) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + c1 +---- + 1 + 2 + 3 + 4 +(4 rows) + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on pg_catalog.generate_series g + Output: g.id + Function Call: generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + QUERY PLAN +------------------------------------------------------------ + Hash Join + Output: t1.c1, u.ord + Hash Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" + -> Hash + Output: u.ord, u.id + -> Function Scan on pg_catalog.unnest u + Output: u.ord, u.id + Function Call: unnest('{1,5,10}'::integer[]) +(11 rows) + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: t1.c1, t2.c1 + Merge Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST + -> Sort + Output: t2.c1, u.id + Sort Key: t2.c1 + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{1,5,10,100}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(13 rows) + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: t1.c1, t2.c1 + Hash Cond: (t1.c1 = t2.c1) + -> Foreign Scan + Output: t1.c1, u.id + Relations: (public.ft1 t1) INNER JOIN (Function u) + Remote SQL: SELECT r1."C 1", f3.c1 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r1."C 1" = f3.c1)))) + -> Hash + Output: t2.c1 + -> Foreign Scan on public.ft6 t2 + Output: t2.c1 + Remote SQL: SELECT c1 FROM "S 1"."T 4" +(12 rows) + +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: t1.c1, t2.c1 + Join Filter: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE ((c3 < '00010')) + -> Materialize + Output: t2.c1, u.id + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (Function u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(12 rows) + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (Function n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + n | a | b +---+---+----- + 2 | 2 | 102 + 3 | 3 | 103 + 4 | 4 | 104 +(3 rows) + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (Function n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)) AND ((f1.c1 > 3)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); + QUERY PLAN +----------------------------------------------------------- + Hash Join + Output: n.n, r.a, r.b + Hash Cond: (r.a = n.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a, b FROM public.base_tbl_fn + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4}'::integer[]) + Filter: (n.n > f_local(3)) +(12 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +DROP FUNCTION f_local(int); +-- Check that a qual on the function RTE using a function from a shippable +-- extension is pushed down. plpgsql (not inlined) with the column as +-- argument (not const-folded) keeps the function call in the qual. +CREATE FUNCTION f_ext(int) RETURNS int AS $$ +BEGIN RETURN $1; END +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ext(int); +-- Force pushdown so the fixed-code plan is deterministically a Foreign +-- Scan; on the unfixed code the qual is classified local, the join is +-- refused, and the plan falls back to a local join instead. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and f_ext(n) > 3; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: n.n, r.a, r.b + Relations: (Function n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)) AND ((public.f_ext(f1.c1) > 3)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and f_ext(n) > 3 ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ext(int); +DROP FUNCTION f_ext(int); +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: s.* + Hash Cond: (rt.a = s.a) + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl_fn + -> Hash + Output: s.*, s.a + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() +(11 rows) + +DROP FUNCTION f_ret_record(); +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + a | b +----+----- + 23 | 123 + 24 | 999 + 25 | 125 +(3 rows) + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + a | b +----+--- + 24 | 5 +(1 row) + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + a | b | t +----+---+--------------------- + 24 | 7 | ("(2,3),(-2,-3)",1) +(1 row) + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: r.a, t.n, t.s + Sort Key: r.a + -> Foreign Scan + Output: r.a, t.n, t.s + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT r1.a, f2.c1, f2.c2 FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + a | n | s +---+---+---- + 3 | 3 | 11 + 6 | 6 | 12 + 9 | 9 | 13 +(3 rows) + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: ((t.*)::text), r.a + Sort Key: r.a + -> Foreign Scan + Output: (t.*)::text, r.a + Relations: (public.remote_tbl r) INNER JOIN (Function t) + Remote SQL: SELECT CASE WHEN (f2.*)::text IS NOT NULL THEN ROW(f2.c1, f2.c2) END, r1.a FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + t | a +--------+--- + (3,11) | 3 + (6,12) | 6 + (9,13) | 9 +(3 rows) + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: u.*, ft5.c1, ft5.c2, ft4.c1, ft4.c2 + Relations: (public.ft5) LEFT JOIN ((public.ft4) INNER JOIN (Function u)) + Remote SQL: SELECT CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END, r1.c1, r1.c2, r2.c1, r2.c2 FROM ("S 1"."T 4" r1 LEFT JOIN ("S 1"."T 3" r2 INNER JOIN ROWS FROM (unnest('{1,2}'::integer[]), unnest('{3,4}'::integer[])) f3(c1, c2) ON (((r2.c1 = f3.c1)))) ON (((r1.c1 = r2.c1)))) WHERE ((r1.c1 < 10)) ORDER BY r1.c1 ASC NULLS LAST +(4 rows) + +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + u | c1 | c2 | c1 | c2 +---+----+----+----+---- + | 3 | 4 | | + | 6 | 7 | | + | 9 | 10 | | +(3 rows) + +-- Same nullable-side whole-row Var, but with outer rows that both match +-- and miss the (foreign x function) inner join. A multi-column function +-- RTE is used so that the reference is a genuine whole-row Var (a single +-- scalar-returning function would collapse to its lone column). This +-- exercises the THEN ROW(...) side of deparseColumnRef()'s whole-row CASE +-- (matched rows reconstruct the composite) as well as the NULL side +-- (missed rows), confirming the executor rebuilds the anonymous composite +-- correctly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: l.a, t.* + Relations: (public.remote_tbl l) LEFT JOIN ((public.remote_tbl r) INNER JOIN (Function t)) + Remote SQL: SELECT r1.a, CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END FROM (public.base_tbl_fn r1 LEFT JOIN (public.base_tbl_fn r2 INNER JOIN ROWS FROM (unnest('{2,4}'::integer[]), unnest('{20,40}'::integer[])) f3(c1, c2) ON (((r2.a = f3.c1)))) ON (((r1.a = r2.a)))) WHERE ((r1.a < 6)) ORDER BY r1.a ASC NULLS LAST +(4 rows) + +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; + a | t +---+-------- + 1 | + 2 | (2,20) + 3 | + 4 | (4,40) + 5 | +(5 rows) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: s.a, s.b + Sort Key: s.a + CTE s + -> Nested Loop + Output: r1.a, r1.b + -> Foreign Scan on public.remote_tbl r1 + Output: r1.a, r1.b + Remote SQL: SELECT a, b FROM public.base_tbl_fn + -> Foreign Scan + Output: NULL::integer + Relations: (public.remote_tbl r2) INNER JOIN (Function f) + Remote SQL: SELECT NULL FROM (public.base_tbl_fn r1 INNER JOIN public.f($1::integer) f2(c1) ON (TRUE)) LIMIT 1::bigint + -> CTE Scan on s + Output: s.a, s.b +(15 rows) + +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + a | b +----+----- + 1 | 101 + 2 | 102 + 3 | 103 + 4 | 104 + 5 | 105 + 6 | 106 + 7 | 107 + 8 | 108 + 9 | 109 + 10 | 110 + 11 | 111 + 12 | 112 + 13 | 113 + 14 | 114 + 15 | 115 + 16 | 116 + 17 | 117 + 18 | 118 + 19 | 119 + 20 | 120 + 21 | 121 + 22 | 122 + 23 | 123 + 24 | 7 + 25 | 125 + 26 | 126 + 27 | 127 + 28 | 128 + 29 | 129 + 30 | 130 +(30 rows) + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: r.a + Merge Cond: (t.n = r.a) + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]), generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Sort + Output: r.a + Sort Key: r.a + -> Foreign Scan on public.remote_tbl r + Output: r.a + Remote SQL: SELECT a FROM public.base_tbl_fn +(15 rows) + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Nested Loop + Output: r.a, t.x + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 3)) ORDER BY a ASC NULLS LAST + -> Function Scan on pg_catalog.unnest t + Output: t.x + Function Call: unnest(ARRAY[r.a]) +(8 rows) + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Merge Left Join + Output: r.a, t.n + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 5)) ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{1,2,3}'::integer[]) +(12 rows) + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + QUERY PLAN +-------------------------------------------------------------------------------- + Merge Semi Join + Output: r.a + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]) +(12 rows) + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 6fa45773c30..c086f9b9adc 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -31,6 +31,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/appendinfo.h" +#include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" #include "optimizer/optimizer.h" @@ -88,6 +89,22 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of per-RTE function metadata, indexed by base RTI offset. Each + * element is either NULL (for non-RTE_FUNCTION rels in this scan) or a + * list of two-element lists (funcrettype, funccollation) -- one inner + * list per function in the RTE. Allows the executor to rebuild TupleDesc + * entries for whole-row references to function RTEs. + */ + FdwScanPrivateFunctions, + + /* + * Integer node: minimum base RT index covered by the scan, used to + * translate scan-local indexes to estate-rtable indexes after setrefs.c + * flattens rtables. + */ + FdwScanPrivateMinRTIndex, }; /* @@ -124,6 +141,11 @@ enum FdwModifyPrivateIndex * 2) Boolean flag showing if the remote query has a RETURNING clause * 3) Integer list of attribute numbers retrieved by RETURNING, if any * 4) Boolean flag showing if we set the command es_processed + * 5) Per-RTE function metadata (mirrors FdwScanPrivateFunctions; lets + * the executor rebuild TupleDesc entries for whole-row Vars over + * function RTEs absorbed into a foreign join) + * 6) Integer node: minimum base RT index of the scan (mirrors + * FdwScanPrivateMinRTIndex) */ enum FdwDirectModifyPrivateIndex { @@ -135,6 +157,10 @@ enum FdwDirectModifyPrivateIndex FdwDirectModifyPrivateRetrievedAttrs, /* set-processed flag (as a Boolean node) */ FdwDirectModifyPrivateSetProcessed, + /* Per-RTE function metadata, indexed by base RTI offset */ + FdwDirectModifyPrivateFunctions, + /* Integer node: minimum base RT index in the scan */ + FdwDirectModifyPrivateMinRTIndex, }; /* @@ -741,6 +767,9 @@ static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, static List *get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel); static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, Path *epq_path, List *restrictlist); static void add_foreign_grouping_paths(PlannerInfo *root, @@ -894,7 +923,7 @@ postgresGetForeignRelSize(PlannerInfo *root, * Identify which baserestrictinfo clauses can be sent to the remote * server and which can't. */ - classifyConditions(root, baserel, baserel->baserestrictinfo, + classifyConditions(root, baserel, fpinfo, baserel->baserestrictinfo, &fpinfo->remote_conds, &fpinfo->local_conds); /* @@ -1298,7 +1327,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1374,7 +1403,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1514,7 +1543,7 @@ postgresGetForeignPlan(PlannerInfo *root, remote_exprs = lappend(remote_exprs, rinfo->clause); else if (list_member_ptr(fpinfo->local_conds, rinfo)) local_exprs = lappend(local_exprs, rinfo->clause); - else if (is_foreign_expr(root, foreignrel, rinfo->clause)) + else if (is_foreign_expr(root, foreignrel, fpinfo, rinfo->clause)) remote_exprs = lappend(remote_exprs, rinfo->clause); else local_exprs = lappend(local_exprs, rinfo->clause); @@ -1635,9 +1664,26 @@ postgresGetForeignPlan(PlannerInfo *root, fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(fpinfo->fetch_size)); + + /* + * Position FdwScanPrivateRelations: either the EXPLAIN relation string + * (joins/upper rels) or a NULL placeholder, so that subsequent indexes + * stay valid for the base-rel scan case. + */ if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + /* + * FdwScanPrivateFunctions / FdwScanPrivateMinRTIndex carry the metadata + * the executor needs to rebuild TupleDesc entries for whole-row Vars + * pointing at RTE_FUNCTION rels absorbed into the foreign scan. + */ + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + fdw_private = lappend(fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1658,9 +1704,15 @@ postgresGetForeignPlan(PlannerInfo *root, /* * Construct a tuple descriptor for the scan tuples handled by a foreign join. + * + * 'rtfuncdata' is the FdwScanPrivateFunctions list saved at plan time, and + * 'rtoffset' is the difference between the executor's RT indexes and the + * scan-local RT indexes captured in that list. Both may be 0/NIL when the + * scan has no RTE_FUNCTION dependents. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, + List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1696,13 +1748,67 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * A whole-row Var points at a FUNCTION RTE absorbed into the + * foreign join. Synthesize an anonymous composite TupleDesc from + * the per-function return-type metadata we saved at plan time; + * the deparser emits these as ROW(f<rti>.c1, f<rti>.c2, ...). + * + * For an upperrel scan (the only path that reaches here) + * postgresGetForeignPlan always builds rtfuncdata via + * get_functions_data(), so it is never NIL; the per-RTE slot for + * the function RTE referenced by this Var must likewise be + * populated. + */ + List *funcdata; + TupleDesc rte_tupdesc; + int num_funcs; + int attnum; + ListCell *lc1, + *lc2; + + Assert(rtfuncdata != NIL); + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + Assert(funcdata != NIL); + num_funcs = list_length(funcdata); + Assert(num_funcs == list_length(rte->eref->colnames)); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc1, funcdata, lc2, rte->eref->colnames) + { + List *fdata = lfirst_node(List, lc1); + char *colname = strVal(lfirst(lc2)); + Oid funcrettype; + Oid funccollation; + + funcrettype = linitial_node(Integer, fdata)->ival; + funccollation = lsecond_node(Integer, fdata)->ival; + + /* get_functions_data() already validated the return type. */ + Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funccollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1738,14 +1844,30 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. For a join, scan the base relids until we + * find an RTE_RELATION (the foreign-table side); ignore any RTE_FUNCTION + * absorbed into the join, which contributes no relation OID to look up. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); + rte = NULL; if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte != NULL && rte->rtekind == RTE_RELATION) + break; + rte = NULL; + } + if (rte == NULL) + elog(ERROR, "could not locate a foreign relation RTE in foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1788,8 +1910,19 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwScanPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwScanPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, + rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2742,7 +2875,7 @@ postgresPlanDirectModify(PlannerInfo *root, if (attno <= InvalidAttrNumber) /* shouldn't happen */ elog(ERROR, "system-column update is not supported"); - if (!is_foreign_expr(root, foreignrel, (Expr *) tle->expr)) + if (!is_foreign_expr(root, foreignrel, fpinfo, (Expr *) tle->expr)) return false; } } @@ -2829,6 +2962,10 @@ postgresPlanDirectModify(PlannerInfo *root, makeBoolean((retrieved_attrs != NIL)), retrieved_attrs, makeBoolean(plan->canSetTag)); + fscan->fdw_private = lappend(fscan->fdw_private, + get_functions_data(root, foreignrel)); + fscan->fdw_private = lappend(fscan->fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Update the foreign-join-related fields. @@ -2942,7 +3079,26 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + /* + * DirectModify on a foreign join: use the per-RTE function + * metadata saved at plan time so a whole-row Var pointing at a + * function RTE absorbed into the join can be rebuilt into a + * usable TupleDesc (e.g. RETURNING t for a join with UNNEST(..., + * ...) AS t(bx, i)). + */ + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + + tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -3055,7 +3211,8 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_length(fdw_private) > FdwScanPrivateRelations && + list_nth(fdw_private, FdwScanPrivateRelations) != NULL) { StringInfoData relations; char *rawrelations; @@ -3105,6 +3262,22 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); + + /* + * If a function RTE was absorbed into the foreign join, + * render it as "Function <alias>" since we have no foreign + * relid. + */ + if (rte->rtekind == RTE_FUNCTION) + { + refname = (char *) list_nth(es->rtable_names, rti - 1); + if (refname == NULL) + refname = rte->eref->aliasname; + appendStringInfo(&relations, "Function %s", + quote_identifier(refname)); + continue; + } + Assert(rte->rtekind == RTE_RELATION); /* This logic should agree with explain.c's ExplainTargetRel */ relname = get_rel_name(rte->relid); @@ -3347,7 +3520,7 @@ estimate_path_cost_size(PlannerInfo *root, * param_join_conds might contain both clauses that are safe to send * across, and clauses that aren't. */ - classifyConditions(root, foreignrel, param_join_conds, + classifyConditions(root, foreignrel, fpinfo, param_join_conds, &remote_param_join_conds, &local_param_join_conds); /* Build the list of columns to be fetched from the foreign server. */ @@ -3480,8 +3653,17 @@ estimate_path_cost_size(PlannerInfo *root, /* For join we expect inner and outer relations set */ Assert(fpinfo->innerrel && fpinfo->outerrel); - fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; + /* + * For a FUNCTION RTE absorbed into the join, use the stub fpinfo + * we built in foreign_join_ok(), since the function rel itself + * has no fdw_private. + */ + fpinfo_i = fpinfo->inner_func_fpinfo ? + fpinfo->inner_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; + fpinfo_o = fpinfo->outer_func_fpinfo ? + fpinfo->outer_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; /* Estimate of number of rows in cross product */ nrows = fpinfo_i->rows * fpinfo_o->rows; @@ -6639,6 +6821,194 @@ semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, return ok; } +/* + * get_base_relids + * Return the set of base relids referenced by a foreign scan rel. + * + * For an upper rel we use the all-query relids minus the outer joins; + * otherwise the rel's own relids minus the outer joins. The result matches + * the relids that create_foreignscan_plan() ultimately uses for + * ForeignScan.fs_base_relids, so it is suitable for any tagging we want to + * store via plan-private state. + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + return bms_difference(relids, root->outer_join_rels); +} + +/* + * get_min_base_rti + * Lowest base RT index in the foreign scan rel. + * + * After setrefs.c flattens the rtable, the scan-local indexes saved in + * plan-private data can be translated to estate indexes by adding + * (ForeignScan.fs_base_relids min - this value). Captured at plan time + * because create_foreignscan_plan() computes the same value internally. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + +/* + * get_functions_data + * Build the per-RTE function metadata list saved as + * FdwScanPrivateFunctions. + * + * The result list is indexed by base RT index relative to the lowest base + * RT index of the scan. Each element is either NULL (for non-RTE_FUNCTION + * base rels in this scan) or a List of List of two Integer nodes: + * (funcrettype, funccollation) -- one inner list per RangeTblFunction. + * + * Only RTE_FUNCTION relids actually appearing in the foreign scan's + * fs_base_relids contribute; others are placeholders so that the consumer + * can index into the result by RTI offset. + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + Relids fscan_relids = get_base_relids(root, rel); + int i; + + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + List *funcdata = NIL; + ListCell *lc; + + if (rte == NULL || i == 0 || + !bms_is_member(i, fscan_relids) || + rte->rtekind != RTE_FUNCTION) + { + rtfuncdata = lappend(rtfuncdata, NULL); + continue; + } + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + Oid funcrettype; + Oid funccollation; + TupleDesc tupdesc; + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + /* + * function_rte_pushdown_ok() already rejected any function that + * doesn't return a well-defined scalar type, so this is a mere + * cross-check. + */ + Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID); + + funccollation = exprCollation(rtfunc->funcexpr); + + funcdata = lappend(funcdata, + list_make2(makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + + return rtfuncdata; +} + +/* + * Check if a relation is a FUNCTION RTE that can be absorbed into a remote + * join. Every function in the RTE must + * + * - return a well-defined scalar type -- we don't ship records/composite + * since the remote server cannot reconstruct a column definition list + * and our deparser does not emit one; + * - have a shippable expression with no mutable subnodes -- is_foreign_expr() + * rejects volatile/stable functions through contain_mutable_functions(), + * so the IMMUTABLE-only restriction is implicit; + * - not contain SubPlans -- we'd otherwise need to ship sub-results to + * the remote, which we do not implement. + * + * WITH ORDINALITY is not supported yet. + */ +static bool +function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel, + RelOptInfo *fdwrel) +{ + RangeTblEntry *rte; + ListCell *lc; + + if (rel->rtekind != RTE_FUNCTION) + return false; + rte = planner_rt_fetch(rel->relid, root); + + /* + * build_simple_rel() copies rtekind straight from the RTE, so for a base + * rel rel->rtekind always matches the RTE's; the check above is therefore + * sufficient. + */ + Assert(rte->rtekind == RTE_FUNCTION); + + if (rte->funcordinality) + return false; + + /* + * Reject up-front any function RTE that lateral-references another + * relation: foreign-join push-down would need to parameterise the remote + * query per outer row, which we don't support, and even considering the + * path is expensive on the planner side. The surrounding lateral_relids + * check in postgresGetForeignJoinPaths() would normally bail out for the + * joinrel, but doing the check here avoids walking the function + * expression entirely. + * + * Note this rejects only lateral references to another relation at the + * same query level. A function argument referencing an outer query level + * (e.g. f(outer.col) inside a subquery) is a different case: it becomes a + * PARAM_EXEC Param, the function rel's lateral_relids is empty, and + * foreign_expr_walker() intentionally treats PARAM_EXEC as shippable. + * The remote query then carries a parameter placeholder, and + * postgres_fdw's ordinary parameter machinery re-sends it on each rescan + * -- i.e. it works as a normal parameterized foreign scan, which is fine. + */ + if (!bms_is_empty(rel->lateral_relids)) + return false; + + Assert(list_length(rte->functions) >= 1); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + TypeFuncClass functypclass; + Oid funcrettype; + TupleDesc tupdesc; + + functypclass = get_expr_result_type(rtfunc->funcexpr, + &funcrettype, &tupdesc); + if (functypclass != TYPEFUNC_SCALAR) + return false; + if (!OidIsValid(funcrettype) || + funcrettype == RECORDOID || + funcrettype == VOIDOID) + return false; + + if (contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, fdwrel, fdwrel->fdw_private, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -6654,6 +7024,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; + bool outer_is_function = false; + bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -6672,15 +7044,86 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, return false; /* - * If either of the joining relations is marked as unsafe to pushdown, the - * join can not be pushed down. + * Detect mixed (foreign x function-RTE) cases. Only INNER joins are + * supported initially. We dispatch on rtekind here so that the same + * function RTE can be absorbed into joins on multiple foreign servers + * (each call gets its own stub fpinfo and rechecks shippability for the + * specific server). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && + (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && + fpinfo_o->pushdown_safe && + function_rte_pushdown_ok(root, innerrel, outerrel)) + { + inner_is_function = true; + } + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) + { + outer_is_function = true; + } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } + + /* + * If one side is a function RTE, allocate a stub fpinfo so the rest of + * this function and the cost estimator can treat it uniformly. We hand + * the stub to the joinrel's deparser via the same path the foreign side + * uses, but we never permanently attach it to the function rel's + * fdw_private (different joinrels may pair the same function RTE with + * different foreign servers). + */ + if (inner_is_function) + { + fpinfo_i = palloc0_object(PgFdwRelationInfo); + fpinfo_i->pushdown_safe = true; + fpinfo_i->server = fpinfo_o->server; + fpinfo_i->shippable_extensions = fpinfo_o->shippable_extensions; + fpinfo_i->relation_name = psprintf("%u", innerrel->relid); + fpinfo_i->rows = innerrel->rows; + fpinfo_i->width = innerrel->reltarget->width; + fpinfo_i->retrieved_rows = innerrel->rows; + fpinfo_i->rel_startup_cost = 0; + fpinfo_i->rel_total_cost = 0; + + /* + * Classify the function rel's own baserestrictinfo now, so that the + * local_conds check below can bail out if any of it is unshippable. + * We classify against the stub, not the joinrel's fpinfo, because the + * latter's server/shippable_extensions aren't populated until + * merge_fdw_options() runs further down. + */ + classifyConditions(root, innerrel, fpinfo_i, innerrel->baserestrictinfo, + &fpinfo_i->remote_conds, &fpinfo_i->local_conds); + fpinfo->inner_func_fpinfo = fpinfo_i; + } + else if (outer_is_function) + { + fpinfo_o = palloc0_object(PgFdwRelationInfo); + fpinfo_o->pushdown_safe = true; + fpinfo_o->server = fpinfo_i->server; + fpinfo_o->shippable_extensions = fpinfo_i->shippable_extensions; + fpinfo_o->relation_name = psprintf("%u", outerrel->relid); + fpinfo_o->rows = outerrel->rows; + fpinfo_o->width = outerrel->reltarget->width; + fpinfo_o->retrieved_rows = outerrel->rows; + fpinfo_o->rel_startup_cost = 0; + fpinfo_o->rel_total_cost = 0; + + /* See the comment in the inner_is_function branch above. */ + classifyConditions(root, outerrel, fpinfo_o, outerrel->baserestrictinfo, + &fpinfo_o->remote_conds, &fpinfo_o->local_conds); + fpinfo->outer_func_fpinfo = fpinfo_o; + } /* * If joining relations have local conditions, those conditions are @@ -6718,7 +7161,7 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, foreach(lc, extra->restrictlist) { RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc); - bool is_remote_clause = is_foreign_expr(root, joinrel, + bool is_remote_clause = is_foreign_expr(root, joinrel, fpinfo, rinfo->clause); if (IS_OUTER_JOIN(jointype) && @@ -7416,7 +7859,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * If any GROUP BY expression is not shippable, then we cannot * push down aggregation to the foreign server. */ - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; /* @@ -7444,7 +7887,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * Non-grouping expression we need to compute. Can we ship it * as-is to the foreign server? */ - if (is_foreign_expr(root, grouped_rel, expr) && + if (is_foreign_expr(root, grouped_rel, fpinfo, expr) && !is_foreign_param(root, grouped_rel, expr)) { /* Yes, so add to tlist as-is; OK to suppress duplicates */ @@ -7464,7 +7907,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * don't have to check is_foreign_param, since that certainly * won't return true for any such expression.) */ - if (!is_foreign_expr(root, grouped_rel, (Expr *) aggvars)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, (Expr *) aggvars)) return false; /* @@ -7516,7 +7959,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, grouped_rel->relids, NULL, NULL); - if (is_foreign_expr(root, grouped_rel, expr)) + if (is_foreign_expr(root, grouped_rel, fpinfo, expr)) fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo); else fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo); @@ -7553,7 +7996,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, */ if (IsA(expr, Aggref)) { - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; tlist = add_to_flat_tlist(tlist, list_make1(expr)); @@ -8066,8 +8509,8 @@ add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel, * Also, the LIMIT/OFFSET cannot be pushed down, if their expressions are * not safe to remote. */ - if (!is_foreign_expr(root, input_rel, (Expr *) parse->limitOffset) || - !is_foreign_expr(root, input_rel, (Expr *) parse->limitCount)) + if (!is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitOffset) || + !is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitCount)) return; /* Safe to push down */ @@ -8713,7 +9156,7 @@ find_em_for_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel) if (bms_is_subset(em->em_relids, rel->relids) && !bms_is_empty(em->em_relids) && bms_is_empty(bms_intersect(em->em_relids, fpinfo->hidden_subquery_rels)) && - is_foreign_expr(root, rel, em->em_expr)) + is_foreign_expr(root, rel, fpinfo, em->em_expr)) return em; } @@ -8735,6 +9178,7 @@ EquivalenceMember * find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel) { + PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private; PathTarget *target = rel->reltarget; ListCell *lc1; int i; @@ -8784,7 +9228,7 @@ find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, continue; /* Check that expression (including relabels!) is shippable */ - if (is_foreign_expr(root, rel, em->em_expr)) + if (is_foreign_expr(root, rel, fpinfo, em->em_expr)) return em; } diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..da7da1c2ea9 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -106,6 +106,16 @@ typedef struct PgFdwRelationInfo /* joinclauses contains only JOIN/ON conditions for an outer join */ List *joinclauses; /* List of RestrictInfo */ + /* + * If a FUNCTION RTE was absorbed into this join, these point at the stub + * PgFdwRelationInfo for the function side (paired with the + * outerrel/innerrel), so the cost estimator and deparser can find it + * without consulting the function rel's fdw_private. At most one of + * outer_func_fpinfo/inner_func_fpinfo is set. + */ + struct PgFdwRelationInfo *outer_func_fpinfo; + struct PgFdwRelationInfo *inner_func_fpinfo; + /* Upper relation information */ UpperRelationKind stage; @@ -183,11 +193,13 @@ extern char *pgfdw_application_name; /* in deparse.c */ extern void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds); extern bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr); extern bool is_foreign_param(PlannerInfo *root, RelOptInfo *baserel, diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 8162c5496bf..3cbf8339602 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -790,6 +790,271 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); + +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + +DROP FUNCTION f_local(int); + +-- Check that a qual on the function RTE using a function from a shippable +-- extension is pushed down. plpgsql (not inlined) with the column as +-- argument (not const-folded) keeps the function call in the qual. +CREATE FUNCTION f_ext(int) RETURNS int AS $$ +BEGIN RETURN $1; END +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ext(int); +-- Force pushdown so the fixed-code plan is deterministically a Foreign +-- Scan; on the unfixed code the qual is classified local, the join is +-- refused, and the plan falls back to a local join instead. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and f_ext(n) > 3; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and f_ext(n) > 3 ORDER BY r.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ext(int); +DROP FUNCTION f_ext(int); + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; +DROP FUNCTION f_ret_record(); + +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + +-- Same nullable-side whole-row Var, but with outer rows that both match +-- and miss the (foreign x function) inner join. A multi-column function +-- RTE is used so that the reference is a genuine whole-row Var (a single +-- scalar-returning function would collapse to its lone column). This +-- exercises the THEN ROW(...) side of deparseColumnRef()'s whole-row CASE +-- (matched rows reconstruct the composite) as well as the NULL side +-- (missed rows), confirming the executor rebuilds the anonymous composite +-- correctly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; + +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); + +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); + +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 687e923c46c..4e70686ad07 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -746,6 +746,30 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if (OidIsValid(outer_rel->serverid) && + inner_rel->rtekind == RTE_FUNCTION) + { + /* + * One side is a foreign relation, the other side is a function RTE. + * If the function is IMMUTABLE, the FDW can absorb the function call + * into the remote query (the result is identical regardless of which + * server evaluates it). Let the FDW decide whether the join is + * actually shippable; here we just propagate the FDW routine so the + * FDW gets a chance. + */ + joinrel->serverid = outer_rel->serverid; + joinrel->userid = outer_rel->userid; + joinrel->useridiscurrent = outer_rel->useridiscurrent; + joinrel->fdwroutine = outer_rel->fdwroutine; + } + else if (OidIsValid(inner_rel->serverid) && + outer_rel->rtekind == RTE_FUNCTION) + { + joinrel->serverid = inner_rel->serverid; + joinrel->userid = inner_rel->userid; + joinrel->useridiscurrent = inner_rel->useridiscurrent; + joinrel->fdwroutine = inner_rel->fdwroutine; + } } /* -- 2.39.5 (Apple Git-154)
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
@ 2026-07-07 10:25                         ` Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2026-07-07 10:25 UTC (permalink / raw)
  To: Alexander Korotkov <aekorotkov@gmail.com>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Alexander Korotkov писал(а) 2026-07-06 17:11:
> Hi, Alexander!
> 
> On Wed, May 20, 2026 at 1:17 PM Alexander Pyhalov
> <a.pyhalov@postgrespro.ru> wrote:
>> I've found another issue. The fact that in the new versions of the 
>> patch
>> RTE RelOptInfo misses fdw_private seems to be unfortunate. For 
>> example,
>> in the last version we haven't thought about classifying
>> baserestrictinfo. And if we do, we should pass fdw_private down to
>> foreign_expr_walker. Perhaps, we could attach it to RTE_FUNCTION rel
>> prior to calling classifyConditions(), but should we later set it back
>> to NULL? Another problem comes if we try to handle joins,  which can
>> crearte subqueries (like INNER/OUTER UNIQUE). In this case we should
>> somehow cook fpinfo for get_relation_column_alias_ids(). Attaching 
>> patch
>> which tries to handle baserestrictinfos by passing fpinfo down to
>> foreign_expr_walker().
> 
> I think passing fpinfo down to foreign_expr_walker() is the right
> approach, thank you.  Attaching it to RTE_FUNCTION rel, and reseting
> it back to NULL would create excessive state and potential source of
> bugs.  The only advantage is saving existing function signatures, but
> it doesn't worth it.
> 
> Also, I don't think we need to care bout
> get_relation_column_alias_ids().  As we currently pushdown function
> only for inner joins, make_outerrel_subquery/make_innerrel_subquery
> are always false, lower_subquery_rels also wouldn't contain
> RTE_FUNCTION relid.
>  Therefore:
> 
>  * In deparseFromExprForRel() for functional rel deparseRangeTblRef()
> is always called with make_subquery=false.
>  * is_subquery_var() returns false.

Well, at least current patch version classifies conditions correctly.

> Other changes I made:
> 
> 1. In foreign_join_ok(), the function side's baserestrictinfo was
> classified against the joinrel fpinfo, whose
> server/shippable_extensions aren't set until merge_fdw_options() runs
> later — so extension-shippable quals would be misclassified as local
> and silently kill the pushdown. Now it: (a) copies
> shippable_extensions from the foreign side onto the stub, and (b)
> classifies against the stub (fpinfo_i/fpinfo_o, which already has
> server). Built-in quals like n > 3 were unaffected; this fixes the
> extension case.  I've added the test case for this.
> 
> 2. Dropped unused funcid. The per-RTE metadata was a 3-element list
> (funcid, funcrettype, funccollation) but funcid was never read.
> Reduced to list_make2(funcrettype, funccollation); updated the
> consumer (linitial/lsecond) and both descriptive comments.

With funcid we could print actual function name in explain.
Now we print, for example,

Relations: ((public.distr1_part_3 d1_3) INNER JOIN (public.distr2_part_3 
d2_3)) INNER JOIN (Function n)

If funcid is preserved, we could output actual function name instead of 
alias. This is more similar to
how we show relation names. Attaching updated patch, which preserves 
function names in explain.

After looking at it once more, I'm not convinced when we can get 
not-FuncExpr in rtfunc->funcexpr.
So added more checks to function_rte_pushdown_ok() to avoid dealing with 
such case.
-- 
Best regards,
Alexander Pyhalov,
Postgres Professional

Attachments:

v11-0001-postgres_fdw-push-down-FUNCTION-RTE-into-foreign.patch (text/x-diff, 82.5K) download From b850713b648ed985816c733552db40d613294005 Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Tue, 7 Jul 2026 09:57:19 +0300 Subject: [PATCH] postgres_fdw: push down FUNCTION RTE into foreign joins A foreign join planning hook now considers a (foreign-table x function-RTE) INNER join as a push-down candidate when the function expression is IMMUTABLE and otherwise shippable. The remote query absorbs the function call as a FROM-list item (e.g. unnest(...) AS f<rti>(c1, c2, ...)), so the foreign side returns only rows that match the function-produced set and the join executes entirely on the remote. An IMMUTABLE function gives the same result on any server, so the same function RTE can be a push-down candidate for several distinct foreign servers without semantic risk. To keep the planner state consistent across those independent attempts, the per-call stub fpinfo for the function side lives on the joinrel's PgFdwRelationInfo (new outer_func_fpinfo / inner_func_fpinfo), never on the function rel itself, and the function side is detected via rtekind rather than fdw_private. set_foreign_rel_properties() propagates fdwroutine onto a joinrel that pairs a foreign rel with an RTE_FUNCTION rel so GetForeignJoinPaths gets called; the FDW retains full control over whether to actually generate a path. deparseRangeTblRef and deparseColumnRef gain a FUNCTION-RTE branch that emits the function expression and resolves Vars to the generated --- contrib/postgres_fdw/deparse.c | 143 +++- .../postgres_fdw/expected/postgres_fdw.out | 631 ++++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 608 +++++++++++++++-- contrib/postgres_fdw/postgres_fdw.h | 12 + contrib/postgres_fdw/sql/postgres_fdw.sql | 265 ++++++++ src/backend/optimizer/util/relnode.c | 24 + 6 files changed, 1626 insertions(+), 57 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 2dcc6c8af1b..a2e9301fb65 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -68,6 +68,7 @@ typedef struct foreign_glob_cxt { PlannerInfo *root; /* global planner state */ RelOptInfo *foreignrel; /* the foreign relation we are planning for */ + PgFdwRelationInfo *fpinfo; /* the foreign server info we should rely on */ Relids relids; /* relids of base relations in the underlying * scan */ } foreign_glob_cxt; @@ -112,6 +113,7 @@ typedef struct deparse_expr_cxt appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno)) #define SUBQUERY_REL_ALIAS_PREFIX "s" #define SUBQUERY_COL_ALIAS_PREFIX "c" +#define FUNCTION_REL_ALIAS_PREFIX "f" /* * Functions to determine whether an expression can be evaluated safely on @@ -217,6 +219,7 @@ static void get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel, void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds) @@ -230,7 +233,7 @@ classifyConditions(PlannerInfo *root, { RestrictInfo *ri = lfirst_node(RestrictInfo, lc); - if (is_foreign_expr(root, baserel, ri->clause)) + if (is_foreign_expr(root, baserel, fpinfo, ri->clause)) *remote_conds = lappend(*remote_conds, ri); else *local_conds = lappend(*local_conds, ri); @@ -243,11 +246,11 @@ classifyConditions(PlannerInfo *root, bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr) { foreign_glob_cxt glob_cxt; foreign_loc_cxt loc_cxt; - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private); /* * Check that the expression consists of nodes that are safe to execute @@ -255,6 +258,7 @@ is_foreign_expr(PlannerInfo *root, */ glob_cxt.root = root; glob_cxt.foreignrel = baserel; + glob_cxt.fpinfo = fpinfo; /* * For an upper relation, use relids from its underneath scan relation, @@ -324,8 +328,8 @@ foreign_expr_walker(Node *node, if (node == NULL) return true; - /* May need server info from baserel's fdw_private struct */ - fpinfo = (PgFdwRelationInfo *) (glob_cxt->foreignrel->fdw_private); + /* May need server info from global context */ + fpinfo = glob_cxt->fpinfo; /* Set up inner_cxt for possible recursion to child nodes */ inner_cxt.collation = InvalidOid; @@ -2030,6 +2034,72 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, } } +/* + * Deparse a FUNCTION RTE absorbed into a foreign join. The function call(s) + * are emitted as a FROM-list item: + * + * <funcexpr> AS f<rti>(c1, c2, ..., cN) + * + * For multi-function RTEs (SQL ROWS FROM (f1(), f2(), ...)), each + * function call appears comma-separated inside ROWS FROM(...). Column + * aliases c1..cN cover the union of every function's columns, in the + * order they appear; that matches the column ordering of the RTE. + */ +static void +deparseFunctionRangeTblRef(StringInfo buf, PlannerInfo *root, + RelOptInfo *foreignrel, RelOptInfo *scanrel, + List **params_list) +{ + RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); + deparse_expr_cxt context; + ListCell *lc; + bool multi_func; + int total_cols = 0; + int i; + + Assert(rte->rtekind == RTE_FUNCTION); + Assert(!rte->funcordinality); + Assert(list_length(rte->functions) >= 1); + + multi_func = list_length(rte->functions) > 1; + + context.buf = buf; + context.root = root; + context.foreignrel = scanrel; + context.scanrel = scanrel; + context.params_list = params_list; + + if (multi_func) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (foreach_current_index(lc) > 0) + appendStringInfoString(buf, ", "); + deparseExpr((Expr *) rtfunc->funcexpr, &context); + total_cols += rtfunc->funccolcount; + } + + if (multi_func) + appendStringInfoChar(buf, ')'); + + /* Alias + generated column-name list. */ + appendStringInfo(buf, " %s%d", FUNCTION_REL_ALIAS_PREFIX, foreignrel->relid); + if (total_cols > 0) + { + appendStringInfoChar(buf, '('); + for (i = 1; i <= total_cols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + } +} + /* * Append FROM clause entry for the given relation into buf. * Conditions from lower-level SEMI-JOINs are appended to additional_conds @@ -2040,7 +2110,22 @@ deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **additional_conds, List **params_list) { - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + PgFdwRelationInfo *fpinfo; + + /* + * For a function RTE absorbed into a foreign join, deparse the function + * expression as a FROM-list item and return. The stub fpinfo set up by + * foreign_join_ok() may or may not be present here. + */ + if (foreignrel->rtekind == RTE_FUNCTION) + { + Assert(!make_subquery); + deparseFunctionRangeTblRef(buf, root, foreignrel, foreignrel, + params_list); + return; + } + + fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; /* Should only be called in these cases. */ Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel)); @@ -2712,6 +2797,54 @@ static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col) { + /* + * Function RTE columns: emit as f<varno>.c<varattno>, matching the + * aliases generated by deparseFunctionRangeTblRef(). A whole-row Var + * (varattno == 0) is rendered as ROW(f<varno>.c1, ..., f<varno>.c<N>) + * where N is the total column count of the function RTE (including all + * ROWS FROM (...) members). System attributes such as ctid have no + * meaning for function RTEs and are rejected. + */ + if (rte->rtekind == RTE_FUNCTION) + { + if (varattno == 0) + { + int ncols = list_length(rte->eref->colnames); + int i; + + if (qualify_col) + { + appendStringInfoString(buf, "CASE WHEN ("); + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfoString(buf, "*)::text IS NOT NULL THEN "); + } + + appendStringInfoString(buf, "ROW("); + for (i = 1; i <= ncols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d.%s%d", + FUNCTION_REL_ALIAS_PREFIX, varno, + SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + + if (qualify_col) + appendStringInfoString(buf, " END"); + return; + } + + if (varattno < 0) + elog(ERROR, + "system attribute reference to a function RTE is not supported in foreign join pushdown"); + + if (qualify_col) + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, varattno); + return; + } + /* We support fetching the remote side's CTID and OID. */ if (varattno == SelfItemPointerAttributeNumber) { diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index aaffcf31271..e3355aa8a86 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2885,6 +2885,637 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c (10 rows) ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: t1.c1, t1.c3 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1, t1.c3 + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r1."C 1", r1.c3 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{1,5,10,100}'::integer[]) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + c1 | c3 +-----+------- + 1 | 00001 + 5 | 00005 + 10 | 00010 + 100 | 00100 +(4 rows) + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Sort + Output: t1.c1 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1 + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.generate_series() g) + Remote SQL: SELECT r1."C 1" FROM ("S 1"."T 1" r1 INNER JOIN generate_series(1, 4) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + c1 +---- + 1 + 2 + 3 + 4 +(4 rows) + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on pg_catalog.generate_series g + Output: g.id + Function Call: generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + QUERY PLAN +------------------------------------------------------------ + Hash Join + Output: t1.c1, u.ord + Hash Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" + -> Hash + Output: u.ord, u.id + -> Function Scan on pg_catalog.unnest u + Output: u.ord, u.id + Function Call: unnest('{1,5,10}'::integer[]) +(11 rows) + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: t1.c1, t2.c1 + Merge Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST + -> Sort + Output: t2.c1, u.id + Sort Key: t2.c1 + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{1,5,10,100}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(13 rows) + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: t1.c1, t2.c1 + Hash Cond: (t1.c1 = t2.c1) + -> Foreign Scan + Output: t1.c1, u.id + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r1."C 1", f3.c1 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r1."C 1" = f3.c1)))) + -> Hash + Output: t2.c1 + -> Foreign Scan on public.ft6 t2 + Output: t2.c1 + Remote SQL: SELECT c1 FROM "S 1"."T 4" +(12 rows) + +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: t1.c1, t2.c1 + Join Filter: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE ((c3 < '00010')) + -> Materialize + Output: t2.c1, u.id + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(12 rows) + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + n | a | b +---+---+----- + 2 | 2 | 102 + 3 | 3 | 103 + 4 | 4 | 104 +(3 rows) + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)) AND ((f1.c1 > 3)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); + QUERY PLAN +----------------------------------------------------------- + Hash Join + Output: n.n, r.a, r.b + Hash Cond: (r.a = n.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a, b FROM public.base_tbl_fn + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4}'::integer[]) + Filter: (n.n > f_local(3)) +(12 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +DROP FUNCTION f_local(int); +-- Check that a qual on the function RTE using a function from a shippable +-- extension is pushed down. plpgsql (not inlined) with the column as +-- argument (not const-folded) keeps the function call in the qual. +CREATE FUNCTION f_ext(int) RETURNS int AS $$ +BEGIN RETURN $1; END +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ext(int); +-- Force pushdown so the fixed-code plan is deterministically a Foreign +-- Scan; on the unfixed code the qual is classified local, the join is +-- refused, and the plan falls back to a local join instead. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and f_ext(n) > 3; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)) AND ((public.f_ext(f1.c1) > 3)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and f_ext(n) > 3 ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ext(int); +DROP FUNCTION f_ext(int); +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: s.* + Hash Cond: (rt.a = s.a) + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl_fn + -> Hash + Output: s.*, s.a + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() +(11 rows) + +DROP FUNCTION f_ret_record(); +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + a | b +----+----- + 23 | 123 + 24 | 999 + 25 | 125 +(3 rows) + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + a | b +----+--- + 24 | 5 +(1 row) + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + a | b | t +----+---+--------------------- + 24 | 7 | ("(2,3),(-2,-3)",1) +(1 row) + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: r.a, t.n, t.s + Sort Key: r.a + -> Foreign Scan + Output: r.a, t.n, t.s + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.generate_series()) t) + Remote SQL: SELECT r1.a, f2.c1, f2.c2 FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + a | n | s +---+---+---- + 3 | 3 | 11 + 6 | 6 | 12 + 9 | 9 | 13 +(3 rows) + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: ((t.*)::text), r.a + Sort Key: r.a + -> Foreign Scan + Output: (t.*)::text, r.a + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.generate_series()) t) + Remote SQL: SELECT CASE WHEN (f2.*)::text IS NOT NULL THEN ROW(f2.c1, f2.c2) END, r1.a FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + t | a +--------+--- + (3,11) | 3 + (6,12) | 6 + (9,13) | 9 +(3 rows) + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: u.*, ft5.c1, ft5.c2, ft4.c1, ft4.c2 + Relations: (public.ft5) LEFT JOIN ((public.ft4) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.unnest()) u)) + Remote SQL: SELECT CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END, r1.c1, r1.c2, r2.c1, r2.c2 FROM ("S 1"."T 4" r1 LEFT JOIN ("S 1"."T 3" r2 INNER JOIN ROWS FROM (unnest('{1,2}'::integer[]), unnest('{3,4}'::integer[])) f3(c1, c2) ON (((r2.c1 = f3.c1)))) ON (((r1.c1 = r2.c1)))) WHERE ((r1.c1 < 10)) ORDER BY r1.c1 ASC NULLS LAST +(4 rows) + +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + u | c1 | c2 | c1 | c2 +---+----+----+----+---- + | 3 | 4 | | + | 6 | 7 | | + | 9 | 10 | | +(3 rows) + +-- Same nullable-side whole-row Var, but with outer rows that both match +-- and miss the (foreign x function) inner join. A multi-column function +-- RTE is used so that the reference is a genuine whole-row Var (a single +-- scalar-returning function would collapse to its lone column). This +-- exercises the THEN ROW(...) side of deparseColumnRef()'s whole-row CASE +-- (matched rows reconstruct the composite) as well as the NULL side +-- (missed rows), confirming the executor rebuilds the anonymous composite +-- correctly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: l.a, t.* + Relations: (public.remote_tbl l) LEFT JOIN ((public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.unnest()) t)) + Remote SQL: SELECT r1.a, CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END FROM (public.base_tbl_fn r1 LEFT JOIN (public.base_tbl_fn r2 INNER JOIN ROWS FROM (unnest('{2,4}'::integer[]), unnest('{20,40}'::integer[])) f3(c1, c2) ON (((r2.a = f3.c1)))) ON (((r1.a = r2.a)))) WHERE ((r1.a < 6)) ORDER BY r1.a ASC NULLS LAST +(4 rows) + +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; + a | t +---+-------- + 1 | + 2 | (2,20) + 3 | + 4 | (4,40) + 5 | +(5 rows) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: s.a, s.b + Sort Key: s.a + CTE s + -> Nested Loop + Output: r1.a, r1.b + -> Foreign Scan on public.remote_tbl r1 + Output: r1.a, r1.b + Remote SQL: SELECT a, b FROM public.base_tbl_fn + -> Foreign Scan + Output: NULL::integer + Relations: (public.remote_tbl r2) INNER JOIN (public.f()) + Remote SQL: SELECT NULL FROM (public.base_tbl_fn r1 INNER JOIN public.f($1::integer) f2(c1) ON (TRUE)) LIMIT 1::bigint + -> CTE Scan on s + Output: s.a, s.b +(15 rows) + +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + a | b +----+----- + 1 | 101 + 2 | 102 + 3 | 103 + 4 | 104 + 5 | 105 + 6 | 106 + 7 | 107 + 8 | 108 + 9 | 109 + 10 | 110 + 11 | 111 + 12 | 112 + 13 | 113 + 14 | 114 + 15 | 115 + 16 | 116 + 17 | 117 + 18 | 118 + 19 | 119 + 20 | 120 + 21 | 121 + 22 | 122 + 23 | 123 + 24 | 7 + 25 | 125 + 26 | 126 + 27 | 127 + 28 | 128 + 29 | 129 + 30 | 130 +(30 rows) + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: r.a + Merge Cond: (t.n = r.a) + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]), generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Sort + Output: r.a + Sort Key: r.a + -> Foreign Scan on public.remote_tbl r + Output: r.a + Remote SQL: SELECT a FROM public.base_tbl_fn +(15 rows) + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Nested Loop + Output: r.a, t.x + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 3)) ORDER BY a ASC NULLS LAST + -> Function Scan on pg_catalog.unnest t + Output: t.x + Function Call: unnest(ARRAY[r.a]) +(8 rows) + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Merge Left Join + Output: r.a, t.n + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 5)) ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{1,2,3}'::integer[]) +(12 rows) + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + QUERY PLAN +-------------------------------------------------------------------------------- + Merge Semi Join + Output: r.a + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]) +(12 rows) + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 0ff4ec23164..59af46f6942 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -31,6 +31,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/appendinfo.h" +#include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" #include "optimizer/optimizer.h" @@ -88,6 +89,22 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of per-RTE function metadata, indexed by base RTI offset. Each + * element is either NULL (for non-RTE_FUNCTION rels in this scan) or a + * list of three-element lists (funcid, funcrettype, funccollation) -- one + * inner list per function in the RTE. Allows the executor to rebuild + * TupleDesc entries for whole-row references to function RTEs. + */ + FdwScanPrivateFunctions, + + /* + * Integer node: minimum base RT index covered by the scan, used to + * translate scan-local indexes to estate-rtable indexes after setrefs.c + * flattens rtables. + */ + FdwScanPrivateMinRTIndex, }; /* @@ -124,6 +141,11 @@ enum FdwModifyPrivateIndex * 2) Boolean flag showing if the remote query has a RETURNING clause * 3) Integer list of attribute numbers retrieved by RETURNING, if any * 4) Boolean flag showing if we set the command es_processed + * 5) Per-RTE function metadata (mirrors FdwScanPrivateFunctions; lets + * the executor rebuild TupleDesc entries for whole-row Vars over + * function RTEs absorbed into a foreign join) + * 6) Integer node: minimum base RT index of the scan (mirrors + * FdwScanPrivateMinRTIndex) */ enum FdwDirectModifyPrivateIndex { @@ -135,6 +157,10 @@ enum FdwDirectModifyPrivateIndex FdwDirectModifyPrivateRetrievedAttrs, /* set-processed flag (as a Boolean node) */ FdwDirectModifyPrivateSetProcessed, + /* Per-RTE function metadata, indexed by base RTI offset */ + FdwDirectModifyPrivateFunctions, + /* Integer node: minimum base RT index in the scan */ + FdwDirectModifyPrivateMinRTIndex, }; /* @@ -740,6 +766,9 @@ static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, static List *get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel); static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, Path *epq_path, List *restrictlist); static void add_foreign_grouping_paths(PlannerInfo *root, @@ -893,7 +922,7 @@ postgresGetForeignRelSize(PlannerInfo *root, * Identify which baserestrictinfo clauses can be sent to the remote * server and which can't. */ - classifyConditions(root, baserel, baserel->baserestrictinfo, + classifyConditions(root, baserel, fpinfo, baserel->baserestrictinfo, &fpinfo->remote_conds, &fpinfo->local_conds); /* @@ -1297,7 +1326,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1373,7 +1402,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1513,7 +1542,7 @@ postgresGetForeignPlan(PlannerInfo *root, remote_exprs = lappend(remote_exprs, rinfo->clause); else if (list_member_ptr(fpinfo->local_conds, rinfo)) local_exprs = lappend(local_exprs, rinfo->clause); - else if (is_foreign_expr(root, foreignrel, rinfo->clause)) + else if (is_foreign_expr(root, foreignrel, fpinfo, rinfo->clause)) remote_exprs = lappend(remote_exprs, rinfo->clause); else local_exprs = lappend(local_exprs, rinfo->clause); @@ -1634,9 +1663,26 @@ postgresGetForeignPlan(PlannerInfo *root, fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(fpinfo->fetch_size)); + + /* + * Position FdwScanPrivateRelations: either the EXPLAIN relation string + * (joins/upper rels) or a NULL placeholder, so that subsequent indexes + * stay valid for the base-rel scan case. + */ if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + /* + * FdwScanPrivateFunctions / FdwScanPrivateMinRTIndex carry the metadata + * the executor needs to rebuild TupleDesc entries for whole-row Vars + * pointing at RTE_FUNCTION rels absorbed into the foreign scan. + */ + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + fdw_private = lappend(fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1657,9 +1703,15 @@ postgresGetForeignPlan(PlannerInfo *root, /* * Construct a tuple descriptor for the scan tuples handled by a foreign join. + * + * 'rtfuncdata' is the FdwScanPrivateFunctions list saved at plan time, and + * 'rtoffset' is the difference between the executor's RT indexes and the + * scan-local RT indexes captured in that list. Both may be 0/NIL when the + * scan has no RTE_FUNCTION dependents. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, + List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1695,13 +1747,67 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * A whole-row Var points at a FUNCTION RTE absorbed into the + * foreign join. Synthesize an anonymous composite TupleDesc from + * the per-function return-type metadata we saved at plan time; + * the deparser emits these as ROW(f<rti>.c1, f<rti>.c2, ...). + * + * For an upperrel scan (the only path that reaches here) + * postgresGetForeignPlan always builds rtfuncdata via + * get_functions_data(), so it is never NIL; the per-RTE slot for + * the function RTE referenced by this Var must likewise be + * populated. + */ + List *funcdata; + TupleDesc rte_tupdesc; + int num_funcs; + int attnum; + ListCell *lc1, + *lc2; + + Assert(rtfuncdata != NIL); + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + Assert(funcdata != NIL); + num_funcs = list_length(funcdata); + Assert(num_funcs == list_length(rte->eref->colnames)); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc1, funcdata, lc2, rte->eref->colnames) + { + List *fdata = lfirst_node(List, lc1); + char *colname = strVal(lfirst(lc2)); + Oid funcrettype; + Oid funccollation; + + funcrettype = lsecond_node(Integer, fdata)->ival; + funccollation = lthird_node(Integer, fdata)->ival; + + /* get_functions_data() already validated the return type. */ + Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funccollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1737,14 +1843,30 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. For a join, scan the base relids until we + * find an RTE_RELATION (the foreign-table side); ignore any RTE_FUNCTION + * absorbed into the join, which contributes no relation OID to look up. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); + rte = NULL; if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte != NULL && rte->rtekind == RTE_RELATION) + break; + rte = NULL; + } + if (rte == NULL) + elog(ERROR, "could not locate a foreign relation RTE in foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1787,8 +1909,19 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwScanPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwScanPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, + rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2741,7 +2874,7 @@ postgresPlanDirectModify(PlannerInfo *root, if (attno <= InvalidAttrNumber) /* shouldn't happen */ elog(ERROR, "system-column update is not supported"); - if (!is_foreign_expr(root, foreignrel, (Expr *) tle->expr)) + if (!is_foreign_expr(root, foreignrel, fpinfo, (Expr *) tle->expr)) return false; } } @@ -2828,6 +2961,10 @@ postgresPlanDirectModify(PlannerInfo *root, makeBoolean((retrieved_attrs != NIL)), retrieved_attrs, makeBoolean(plan->canSetTag)); + fscan->fdw_private = lappend(fscan->fdw_private, + get_functions_data(root, foreignrel)); + fscan->fdw_private = lappend(fscan->fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Update the foreign-join-related fields. @@ -2941,7 +3078,26 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + /* + * DirectModify on a foreign join: use the per-RTE function + * metadata saved at plan time so a whole-row Var pointing at a + * function RTE absorbed into the join can be rebuilt into a + * usable TupleDesc (e.g. RETURNING t for a join with UNNEST(..., + * ...) AS t(bx, i)). + */ + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + + tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -3054,7 +3210,8 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_length(fdw_private) > FdwScanPrivateRelations && + list_nth(fdw_private, FdwScanPrivateRelations) != NULL) { StringInfoData relations; char *rawrelations; @@ -3104,25 +3261,90 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); - Assert(rte->rtekind == RTE_RELATION); - /* This logic should agree with explain.c's ExplainTargetRel */ - relname = get_rel_name(rte->relid); - if (es->verbose) - { - char *namespace; - namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); - appendStringInfo(&relations, "%s.%s", - quote_identifier(namespace), - quote_identifier(relname)); + if (rte->rtekind == RTE_FUNCTION) + { + List *rtfuncdata = list_nth(fdw_private, FdwScanPrivateFunctions); + List *funcdata; + bool multi_func; + bool first = true; + ListCell *lc; + + funcdata = list_nth(rtfuncdata, rti - rtoffset); + + multi_func = list_length(funcdata) > 1; + + if (multi_func) + appendStringInfoString(&relations, "ROWS FROM ("); + + foreach(lc, funcdata) + { + List *funcinfo; + Oid funcid; + + + if (!first) + appendStringInfoString(&relations, ", "); + + funcinfo = (List *) lfirst(lc); + + funcid = linitial_node(Integer, funcinfo)->ival; + /* Checked by function_rte_pushdown_ok() */ + Assert(OidIsValid(funcid)); + + /* Match RTE_RELATION behavior */ + relname = get_func_name(funcid); + if (relname == NULL) + elog(ERROR, "cache lookup failed for function %u", funcid); + if (es->verbose) + { + char *namespace; + Oid nsoid = get_func_namespace(funcid); + + namespace = get_namespace_name(nsoid); + if (namespace == NULL) + elog(ERROR, "cache lookup failed for namespace %u", nsoid); + + appendStringInfo(&relations, "%s.%s()", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfo(&relations, "%s()", quote_identifier(relname)); + + first = false; + } + /* Close ROWS FROM */ + if (multi_func) + appendStringInfoChar(&relations, ')'); } else - appendStringInfoString(&relations, - quote_identifier(relname)); + { + Assert(rte->rtekind == RTE_RELATION); + + /* + * This logic should agree with explain.c's + * ExplainTargetRel + */ + relname = get_rel_name(rte->relid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); + appendStringInfo(&relations, "%s.%s", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfoString(&relations, + quote_identifier(relname)); + } + refname = (char *) list_nth(es->rtable_names, rti - 1); if (refname == NULL) refname = rte->eref->aliasname; - if (strcmp(refname, relname) != 0) + if (relname == NULL || strcmp(refname, relname) != 0) appendStringInfo(&relations, " %s", quote_identifier(refname)); } @@ -3346,7 +3568,7 @@ estimate_path_cost_size(PlannerInfo *root, * param_join_conds might contain both clauses that are safe to send * across, and clauses that aren't. */ - classifyConditions(root, foreignrel, param_join_conds, + classifyConditions(root, foreignrel, fpinfo, param_join_conds, &remote_param_join_conds, &local_param_join_conds); /* Build the list of columns to be fetched from the foreign server. */ @@ -3479,8 +3701,17 @@ estimate_path_cost_size(PlannerInfo *root, /* For join we expect inner and outer relations set */ Assert(fpinfo->innerrel && fpinfo->outerrel); - fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; + /* + * For a FUNCTION RTE absorbed into the join, use the stub fpinfo + * we built in foreign_join_ok(), since the function rel itself + * has no fdw_private. + */ + fpinfo_i = fpinfo->inner_func_fpinfo ? + fpinfo->inner_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; + fpinfo_o = fpinfo->outer_func_fpinfo ? + fpinfo->outer_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; /* Estimate of number of rows in cross product */ nrows = fpinfo_i->rows * fpinfo_o->rows; @@ -6619,6 +6850,205 @@ semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, return ok; } +/* + * get_base_relids + * Return the set of base relids referenced by a foreign scan rel. + * + * For an upper rel we use the all-query relids minus the outer joins; + * otherwise the rel's own relids minus the outer joins. The result matches + * the relids that create_foreignscan_plan() ultimately uses for + * ForeignScan.fs_base_relids, so it is suitable for any tagging we want to + * store via plan-private state. + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + return bms_difference(relids, root->outer_join_rels); +} + +/* + * get_min_base_rti + * Lowest base RT index in the foreign scan rel. + * + * After setrefs.c flattens the rtable, the scan-local indexes saved in + * plan-private data can be translated to estate indexes by adding + * (ForeignScan.fs_base_relids min - this value). Captured at plan time + * because create_foreignscan_plan() computes the same value internally. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + +/* + * get_functions_data + * Build the per-RTE function metadata list saved as + * FdwScanPrivateFunctions. + * + * The result list is indexed by base RT index relative to the lowest base + * RT index of the scan. Each element is either NULL (for non-RTE_FUNCTION + * base rels in this scan) or a List of List of two Integer nodes: + * (funcrettype, funccollation) -- one inner list per RangeTblFunction. + * + * Only RTE_FUNCTION relids actually appearing in the foreign scan's + * fs_base_relids contribute; others are placeholders so that the consumer + * can index into the result by RTI offset. + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + Relids fscan_relids = get_base_relids(root, rel); + int i; + + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + List *funcdata = NIL; + ListCell *lc; + + if (rte == NULL || i == 0 || + !bms_is_member(i, fscan_relids) || + rte->rtekind != RTE_FUNCTION) + { + rtfuncdata = lappend(rtfuncdata, NULL); + continue; + } + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + Oid funcrettype; + Oid funccollation; + TupleDesc tupdesc; + Oid funcid; + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + /* + * function_rte_pushdown_ok() already rejected any function that + * doesn't return a well-defined scalar type, so this is a mere + * cross-check. + */ + Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID); + + funccollation = exprCollation(rtfunc->funcexpr); + + funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid; + + funcdata = lappend(funcdata, + list_make3(makeInteger(funcid), + makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + + return rtfuncdata; +} + +/* + * Check if a relation is a FUNCTION RTE that can be absorbed into a remote + * join. Every function in the RTE must + * + * - return a well-defined scalar type -- we don't ship records/composite + * since the remote server cannot reconstruct a column definition list + * and our deparser does not emit one; + * - have a shippable expression with no mutable subnodes -- is_foreign_expr() + * rejects volatile/stable functions through contain_mutable_functions(), + * so the IMMUTABLE-only restriction is implicit; + * - not contain SubPlans -- we'd otherwise need to ship sub-results to + * the remote, which we do not implement. + * + * WITH ORDINALITY is not supported yet. + */ +static bool +function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel, + RelOptInfo *fdwrel) +{ + RangeTblEntry *rte; + ListCell *lc; + + if (rel->rtekind != RTE_FUNCTION) + return false; + rte = planner_rt_fetch(rel->relid, root); + + /* + * build_simple_rel() copies rtekind straight from the RTE, so for a base + * rel rel->rtekind always matches the RTE's; the check above is therefore + * sufficient. + */ + Assert(rte->rtekind == RTE_FUNCTION); + + if (rte->funcordinality) + return false; + + /* + * Reject up-front any function RTE that lateral-references another + * relation: foreign-join push-down would need to parameterise the remote + * query per outer row, which we don't support, and even considering the + * path is expensive on the planner side. The surrounding lateral_relids + * check in postgresGetForeignJoinPaths() would normally bail out for the + * joinrel, but doing the check here avoids walking the function + * expression entirely. + * + * Note this rejects only lateral references to another relation at the + * same query level. A function argument referencing an outer query level + * (e.g. f(outer.col) inside a subquery) is a different case: it becomes a + * PARAM_EXEC Param, the function rel's lateral_relids is empty, and + * foreign_expr_walker() intentionally treats PARAM_EXEC as shippable. The + * remote query then carries a parameter placeholder, and postgres_fdw's + * ordinary parameter machinery re-sends it on each rescan -- i.e. it + * works as a normal parameterized foreign scan, which is fine. + */ + if (!bms_is_empty(rel->lateral_relids)) + return false; + + Assert(list_length(rte->functions) >= 1); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + TypeFuncClass functypclass; + Oid funcrettype; + TupleDesc tupdesc; + + /* Refuse to deal with strange funcexprs */ + if (!IsA(rtfunc->funcexpr, FuncExpr)) + return false; + + if (!OidIsValid(((FuncExpr *) rtfunc->funcexpr)->funcid)) + return false; + + functypclass = get_expr_result_type(rtfunc->funcexpr, + &funcrettype, &tupdesc); + if (functypclass != TYPEFUNC_SCALAR) + return false; + if (!OidIsValid(funcrettype) || + funcrettype == RECORDOID || + funcrettype == VOIDOID) + return false; + + if (contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, fdwrel, fdwrel->fdw_private, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -6634,6 +7064,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; + bool outer_is_function = false; + bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -6652,15 +7084,86 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, return false; /* - * If either of the joining relations is marked as unsafe to pushdown, the - * join can not be pushed down. + * Detect mixed (foreign x function-RTE) cases. Only INNER joins are + * supported initially. We dispatch on rtekind here so that the same + * function RTE can be absorbed into joins on multiple foreign servers + * (each call gets its own stub fpinfo and rechecks shippability for the + * specific server). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && + (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && + fpinfo_o->pushdown_safe && + function_rte_pushdown_ok(root, innerrel, outerrel)) + { + inner_is_function = true; + } + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) + { + outer_is_function = true; + } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } + + /* + * If one side is a function RTE, allocate a stub fpinfo so the rest of + * this function and the cost estimator can treat it uniformly. We hand + * the stub to the joinrel's deparser via the same path the foreign side + * uses, but we never permanently attach it to the function rel's + * fdw_private (different joinrels may pair the same function RTE with + * different foreign servers). + */ + if (inner_is_function) + { + fpinfo_i = palloc0_object(PgFdwRelationInfo); + fpinfo_i->pushdown_safe = true; + fpinfo_i->server = fpinfo_o->server; + fpinfo_i->shippable_extensions = fpinfo_o->shippable_extensions; + fpinfo_i->relation_name = psprintf("%u", innerrel->relid); + fpinfo_i->rows = innerrel->rows; + fpinfo_i->width = innerrel->reltarget->width; + fpinfo_i->retrieved_rows = innerrel->rows; + fpinfo_i->rel_startup_cost = 0; + fpinfo_i->rel_total_cost = 0; + + /* + * Classify the function rel's own baserestrictinfo now, so that the + * local_conds check below can bail out if any of it is unshippable. + * We classify against the stub, not the joinrel's fpinfo, because the + * latter's server/shippable_extensions aren't populated until + * merge_fdw_options() runs further down. + */ + classifyConditions(root, innerrel, fpinfo_i, innerrel->baserestrictinfo, + &fpinfo_i->remote_conds, &fpinfo_i->local_conds); + fpinfo->inner_func_fpinfo = fpinfo_i; + } + else if (outer_is_function) + { + fpinfo_o = palloc0_object(PgFdwRelationInfo); + fpinfo_o->pushdown_safe = true; + fpinfo_o->server = fpinfo_i->server; + fpinfo_o->shippable_extensions = fpinfo_i->shippable_extensions; + fpinfo_o->relation_name = psprintf("%u", outerrel->relid); + fpinfo_o->rows = outerrel->rows; + fpinfo_o->width = outerrel->reltarget->width; + fpinfo_o->retrieved_rows = outerrel->rows; + fpinfo_o->rel_startup_cost = 0; + fpinfo_o->rel_total_cost = 0; + + /* See the comment in the inner_is_function branch above. */ + classifyConditions(root, outerrel, fpinfo_o, outerrel->baserestrictinfo, + &fpinfo_o->remote_conds, &fpinfo_o->local_conds); + fpinfo->outer_func_fpinfo = fpinfo_o; + } /* * If joining relations have local conditions, those conditions are @@ -6698,7 +7201,7 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, foreach(lc, extra->restrictlist) { RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc); - bool is_remote_clause = is_foreign_expr(root, joinrel, + bool is_remote_clause = is_foreign_expr(root, joinrel, fpinfo, rinfo->clause); if (IS_OUTER_JOIN(jointype) && @@ -7396,7 +7899,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * If any GROUP BY expression is not shippable, then we cannot * push down aggregation to the foreign server. */ - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; /* @@ -7424,7 +7927,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * Non-grouping expression we need to compute. Can we ship it * as-is to the foreign server? */ - if (is_foreign_expr(root, grouped_rel, expr) && + if (is_foreign_expr(root, grouped_rel, fpinfo, expr) && !is_foreign_param(root, grouped_rel, expr)) { /* Yes, so add to tlist as-is; OK to suppress duplicates */ @@ -7444,7 +7947,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * don't have to check is_foreign_param, since that certainly * won't return true for any such expression.) */ - if (!is_foreign_expr(root, grouped_rel, (Expr *) aggvars)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, (Expr *) aggvars)) return false; /* @@ -7496,7 +7999,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, grouped_rel->relids, NULL, NULL); - if (is_foreign_expr(root, grouped_rel, expr)) + if (is_foreign_expr(root, grouped_rel, fpinfo, expr)) fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo); else fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo); @@ -7533,7 +8036,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, */ if (IsA(expr, Aggref)) { - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; tlist = add_to_flat_tlist(tlist, list_make1(expr)); @@ -8046,8 +8549,8 @@ add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel, * Also, the LIMIT/OFFSET cannot be pushed down, if their expressions are * not safe to remote. */ - if (!is_foreign_expr(root, input_rel, (Expr *) parse->limitOffset) || - !is_foreign_expr(root, input_rel, (Expr *) parse->limitCount)) + if (!is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitOffset) || + !is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitCount)) return; /* Safe to push down */ @@ -8693,7 +9196,7 @@ find_em_for_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel) if (bms_is_subset(em->em_relids, rel->relids) && !bms_is_empty(em->em_relids) && bms_is_empty(bms_intersect(em->em_relids, fpinfo->hidden_subquery_rels)) && - is_foreign_expr(root, rel, em->em_expr)) + is_foreign_expr(root, rel, fpinfo, em->em_expr)) return em; } @@ -8715,6 +9218,7 @@ EquivalenceMember * find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel) { + PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private; PathTarget *target = rel->reltarget; ListCell *lc1; int i; @@ -8764,7 +9268,7 @@ find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, continue; /* Check that expression (including relabels!) is shippable */ - if (is_foreign_expr(root, rel, em->em_expr)) + if (is_foreign_expr(root, rel, fpinfo, em->em_expr)) return em; } diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..da7da1c2ea9 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -106,6 +106,16 @@ typedef struct PgFdwRelationInfo /* joinclauses contains only JOIN/ON conditions for an outer join */ List *joinclauses; /* List of RestrictInfo */ + /* + * If a FUNCTION RTE was absorbed into this join, these point at the stub + * PgFdwRelationInfo for the function side (paired with the + * outerrel/innerrel), so the cost estimator and deparser can find it + * without consulting the function rel's fdw_private. At most one of + * outer_func_fpinfo/inner_func_fpinfo is set. + */ + struct PgFdwRelationInfo *outer_func_fpinfo; + struct PgFdwRelationInfo *inner_func_fpinfo; + /* Upper relation information */ UpperRelationKind stage; @@ -183,11 +193,13 @@ extern char *pgfdw_application_name; /* in deparse.c */ extern void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds); extern bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr); extern bool is_foreign_param(PlannerInfo *root, RelOptInfo *baserel, diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 267d3c1a7e7..2e63281ce2d 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -790,6 +790,271 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); + +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + +DROP FUNCTION f_local(int); + +-- Check that a qual on the function RTE using a function from a shippable +-- extension is pushed down. plpgsql (not inlined) with the column as +-- argument (not const-folded) keeps the function call in the qual. +CREATE FUNCTION f_ext(int) RETURNS int AS $$ +BEGIN RETURN $1; END +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ext(int); +-- Force pushdown so the fixed-code plan is deterministically a Foreign +-- Scan; on the unfixed code the qual is classified local, the join is +-- refused, and the plan falls back to a local join instead. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and f_ext(n) > 3; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and f_ext(n) > 3 ORDER BY r.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ext(int); +DROP FUNCTION f_ext(int); + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; +DROP FUNCTION f_ret_record(); + +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + +-- Same nullable-side whole-row Var, but with outer rows that both match +-- and miss the (foreign x function) inner join. A multi-column function +-- RTE is used so that the reference is a genuine whole-row Var (a single +-- scalar-returning function would collapse to its lone column). This +-- exercises the THEN ROW(...) side of deparseColumnRef()'s whole-row CASE +-- (matched rows reconstruct the composite) as well as the NULL side +-- (missed rows), confirming the executor rebuilds the anonymous composite +-- correctly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; + +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); + +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); + +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 3fc2c2f71d0..f21ae1baeb2 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -746,6 +746,30 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if (OidIsValid(outer_rel->serverid) && + inner_rel->rtekind == RTE_FUNCTION) + { + /* + * One side is a foreign relation, the other side is a function RTE. + * If the function is IMMUTABLE, the FDW can absorb the function call + * into the remote query (the result is identical regardless of which + * server evaluates it). Let the FDW decide whether the join is + * actually shippable; here we just propagate the FDW routine so the + * FDW gets a chance. + */ + joinrel->serverid = outer_rel->serverid; + joinrel->userid = outer_rel->userid; + joinrel->useridiscurrent = outer_rel->useridiscurrent; + joinrel->fdwroutine = outer_rel->fdwroutine; + } + else if (OidIsValid(inner_rel->serverid) && + outer_rel->rtekind == RTE_FUNCTION) + { + joinrel->serverid = inner_rel->serverid; + joinrel->userid = inner_rel->userid; + joinrel->useridiscurrent = inner_rel->useridiscurrent; + joinrel->fdwroutine = inner_rel->fdwroutine; + } } /* -- 2.43.0
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-07-30 21:19                           ` Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Korotkov @ 2026-07-30 21:19 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Jul 7, 2026 at 12:25 PM Alexander Pyhalov
<a.pyhalov@postgrespro.ru> wrote:
>
> Alexander Korotkov писал(а) 2026-07-06 17:11:
> > Hi, Alexander!
> >
> > On Wed, May 20, 2026 at 1:17 PM Alexander Pyhalov
> > <a.pyhalov@postgrespro.ru> wrote:
> >> I've found another issue. The fact that in the new versions of the
> >> patch
> >> RTE RelOptInfo misses fdw_private seems to be unfortunate. For
> >> example,
> >> in the last version we haven't thought about classifying
> >> baserestrictinfo. And if we do, we should pass fdw_private down to
> >> foreign_expr_walker. Perhaps, we could attach it to RTE_FUNCTION rel
> >> prior to calling classifyConditions(), but should we later set it back
> >> to NULL? Another problem comes if we try to handle joins,  which can
> >> crearte subqueries (like INNER/OUTER UNIQUE). In this case we should
> >> somehow cook fpinfo for get_relation_column_alias_ids(). Attaching
> >> patch
> >> which tries to handle baserestrictinfos by passing fpinfo down to
> >> foreign_expr_walker().
> >
> > I think passing fpinfo down to foreign_expr_walker() is the right
> > approach, thank you.  Attaching it to RTE_FUNCTION rel, and reseting
> > it back to NULL would create excessive state and potential source of
> > bugs.  The only advantage is saving existing function signatures, but
> > it doesn't worth it.
> >
> > Also, I don't think we need to care bout
> > get_relation_column_alias_ids().  As we currently pushdown function
> > only for inner joins, make_outerrel_subquery/make_innerrel_subquery
> > are always false, lower_subquery_rels also wouldn't contain
> > RTE_FUNCTION relid.
> >  Therefore:
> >
> >  * In deparseFromExprForRel() for functional rel deparseRangeTblRef()
> > is always called with make_subquery=false.
> >  * is_subquery_var() returns false.
>
> Well, at least current patch version classifies conditions correctly.
>
> > Other changes I made:
> >
> > 1. In foreign_join_ok(), the function side's baserestrictinfo was
> > classified against the joinrel fpinfo, whose
> > server/shippable_extensions aren't set until merge_fdw_options() runs
> > later — so extension-shippable quals would be misclassified as local
> > and silently kill the pushdown. Now it: (a) copies
> > shippable_extensions from the foreign side onto the stub, and (b)
> > classifies against the stub (fpinfo_i/fpinfo_o, which already has
> > server). Built-in quals like n > 3 were unaffected; this fixes the
> > extension case.  I've added the test case for this.
> >
> > 2. Dropped unused funcid. The per-RTE metadata was a 3-element list
> > (funcid, funcrettype, funccollation) but funcid was never read.
> > Reduced to list_make2(funcrettype, funccollation); updated the
> > consumer (linitial/lsecond) and both descriptive comments.
>
> With funcid we could print actual function name in explain.
> Now we print, for example,
>
> Relations: ((public.distr1_part_3 d1_3) INNER JOIN (public.distr2_part_3
> d2_3)) INNER JOIN (Function n)
>
> If funcid is preserved, we could output actual function name instead of
> alias. This is more similar to
> how we show relation names. Attaching updated patch, which preserves
> function names in explain.
>
> After looking at it once more, I'm not convinced when we can get
> not-FuncExpr in rtfunc->funcexpr.
> So added more checks to function_rte_pushdown_ok() to avoid dealing with
> such case.

I agree on your changes.  I've put some additional.

1) Extracted initialization of stub fpinfo for function RTE into
init_func_stub_fpinfo().  The stub now inherits fdw_startup_cost,
fdw_tuple_cost, use_remote_estimate, fetch_size and async_capable from
the foreign side, in addition to server and shippable_extensions.
Without this, merge_fdw_options() and the cost estimator would pick up
zeroed values of fdw_startup_cost and fdw_tuple_cost when the function
RTEis on the outer side of the join, so the pushdown path appears to
be artificially cheap.
2) Added a comment on the whole-row Var CASE WHEN wrapper in
deparseColumnRef() explaining that it is a no-op under the current
INNER-only policy but kept to stay correct for future outer-join and
null-supply scenarios.  Please, check if you agree with this.
3) Documented the new pushdown case in postgres-fdw.sgml, listing the
conditions under which a foreign-table x set-returning-function INNER
join is absorbed into the remote query.
4) Added a regression test verifying that a STABLE (not IMMUTABLE)
set- returning function is rejected for pushdown, alongside the
existing VOLATILE-rejection test.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

v12-0001-postgres_fdw-push-down-FUNCTION-RTE-into-foreign.patch (application/octet-stream, 87.3K) download From eb18fa4a707b76df8fa7f89eacf97ae722b872cf Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Tue, 7 Jul 2026 09:57:19 +0300 Subject: [PATCH v12] postgres_fdw: push down FUNCTION RTE into foreign joins A foreign join planning hook now considers a (foreign-table x function-RTE) INNER join as a push-down candidate when the function expression is IMMUTABLE and otherwise shippable. The remote query absorbs the function call as a FROM-list item (e.g. unnest(...) AS f<rti>(c1, c2, ...)), so the foreign side returns only rows that match the function-produced set and the join executes entirely on the remote. An IMMUTABLE function gives the same result on any server, so the same function RTE can be a push-down candidate for several distinct foreign servers without semantic risk. To keep the planner state consistent across those independent attempts, the per-call stub fpinfo for the function side lives on the joinrel's PgFdwRelationInfo (new outer_func_fpinfo / inner_func_fpinfo), never on the function rel itself, and the function side is detected via rtekind rather than fdw_private. set_foreign_rel_properties() propagates fdwroutine onto a joinrel that pairs a foreign rel with an RTE_FUNCTION rel so GetForeignJoinPaths gets called; the FDW retains full control over whether to actually generate a path. deparseRangeTblRef and deparseColumnRef gain a FUNCTION-RTE branch that emits the function expression and resolves Vars to the generated column aliases. --- contrib/postgres_fdw/deparse.c | 157 ++++- .../postgres_fdw/expected/postgres_fdw.out | 654 ++++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 635 +++++++++++++++-- contrib/postgres_fdw/postgres_fdw.h | 12 + contrib/postgres_fdw/sql/postgres_fdw.sql | 274 ++++++++ doc/src/sgml/postgres-fdw.sgml | 18 + src/backend/optimizer/util/relnode.c | 24 + 7 files changed, 1717 insertions(+), 57 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 9d1932230e7..2e0faa03ba1 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -68,6 +68,7 @@ typedef struct foreign_glob_cxt { PlannerInfo *root; /* global planner state */ RelOptInfo *foreignrel; /* the foreign relation we are planning for */ + PgFdwRelationInfo *fpinfo; /* the foreign server info we should rely on */ Relids relids; /* relids of base relations in the underlying * scan */ } foreign_glob_cxt; @@ -112,6 +113,7 @@ typedef struct deparse_expr_cxt appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno)) #define SUBQUERY_REL_ALIAS_PREFIX "s" #define SUBQUERY_COL_ALIAS_PREFIX "c" +#define FUNCTION_REL_ALIAS_PREFIX "f" /* * Functions to determine whether an expression can be evaluated safely on @@ -217,6 +219,7 @@ static void get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel, void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds) @@ -230,7 +233,7 @@ classifyConditions(PlannerInfo *root, { RestrictInfo *ri = lfirst_node(RestrictInfo, lc); - if (is_foreign_expr(root, baserel, ri->clause)) + if (is_foreign_expr(root, baserel, fpinfo, ri->clause)) *remote_conds = lappend(*remote_conds, ri); else *local_conds = lappend(*local_conds, ri); @@ -243,11 +246,11 @@ classifyConditions(PlannerInfo *root, bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr) { foreign_glob_cxt glob_cxt; foreign_loc_cxt loc_cxt; - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private); /* * Check that the expression consists of nodes that are safe to execute @@ -255,6 +258,7 @@ is_foreign_expr(PlannerInfo *root, */ glob_cxt.root = root; glob_cxt.foreignrel = baserel; + glob_cxt.fpinfo = fpinfo; /* * For an upper relation, use relids from its underneath scan relation, @@ -324,8 +328,8 @@ foreign_expr_walker(Node *node, if (node == NULL) return true; - /* May need server info from baserel's fdw_private struct */ - fpinfo = (PgFdwRelationInfo *) (glob_cxt->foreignrel->fdw_private); + /* May need server info from global context */ + fpinfo = glob_cxt->fpinfo; /* Set up inner_cxt for possible recursion to child nodes */ inner_cxt.collation = InvalidOid; @@ -2050,6 +2054,72 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, } } +/* + * Deparse a FUNCTION RTE absorbed into a foreign join. The function call(s) + * are emitted as a FROM-list item: + * + * <funcexpr> AS f<rti>(c1, c2, ..., cN) + * + * For multi-function RTEs (SQL ROWS FROM (f1(), f2(), ...)), each + * function call appears comma-separated inside ROWS FROM(...). Column + * aliases c1..cN cover the union of every function's columns, in the + * order they appear; that matches the column ordering of the RTE. + */ +static void +deparseFunctionRangeTblRef(StringInfo buf, PlannerInfo *root, + RelOptInfo *foreignrel, RelOptInfo *scanrel, + List **params_list) +{ + RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); + deparse_expr_cxt context; + ListCell *lc; + bool multi_func; + int total_cols = 0; + int i; + + Assert(rte->rtekind == RTE_FUNCTION); + Assert(!rte->funcordinality); + Assert(list_length(rte->functions) >= 1); + + multi_func = list_length(rte->functions) > 1; + + context.buf = buf; + context.root = root; + context.foreignrel = scanrel; + context.scanrel = scanrel; + context.params_list = params_list; + + if (multi_func) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (foreach_current_index(lc) > 0) + appendStringInfoString(buf, ", "); + deparseExpr((Expr *) rtfunc->funcexpr, &context); + total_cols += rtfunc->funccolcount; + } + + if (multi_func) + appendStringInfoChar(buf, ')'); + + /* Alias + generated column-name list. */ + appendStringInfo(buf, " %s%d", FUNCTION_REL_ALIAS_PREFIX, foreignrel->relid); + if (total_cols > 0) + { + appendStringInfoChar(buf, '('); + for (i = 1; i <= total_cols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + } +} + /* * Append FROM clause entry for the given relation into buf. * Conditions from lower-level SEMI-JOINs are appended to additional_conds @@ -2060,7 +2130,22 @@ deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **additional_conds, List **params_list) { - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + PgFdwRelationInfo *fpinfo; + + /* + * For a function RTE absorbed into a foreign join, deparse the function + * expression as a FROM-list item and return. The stub fpinfo set up by + * foreign_join_ok() may or may not be present here. + */ + if (foreignrel->rtekind == RTE_FUNCTION) + { + Assert(!make_subquery); + deparseFunctionRangeTblRef(buf, root, foreignrel, foreignrel, + params_list); + return; + } + + fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; /* Should only be called in these cases. */ Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel)); @@ -2732,6 +2817,68 @@ static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col) { + /* + * Function RTE columns: emit as f<varno>.c<varattno>, matching the + * aliases generated by deparseFunctionRangeTblRef(). A whole-row Var + * (varattno == 0) is rendered as ROW(f<varno>.c1, ..., f<varno>.c<N>) + * where N is the total column count of the function RTE (including all + * ROWS FROM (...) members). System attributes such as ctid have no + * meaning for function RTEs and are rejected. + */ + if (rte->rtekind == RTE_FUNCTION) + { + if (varattno == 0) + { + int ncols = list_length(rte->eref->colnames); + int i; + + /* + * The CASE WHEN wrapper distinguishes a NULL-supplied outer-join + * row (whole-row Var is NULL) from a row whose columns all happen + * to be NULL (whole-row Var is ROW(NULL, ..., NULL)). A bare + * ROW(...) would collapse those two cases to the latter. + * + * The current push-down policy only absorbs INNER joins with a + * function RTE, so the null-supplied case cannot arise from a + * remote outer join we emit ourselves. We still emit the wrapper + * unconditionally: it is a no-op for INNER-join rows, and it keeps + * the deparsed SQL correct if a future patch relaxes the INNER + * restriction (or a higher-level outer join propagates a NULL row + * through the foreign scan's tuple). + */ + if (qualify_col) + { + appendStringInfoString(buf, "CASE WHEN ("); + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfoString(buf, "*)::text IS NOT NULL THEN "); + } + + appendStringInfoString(buf, "ROW("); + for (i = 1; i <= ncols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d.%s%d", + FUNCTION_REL_ALIAS_PREFIX, varno, + SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + + if (qualify_col) + appendStringInfoString(buf, " END"); + return; + } + + if (varattno < 0) + elog(ERROR, + "system attribute reference to a function RTE is not supported in foreign join pushdown"); + + if (qualify_col) + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, varattno); + return; + } + /* We support fetching the remote side's CTID and OID. */ if (varattno == SelfItemPointerAttributeNumber) { diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index d19121b05da..a230096cc54 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2960,6 +2960,660 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c (10 rows) ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: t1.c1, t1.c3 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1, t1.c3 + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r1."C 1", r1.c3 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{1,5,10,100}'::integer[]) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + c1 | c3 +-----+------- + 1 | 00001 + 5 | 00005 + 10 | 00010 + 100 | 00100 +(4 rows) + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Sort + Output: t1.c1 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1 + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.generate_series() g) + Remote SQL: SELECT r1."C 1" FROM ("S 1"."T 1" r1 INNER JOIN generate_series(1, 4) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + c1 +---- + 1 + 2 + 3 + 4 +(4 rows) + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on pg_catalog.generate_series g + Output: g.id + Function Call: generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +-- STABLE function must NOT be pushed down either: even though its result is +-- constant within one query, evaluating it on the remote server could yield +-- a different value than evaluating it locally. +CREATE FUNCTION f_stable(int) RETURNS SETOF int LANGUAGE plpgsql STABLE AS +$$ BEGIN RETURN QUERY SELECT generate_series(1, $1); END $$; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, f_stable(4) AS g(id) WHERE t1.c1 = g.id; + QUERY PLAN +--------------------------------------------------------- + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on public.f_stable g + Output: g.id + Function Call: f_stable(4) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +DROP FUNCTION f_stable(int); +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + QUERY PLAN +------------------------------------------------------------ + Hash Join + Output: t1.c1, u.ord + Hash Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" + -> Hash + Output: u.ord, u.id + -> Function Scan on pg_catalog.unnest u + Output: u.ord, u.id + Function Call: unnest('{1,5,10}'::integer[]) +(11 rows) + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: t1.c1, t2.c1 + Merge Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST + -> Sort + Output: t2.c1, u.id + Sort Key: t2.c1 + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{1,5,10,100}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(13 rows) + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: t1.c1, t2.c1 + Hash Cond: (t1.c1 = t2.c1) + -> Foreign Scan + Output: t1.c1, u.id + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r1."C 1", f3.c1 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r1."C 1" = f3.c1)))) + -> Hash + Output: t2.c1 + -> Foreign Scan on public.ft6 t2 + Output: t2.c1 + Remote SQL: SELECT c1 FROM "S 1"."T 4" +(12 rows) + +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: t1.c1, t2.c1 + Join Filter: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE ((c3 < '00010')) + -> Materialize + Output: t2.c1, u.id + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(12 rows) + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + n | a | b +---+---+----- + 2 | 2 | 102 + 3 | 3 | 103 + 4 | 4 | 104 +(3 rows) + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)) AND ((f1.c1 > 3)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); + QUERY PLAN +----------------------------------------------------------- + Hash Join + Output: n.n, r.a, r.b + Hash Cond: (r.a = n.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a, b FROM public.base_tbl_fn + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4}'::integer[]) + Filter: (n.n > f_local(3)) +(12 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +DROP FUNCTION f_local(int); +-- Check that a qual on the function RTE using a function from a shippable +-- extension is pushed down. plpgsql (not inlined) with the column as +-- argument (not const-folded) keeps the function call in the qual. +CREATE FUNCTION f_ext(int) RETURNS int AS $$ +BEGIN RETURN $1; END +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ext(int); +-- Force pushdown so the fixed-code plan is deterministically a Foreign +-- Scan; on the unfixed code the qual is classified local, the join is +-- refused, and the plan falls back to a local join instead. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and f_ext(n) > 3; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)) AND ((public.f_ext(f1.c1) > 3)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and f_ext(n) > 3 ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ext(int); +DROP FUNCTION f_ext(int); +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: s.* + Hash Cond: (rt.a = s.a) + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl_fn + -> Hash + Output: s.*, s.a + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() +(11 rows) + +DROP FUNCTION f_ret_record(); +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + a | b +----+----- + 23 | 123 + 24 | 999 + 25 | 125 +(3 rows) + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + a | b +----+--- + 24 | 5 +(1 row) + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + a | b | t +----+---+--------------------- + 24 | 7 | ("(2,3),(-2,-3)",1) +(1 row) + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: r.a, t.n, t.s + Sort Key: r.a + -> Foreign Scan + Output: r.a, t.n, t.s + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.generate_series()) t) + Remote SQL: SELECT r1.a, f2.c1, f2.c2 FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + a | n | s +---+---+---- + 3 | 3 | 11 + 6 | 6 | 12 + 9 | 9 | 13 +(3 rows) + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: ((t.*)::text), r.a + Sort Key: r.a + -> Foreign Scan + Output: (t.*)::text, r.a + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.generate_series()) t) + Remote SQL: SELECT CASE WHEN (f2.*)::text IS NOT NULL THEN ROW(f2.c1, f2.c2) END, r1.a FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + t | a +--------+--- + (3,11) | 3 + (6,12) | 6 + (9,13) | 9 +(3 rows) + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: u.*, ft5.c1, ft5.c2, ft4.c1, ft4.c2 + Relations: (public.ft5) LEFT JOIN ((public.ft4) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.unnest()) u)) + Remote SQL: SELECT CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END, r1.c1, r1.c2, r2.c1, r2.c2 FROM ("S 1"."T 4" r1 LEFT JOIN ("S 1"."T 3" r2 INNER JOIN ROWS FROM (unnest('{1,2}'::integer[]), unnest('{3,4}'::integer[])) f3(c1, c2) ON (((r2.c1 = f3.c1)))) ON (((r1.c1 = r2.c1)))) WHERE ((r1.c1 < 10)) ORDER BY r1.c1 ASC NULLS LAST +(4 rows) + +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + u | c1 | c2 | c1 | c2 +---+----+----+----+---- + | 3 | 4 | | + | 6 | 7 | | + | 9 | 10 | | +(3 rows) + +-- Same nullable-side whole-row Var, but with outer rows that both match +-- and miss the (foreign x function) inner join. A multi-column function +-- RTE is used so that the reference is a genuine whole-row Var (a single +-- scalar-returning function would collapse to its lone column). This +-- exercises the THEN ROW(...) side of deparseColumnRef()'s whole-row CASE +-- (matched rows reconstruct the composite) as well as the NULL side +-- (missed rows), confirming the executor rebuilds the anonymous composite +-- correctly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: l.a, t.* + Relations: (public.remote_tbl l) LEFT JOIN ((public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.unnest()) t)) + Remote SQL: SELECT r1.a, CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END FROM (public.base_tbl_fn r1 LEFT JOIN (public.base_tbl_fn r2 INNER JOIN ROWS FROM (unnest('{2,4}'::integer[]), unnest('{20,40}'::integer[])) f3(c1, c2) ON (((r2.a = f3.c1)))) ON (((r1.a = r2.a)))) WHERE ((r1.a < 6)) ORDER BY r1.a ASC NULLS LAST +(4 rows) + +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; + a | t +---+-------- + 1 | + 2 | (2,20) + 3 | + 4 | (4,40) + 5 | +(5 rows) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: s.a, s.b + Sort Key: s.a + CTE s + -> Nested Loop + Output: r1.a, r1.b + -> Foreign Scan on public.remote_tbl r1 + Output: r1.a, r1.b + Remote SQL: SELECT a, b FROM public.base_tbl_fn + -> Foreign Scan + Output: NULL::integer + Relations: (public.remote_tbl r2) INNER JOIN (public.f()) + Remote SQL: SELECT NULL FROM (public.base_tbl_fn r1 INNER JOIN public.f($1::integer) f2(c1) ON (TRUE)) LIMIT 1::bigint + -> CTE Scan on s + Output: s.a, s.b +(15 rows) + +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + a | b +----+----- + 1 | 101 + 2 | 102 + 3 | 103 + 4 | 104 + 5 | 105 + 6 | 106 + 7 | 107 + 8 | 108 + 9 | 109 + 10 | 110 + 11 | 111 + 12 | 112 + 13 | 113 + 14 | 114 + 15 | 115 + 16 | 116 + 17 | 117 + 18 | 118 + 19 | 119 + 20 | 120 + 21 | 121 + 22 | 122 + 23 | 123 + 24 | 7 + 25 | 125 + 26 | 126 + 27 | 127 + 28 | 128 + 29 | 129 + 30 | 130 +(30 rows) + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: r.a + Merge Cond: (t.n = r.a) + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]), generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Sort + Output: r.a + Sort Key: r.a + -> Foreign Scan on public.remote_tbl r + Output: r.a + Remote SQL: SELECT a FROM public.base_tbl_fn +(15 rows) + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Nested Loop + Output: r.a, t.x + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 3)) ORDER BY a ASC NULLS LAST + -> Function Scan on pg_catalog.unnest t + Output: t.x + Function Call: unnest(ARRAY[r.a]) +(8 rows) + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Merge Left Join + Output: r.a, t.n + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 5)) ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{1,2,3}'::integer[]) +(12 rows) + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + QUERY PLAN +-------------------------------------------------------------------------------- + Merge Semi Join + Output: r.a + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]) +(12 rows) + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 8b660a6c02c..f6a6e62e1a3 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -30,6 +30,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/appendinfo.h" +#include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" #include "optimizer/optimizer.h" @@ -90,6 +91,22 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of per-RTE function metadata, indexed by base RTI offset. Each + * element is either NULL (for non-RTE_FUNCTION rels in this scan) or a + * list of three-element lists (funcid, funcrettype, funccollation) -- one + * inner list per function in the RTE. Allows the executor to rebuild + * TupleDesc entries for whole-row references to function RTEs. + */ + FdwScanPrivateFunctions, + + /* + * Integer node: minimum base RT index covered by the scan, used to + * translate scan-local indexes to estate-rtable indexes after setrefs.c + * flattens rtables. + */ + FdwScanPrivateMinRTIndex, }; /* @@ -126,6 +143,11 @@ enum FdwModifyPrivateIndex * 2) Boolean flag showing if the remote query has a RETURNING clause * 3) Integer list of attribute numbers retrieved by RETURNING, if any * 4) Boolean flag showing if we set the command es_processed + * 5) Per-RTE function metadata (mirrors FdwScanPrivateFunctions; lets + * the executor rebuild TupleDesc entries for whole-row Vars over + * function RTEs absorbed into a foreign join) + * 6) Integer node: minimum base RT index of the scan (mirrors + * FdwScanPrivateMinRTIndex) */ enum FdwDirectModifyPrivateIndex { @@ -137,6 +159,10 @@ enum FdwDirectModifyPrivateIndex FdwDirectModifyPrivateRetrievedAttrs, /* set-processed flag (as a Boolean node) */ FdwDirectModifyPrivateSetProcessed, + /* Per-RTE function metadata, indexed by base RTI offset */ + FdwDirectModifyPrivateFunctions, + /* Integer node: minimum base RT index in the scan */ + FdwDirectModifyPrivateMinRTIndex, }; /* @@ -619,6 +645,9 @@ static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, static List *get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel); static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, Path *epq_path, List *restrictlist); static void add_foreign_grouping_paths(PlannerInfo *root, @@ -772,7 +801,7 @@ postgresGetForeignRelSize(PlannerInfo *root, * Identify which baserestrictinfo clauses can be sent to the remote * server and which can't. */ - classifyConditions(root, baserel, baserel->baserestrictinfo, + classifyConditions(root, baserel, fpinfo, baserel->baserestrictinfo, &fpinfo->remote_conds, &fpinfo->local_conds); /* @@ -1176,7 +1205,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1252,7 +1281,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1392,7 +1421,7 @@ postgresGetForeignPlan(PlannerInfo *root, remote_exprs = lappend(remote_exprs, rinfo->clause); else if (list_member_ptr(fpinfo->local_conds, rinfo)) local_exprs = lappend(local_exprs, rinfo->clause); - else if (is_foreign_expr(root, foreignrel, rinfo->clause)) + else if (is_foreign_expr(root, foreignrel, fpinfo, rinfo->clause)) remote_exprs = lappend(remote_exprs, rinfo->clause); else local_exprs = lappend(local_exprs, rinfo->clause); @@ -1513,9 +1542,26 @@ postgresGetForeignPlan(PlannerInfo *root, fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(fpinfo->fetch_size)); + + /* + * Position FdwScanPrivateRelations: either the EXPLAIN relation string + * (joins/upper rels) or a NULL placeholder, so that subsequent indexes + * stay valid for the base-rel scan case. + */ if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + /* + * FdwScanPrivateFunctions / FdwScanPrivateMinRTIndex carry the metadata + * the executor needs to rebuild TupleDesc entries for whole-row Vars + * pointing at RTE_FUNCTION rels absorbed into the foreign scan. + */ + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + fdw_private = lappend(fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1536,9 +1582,15 @@ postgresGetForeignPlan(PlannerInfo *root, /* * Construct a tuple descriptor for the scan tuples handled by a foreign join. + * + * 'rtfuncdata' is the FdwScanPrivateFunctions list saved at plan time, and + * 'rtoffset' is the difference between the executor's RT indexes and the + * scan-local RT indexes captured in that list. Both may be 0/NIL when the + * scan has no RTE_FUNCTION dependents. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, + List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1574,13 +1626,67 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * A whole-row Var points at a FUNCTION RTE absorbed into the + * foreign join. Synthesize an anonymous composite TupleDesc from + * the per-function return-type metadata we saved at plan time; + * the deparser emits these as ROW(f<rti>.c1, f<rti>.c2, ...). + * + * For an upperrel scan (the only path that reaches here) + * postgresGetForeignPlan always builds rtfuncdata via + * get_functions_data(), so it is never NIL; the per-RTE slot for + * the function RTE referenced by this Var must likewise be + * populated. + */ + List *funcdata; + TupleDesc rte_tupdesc; + int num_funcs; + int attnum; + ListCell *lc1, + *lc2; + + Assert(rtfuncdata != NIL); + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + Assert(funcdata != NIL); + num_funcs = list_length(funcdata); + Assert(num_funcs == list_length(rte->eref->colnames)); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc1, funcdata, lc2, rte->eref->colnames) + { + List *fdata = lfirst_node(List, lc1); + char *colname = strVal(lfirst(lc2)); + Oid funcrettype; + Oid funccollation; + + funcrettype = lsecond_node(Integer, fdata)->ival; + funccollation = lthird_node(Integer, fdata)->ival; + + /* get_functions_data() already validated the return type. */ + Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funccollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1616,14 +1722,30 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. For a join, scan the base relids until we + * find an RTE_RELATION (the foreign-table side); ignore any RTE_FUNCTION + * absorbed into the join, which contributes no relation OID to look up. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); + rte = NULL; if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte != NULL && rte->rtekind == RTE_RELATION) + break; + rte = NULL; + } + if (rte == NULL) + elog(ERROR, "could not locate a foreign relation RTE in foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1666,8 +1788,19 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwScanPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwScanPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, + rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2620,7 +2753,7 @@ postgresPlanDirectModify(PlannerInfo *root, if (attno <= InvalidAttrNumber) /* shouldn't happen */ elog(ERROR, "system-column update is not supported"); - if (!is_foreign_expr(root, foreignrel, (Expr *) tle->expr)) + if (!is_foreign_expr(root, foreignrel, fpinfo, (Expr *) tle->expr)) return false; } } @@ -2707,6 +2840,10 @@ postgresPlanDirectModify(PlannerInfo *root, makeBoolean((retrieved_attrs != NIL)), retrieved_attrs, makeBoolean(plan->canSetTag)); + fscan->fdw_private = lappend(fscan->fdw_private, + get_functions_data(root, foreignrel)); + fscan->fdw_private = lappend(fscan->fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Update the foreign-join-related fields. @@ -2820,7 +2957,26 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + /* + * DirectModify on a foreign join: use the per-RTE function + * metadata saved at plan time so a whole-row Var pointing at a + * function RTE absorbed into the join can be rebuilt into a + * usable TupleDesc (e.g. RETURNING t for a join with UNNEST(..., + * ...) AS t(bx, i)). + */ + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + + tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -2933,7 +3089,8 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_length(fdw_private) > FdwScanPrivateRelations && + list_nth(fdw_private, FdwScanPrivateRelations) != NULL) { StringInfoData relations; char *rawrelations; @@ -2983,25 +3140,90 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); - Assert(rte->rtekind == RTE_RELATION); - /* This logic should agree with explain.c's ExplainTargetRel */ - relname = get_rel_name(rte->relid); - if (es->verbose) - { - char *namespace; - namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); - appendStringInfo(&relations, "%s.%s", - quote_identifier(namespace), - quote_identifier(relname)); + if (rte->rtekind == RTE_FUNCTION) + { + List *rtfuncdata = list_nth(fdw_private, FdwScanPrivateFunctions); + List *funcdata; + bool multi_func; + bool first = true; + ListCell *lc; + + funcdata = list_nth(rtfuncdata, rti - rtoffset); + + multi_func = list_length(funcdata) > 1; + + if (multi_func) + appendStringInfoString(&relations, "ROWS FROM ("); + + foreach(lc, funcdata) + { + List *funcinfo; + Oid funcid; + + + if (!first) + appendStringInfoString(&relations, ", "); + + funcinfo = (List *) lfirst(lc); + + funcid = linitial_node(Integer, funcinfo)->ival; + /* Checked by function_rte_pushdown_ok() */ + Assert(OidIsValid(funcid)); + + /* Match RTE_RELATION behavior */ + relname = get_func_name(funcid); + if (relname == NULL) + elog(ERROR, "cache lookup failed for function %u", funcid); + if (es->verbose) + { + char *namespace; + Oid nsoid = get_func_namespace(funcid); + + namespace = get_namespace_name(nsoid); + if (namespace == NULL) + elog(ERROR, "cache lookup failed for namespace %u", nsoid); + + appendStringInfo(&relations, "%s.%s()", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfo(&relations, "%s()", quote_identifier(relname)); + + first = false; + } + /* Close ROWS FROM */ + if (multi_func) + appendStringInfoChar(&relations, ')'); } else - appendStringInfoString(&relations, - quote_identifier(relname)); + { + Assert(rte->rtekind == RTE_RELATION); + + /* + * This logic should agree with explain.c's + * ExplainTargetRel + */ + relname = get_rel_name(rte->relid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); + appendStringInfo(&relations, "%s.%s", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfoString(&relations, + quote_identifier(relname)); + } + refname = (char *) list_nth(es->rtable_names, rti - 1); if (refname == NULL) refname = rte->eref->aliasname; - if (strcmp(refname, relname) != 0) + if (relname == NULL || strcmp(refname, relname) != 0) appendStringInfo(&relations, " %s", quote_identifier(refname)); } @@ -3225,7 +3447,7 @@ estimate_path_cost_size(PlannerInfo *root, * param_join_conds might contain both clauses that are safe to send * across, and clauses that aren't. */ - classifyConditions(root, foreignrel, param_join_conds, + classifyConditions(root, foreignrel, fpinfo, param_join_conds, &remote_param_join_conds, &local_param_join_conds); /* Build the list of columns to be fetched from the foreign server. */ @@ -3358,8 +3580,17 @@ estimate_path_cost_size(PlannerInfo *root, /* For join we expect inner and outer relations set */ Assert(fpinfo->innerrel && fpinfo->outerrel); - fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; + /* + * For a FUNCTION RTE absorbed into the join, use the stub fpinfo + * we built in foreign_join_ok(), since the function rel itself + * has no fdw_private. + */ + fpinfo_i = fpinfo->inner_func_fpinfo ? + fpinfo->inner_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; + fpinfo_o = fpinfo->outer_func_fpinfo ? + fpinfo->outer_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; /* Estimate of number of rows in cross product */ nrows = fpinfo_i->rows * fpinfo_o->rows; @@ -6570,6 +6801,250 @@ semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, return ok; } +/* + * get_base_relids + * Return the set of base relids referenced by a foreign scan rel. + * + * For an upper rel we use the all-query relids minus the outer joins; + * otherwise the rel's own relids minus the outer joins. The result matches + * the relids that create_foreignscan_plan() ultimately uses for + * ForeignScan.fs_base_relids, so it is suitable for any tagging we want to + * store via plan-private state. + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + return bms_difference(relids, root->outer_join_rels); +} + +/* + * get_min_base_rti + * Lowest base RT index in the foreign scan rel. + * + * After setrefs.c flattens the rtable, the scan-local indexes saved in + * plan-private data can be translated to estate indexes by adding + * (ForeignScan.fs_base_relids min - this value). Captured at plan time + * because create_foreignscan_plan() computes the same value internally. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + +/* + * get_functions_data + * Build the per-RTE function metadata list saved as + * FdwScanPrivateFunctions. + * + * The result list is indexed by base RT index relative to the lowest base + * RT index of the scan. Each element is either NULL (for non-RTE_FUNCTION + * base rels in this scan) or a List of List of two Integer nodes: + * (funcrettype, funccollation) -- one inner list per RangeTblFunction. + * + * Only RTE_FUNCTION relids actually appearing in the foreign scan's + * fs_base_relids contribute; others are placeholders so that the consumer + * can index into the result by RTI offset. + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + Relids fscan_relids = get_base_relids(root, rel); + int i; + + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + List *funcdata = NIL; + ListCell *lc; + + if (rte == NULL || i == 0 || + !bms_is_member(i, fscan_relids) || + rte->rtekind != RTE_FUNCTION) + { + rtfuncdata = lappend(rtfuncdata, NULL); + continue; + } + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + Oid funcrettype; + Oid funccollation; + TupleDesc tupdesc; + Oid funcid; + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + /* + * function_rte_pushdown_ok() already rejected any function that + * doesn't return a well-defined scalar type, so this is a mere + * cross-check. + */ + Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID); + + funccollation = exprCollation(rtfunc->funcexpr); + + funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid; + + funcdata = lappend(funcdata, + list_make3(makeInteger(funcid), + makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + + return rtfuncdata; +} + +/* + * init_func_stub_fpinfo + * Build a stub PgFdwRelationInfo for a FUNCTION RTE that is being + * absorbed into a foreign join. + * + * A function RTE has no fdw_private of its own, but the joinrel-level cost + * estimator, deparser and merge_fdw_options() all read server-level options + * from the "outer" fpinfo unconditionally. So the stub must carry the same + * server, shippable_extensions, and cost-related options as the real foreign + * side of the join; otherwise the pushdown path is judged against zeroed + * fdw_startup_cost/fdw_tuple_cost/etc. and looks artificially cheap. + * + * The stub is meaningful only for the specific (foreign, function) pairing + * that produced it; it must live on the joinrel's PgFdwRelationInfo, never + * on the function rel's fdw_private, since the same function RTE may pair + * with different foreign servers in sibling joinrels. + */ +static PgFdwRelationInfo * +init_func_stub_fpinfo(const PgFdwRelationInfo *fpinfo_foreign, + RelOptInfo *funcrel) +{ + PgFdwRelationInfo *stub = palloc0_object(PgFdwRelationInfo); + + stub->pushdown_safe = true; + + /* Server-level options, inherited from the foreign side. */ + stub->server = fpinfo_foreign->server; + stub->shippable_extensions = fpinfo_foreign->shippable_extensions; + stub->fdw_startup_cost = fpinfo_foreign->fdw_startup_cost; + stub->fdw_tuple_cost = fpinfo_foreign->fdw_tuple_cost; + stub->use_remote_estimate = fpinfo_foreign->use_remote_estimate; + stub->fetch_size = fpinfo_foreign->fetch_size; + stub->async_capable = fpinfo_foreign->async_capable; + + /* Function-side identity and estimates from the local planner. */ + stub->relation_name = psprintf("%u", funcrel->relid); + stub->rows = funcrel->rows; + stub->width = funcrel->reltarget->width; + stub->retrieved_rows = funcrel->rows; + stub->rel_startup_cost = 0; + stub->rel_total_cost = 0; + + return stub; +} + +/* + * Check if a relation is a FUNCTION RTE that can be absorbed into a remote + * join. Every function in the RTE must + * + * - return a well-defined scalar type -- we don't ship records/composite + * since the remote server cannot reconstruct a column definition list + * and our deparser does not emit one; + * - have a shippable expression with no mutable subnodes -- is_foreign_expr() + * rejects volatile/stable functions through contain_mutable_functions(), + * so the IMMUTABLE-only restriction is implicit; + * - not contain SubPlans -- we'd otherwise need to ship sub-results to + * the remote, which we do not implement. + * + * WITH ORDINALITY is not supported yet. + */ +static bool +function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel, + RelOptInfo *fdwrel) +{ + RangeTblEntry *rte; + ListCell *lc; + + if (rel->rtekind != RTE_FUNCTION) + return false; + rte = planner_rt_fetch(rel->relid, root); + + /* + * build_simple_rel() copies rtekind straight from the RTE, so for a base + * rel rel->rtekind always matches the RTE's; the check above is therefore + * sufficient. + */ + Assert(rte->rtekind == RTE_FUNCTION); + + if (rte->funcordinality) + return false; + + /* + * Reject up-front any function RTE that lateral-references another + * relation: foreign-join push-down would need to parameterise the remote + * query per outer row, which we don't support, and even considering the + * path is expensive on the planner side. The surrounding lateral_relids + * check in postgresGetForeignJoinPaths() would normally bail out for the + * joinrel, but doing the check here avoids walking the function + * expression entirely. + * + * Note this rejects only lateral references to another relation at the + * same query level. A function argument referencing an outer query level + * (e.g. f(outer.col) inside a subquery) is a different case: it becomes a + * PARAM_EXEC Param, the function rel's lateral_relids is empty, and + * foreign_expr_walker() intentionally treats PARAM_EXEC as shippable. The + * remote query then carries a parameter placeholder, and postgres_fdw's + * ordinary parameter machinery re-sends it on each rescan -- i.e. it + * works as a normal parameterized foreign scan, which is fine. + */ + if (!bms_is_empty(rel->lateral_relids)) + return false; + + Assert(list_length(rte->functions) >= 1); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + TypeFuncClass functypclass; + Oid funcrettype; + TupleDesc tupdesc; + + /* Refuse to deal with strange funcexprs */ + if (!IsA(rtfunc->funcexpr, FuncExpr)) + return false; + + if (!OidIsValid(((FuncExpr *) rtfunc->funcexpr)->funcid)) + return false; + + functypclass = get_expr_result_type(rtfunc->funcexpr, + &funcrettype, &tupdesc); + if (functypclass != TYPEFUNC_SCALAR) + return false; + if (!OidIsValid(funcrettype) || + funcrettype == RECORDOID || + funcrettype == VOIDOID) + return false; + + if (contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, fdwrel, fdwrel->fdw_private, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -6585,6 +7060,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; + bool outer_is_function = false; + bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -6603,15 +7080,68 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, return false; /* - * If either of the joining relations is marked as unsafe to pushdown, the - * join can not be pushed down. + * Detect mixed (foreign x function-RTE) cases. Only INNER joins are + * supported initially. We dispatch on rtekind here so that the same + * function RTE can be absorbed into joins on multiple foreign servers + * (each call gets its own stub fpinfo and rechecks shippability for the + * specific server). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && + (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && + fpinfo_o->pushdown_safe && + function_rte_pushdown_ok(root, innerrel, outerrel)) + { + inner_is_function = true; + } + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) + { + outer_is_function = true; + } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } + + /* + * If one side is a function RTE, allocate a stub fpinfo so the rest of + * this function and the cost estimator can treat it uniformly. We hand + * the stub to the joinrel's deparser via the same path the foreign side + * uses, but we never permanently attach it to the function rel's + * fdw_private (different joinrels may pair the same function RTE with + * different foreign servers). + */ + if (inner_is_function) + { + fpinfo_i = init_func_stub_fpinfo(fpinfo_o, innerrel); + + /* + * Classify the function rel's own baserestrictinfo now, so that the + * local_conds check below can bail out if any of it is unshippable. + * We classify against the stub, not the joinrel's fpinfo, because the + * latter's server/shippable_extensions aren't populated until + * merge_fdw_options() runs further down. + */ + classifyConditions(root, innerrel, fpinfo_i, innerrel->baserestrictinfo, + &fpinfo_i->remote_conds, &fpinfo_i->local_conds); + fpinfo->inner_func_fpinfo = fpinfo_i; + } + else if (outer_is_function) + { + fpinfo_o = init_func_stub_fpinfo(fpinfo_i, outerrel); + + /* See the comment in the inner_is_function branch above. */ + classifyConditions(root, outerrel, fpinfo_o, outerrel->baserestrictinfo, + &fpinfo_o->remote_conds, &fpinfo_o->local_conds); + fpinfo->outer_func_fpinfo = fpinfo_o; + } /* * If joining relations have local conditions, those conditions are @@ -6649,7 +7179,7 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, foreach(lc, extra->restrictlist) { RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc); - bool is_remote_clause = is_foreign_expr(root, joinrel, + bool is_remote_clause = is_foreign_expr(root, joinrel, fpinfo, rinfo->clause); if (IS_OUTER_JOIN(jointype) && @@ -7347,7 +7877,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * If any GROUP BY expression is not shippable, then we cannot * push down aggregation to the foreign server. */ - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; /* @@ -7375,7 +7905,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * Non-grouping expression we need to compute. Can we ship it * as-is to the foreign server? */ - if (is_foreign_expr(root, grouped_rel, expr) && + if (is_foreign_expr(root, grouped_rel, fpinfo, expr) && !is_foreign_param(root, grouped_rel, expr)) { /* Yes, so add to tlist as-is; OK to suppress duplicates */ @@ -7395,7 +7925,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * don't have to check is_foreign_param, since that certainly * won't return true for any such expression.) */ - if (!is_foreign_expr(root, grouped_rel, (Expr *) aggvars)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, (Expr *) aggvars)) return false; /* @@ -7447,7 +7977,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, grouped_rel->relids, NULL, NULL); - if (is_foreign_expr(root, grouped_rel, expr)) + if (is_foreign_expr(root, grouped_rel, fpinfo, expr)) fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo); else fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo); @@ -7484,7 +8014,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, */ if (IsA(expr, Aggref)) { - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; tlist = add_to_flat_tlist(tlist, list_make1(expr)); @@ -7997,8 +8527,8 @@ add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel, * Also, the LIMIT/OFFSET cannot be pushed down, if their expressions are * not safe to remote. */ - if (!is_foreign_expr(root, input_rel, (Expr *) parse->limitOffset) || - !is_foreign_expr(root, input_rel, (Expr *) parse->limitCount)) + if (!is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitOffset) || + !is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitCount)) return; /* Safe to push down */ @@ -8644,7 +9174,7 @@ find_em_for_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel) if (bms_is_subset(em->em_relids, rel->relids) && !bms_is_empty(em->em_relids) && bms_is_empty(bms_intersect(em->em_relids, fpinfo->hidden_subquery_rels)) && - is_foreign_expr(root, rel, em->em_expr)) + is_foreign_expr(root, rel, fpinfo, em->em_expr)) return em; } @@ -8666,6 +9196,7 @@ EquivalenceMember * find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel) { + PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private; PathTarget *target = rel->reltarget; ListCell *lc1; int i; @@ -8715,7 +9246,7 @@ find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, continue; /* Check that expression (including relabels!) is shippable */ - if (is_foreign_expr(root, rel, em->em_expr)) + if (is_foreign_expr(root, rel, fpinfo, em->em_expr)) return em; } diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..da7da1c2ea9 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -106,6 +106,16 @@ typedef struct PgFdwRelationInfo /* joinclauses contains only JOIN/ON conditions for an outer join */ List *joinclauses; /* List of RestrictInfo */ + /* + * If a FUNCTION RTE was absorbed into this join, these point at the stub + * PgFdwRelationInfo for the function side (paired with the + * outerrel/innerrel), so the cost estimator and deparser can find it + * without consulting the function rel's fdw_private. At most one of + * outer_func_fpinfo/inner_func_fpinfo is set. + */ + struct PgFdwRelationInfo *outer_func_fpinfo; + struct PgFdwRelationInfo *inner_func_fpinfo; + /* Upper relation information */ UpperRelationKind stage; @@ -183,11 +193,13 @@ extern char *pgfdw_application_name; /* in deparse.c */ extern void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds); extern bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr); extern bool is_foreign_param(PlannerInfo *root, RelOptInfo *baserel, diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index e7019952173..7dcb206e394 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -825,6 +825,280 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + +-- STABLE function must NOT be pushed down either: even though its result is +-- constant within one query, evaluating it on the remote server could yield +-- a different value than evaluating it locally. +CREATE FUNCTION f_stable(int) RETURNS SETOF int LANGUAGE plpgsql STABLE AS +$$ BEGIN RETURN QUERY SELECT generate_series(1, $1); END $$; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, f_stable(4) AS g(id) WHERE t1.c1 = g.id; +DROP FUNCTION f_stable(int); + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); + +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + +DROP FUNCTION f_local(int); + +-- Check that a qual on the function RTE using a function from a shippable +-- extension is pushed down. plpgsql (not inlined) with the column as +-- argument (not const-folded) keeps the function call in the qual. +CREATE FUNCTION f_ext(int) RETURNS int AS $$ +BEGIN RETURN $1; END +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ext(int); +-- Force pushdown so the fixed-code plan is deterministically a Foreign +-- Scan; on the unfixed code the qual is classified local, the join is +-- refused, and the plan falls back to a local join instead. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and f_ext(n) > 3; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and f_ext(n) > 3 ORDER BY r.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ext(int); +DROP FUNCTION f_ext(int); + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; +DROP FUNCTION f_ret_record(); + +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + +-- Same nullable-side whole-row Var, but with outer rows that both match +-- and miss the (foreign x function) inner join. A multi-column function +-- RTE is used so that the reference is a genuine whole-row Var (a single +-- scalar-returning function would collapse to its lone column). This +-- exercises the THEN ROW(...) side of deparseColumnRef()'s whole-row CASE +-- (matched rows reconstruct the composite) as well as the NULL side +-- (missed rows), confirming the executor rebuilds the anonymous composite +-- correctly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; + +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); + +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); + +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml index b9e1b04463e..82e59e19a9e 100644 --- a/doc/src/sgml/postgres-fdw.sgml +++ b/doc/src/sgml/postgres-fdw.sgml @@ -1193,6 +1193,24 @@ CREATE SUBSCRIPTION my_subscription SERVER subscription_server PUBLICATION testp <literal>WHERE</literal> clauses. </para> + <para> + An <literal>INNER JOIN</literal> between a foreign table and a set-returning + function appearing as a <literal>FROM</literal>-list item can likewise be + pushed down: the function call is absorbed into the remote query so that + only rows matching the function's output are fetched. This is attempted + only when the function is <literal>IMMUTABLE</literal> (so evaluating it on + the remote server is guaranteed to produce the same result as evaluating + it locally), its arguments and any restriction clauses on it are + shippable, and none of the following disqualifying conditions applies: + the join type is not <literal>INNER</literal>; the function is used with + <literal>WITH ORDINALITY</literal>; the function returns a + <type>record</type> type without an accompanying column definition list; + or the function laterally references another relation at the same query + level. A function argument that is a parameter from an enclosing query + level is allowed and is transmitted to the remote server as a query + parameter. + </para> + <para> The query that is actually sent to the remote server for execution can be examined using <command>EXPLAIN VERBOSE</command>. diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 687e923c46c..4e70686ad07 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -746,6 +746,30 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if (OidIsValid(outer_rel->serverid) && + inner_rel->rtekind == RTE_FUNCTION) + { + /* + * One side is a foreign relation, the other side is a function RTE. + * If the function is IMMUTABLE, the FDW can absorb the function call + * into the remote query (the result is identical regardless of which + * server evaluates it). Let the FDW decide whether the join is + * actually shippable; here we just propagate the FDW routine so the + * FDW gets a chance. + */ + joinrel->serverid = outer_rel->serverid; + joinrel->userid = outer_rel->userid; + joinrel->useridiscurrent = outer_rel->useridiscurrent; + joinrel->fdwroutine = outer_rel->fdwroutine; + } + else if (OidIsValid(inner_rel->serverid) && + outer_rel->rtekind == RTE_FUNCTION) + { + joinrel->serverid = inner_rel->serverid; + joinrel->userid = inner_rel->userid; + joinrel->useridiscurrent = inner_rel->useridiscurrent; + joinrel->fdwroutine = inner_rel->fdwroutine; + } } /* -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
@ 2026-07-31 06:19                             ` Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2026-07-31 06:19 UTC (permalink / raw)
  To: Alexander Korotkov <aekorotkov@gmail.com>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Alexander Korotkov писал(а) 2026-07-31 00:19:
> On Tue, Jul 7, 2026 at 12:25 PM Alexander Pyhalov
> <a.pyhalov@postgrespro.ru> wrote:
>> 
>> Alexander Korotkov писал(а) 2026-07-06 17:11:
>> > Hi, Alexander!
>> >
>> > On Wed, May 20, 2026 at 1:17 PM Alexander Pyhalov
>> > <a.pyhalov@postgrespro.ru> wrote:
>> >> I've found another issue. The fact that in the new versions of the
>> >> patch
>> >> RTE RelOptInfo misses fdw_private seems to be unfortunate. For
>> >> example,
>> >> in the last version we haven't thought about classifying
>> >> baserestrictinfo. And if we do, we should pass fdw_private down to
>> >> foreign_expr_walker. Perhaps, we could attach it to RTE_FUNCTION rel
>> >> prior to calling classifyConditions(), but should we later set it back
>> >> to NULL? Another problem comes if we try to handle joins,  which can
>> >> crearte subqueries (like INNER/OUTER UNIQUE). In this case we should
>> >> somehow cook fpinfo for get_relation_column_alias_ids(). Attaching
>> >> patch
>> >> which tries to handle baserestrictinfos by passing fpinfo down to
>> >> foreign_expr_walker().
>> >
>> > I think passing fpinfo down to foreign_expr_walker() is the right
>> > approach, thank you.  Attaching it to RTE_FUNCTION rel, and reseting
>> > it back to NULL would create excessive state and potential source of
>> > bugs.  The only advantage is saving existing function signatures, but
>> > it doesn't worth it.
>> >
>> > Also, I don't think we need to care bout
>> > get_relation_column_alias_ids().  As we currently pushdown function
>> > only for inner joins, make_outerrel_subquery/make_innerrel_subquery
>> > are always false, lower_subquery_rels also wouldn't contain
>> > RTE_FUNCTION relid.
>> >  Therefore:
>> >
>> >  * In deparseFromExprForRel() for functional rel deparseRangeTblRef()
>> > is always called with make_subquery=false.
>> >  * is_subquery_var() returns false.
>> 
>> Well, at least current patch version classifies conditions correctly.
>> 
>> > Other changes I made:
>> >
>> > 1. In foreign_join_ok(), the function side's baserestrictinfo was
>> > classified against the joinrel fpinfo, whose
>> > server/shippable_extensions aren't set until merge_fdw_options() runs
>> > later — so extension-shippable quals would be misclassified as local
>> > and silently kill the pushdown. Now it: (a) copies
>> > shippable_extensions from the foreign side onto the stub, and (b)
>> > classifies against the stub (fpinfo_i/fpinfo_o, which already has
>> > server). Built-in quals like n > 3 were unaffected; this fixes the
>> > extension case.  I've added the test case for this.
>> >
>> > 2. Dropped unused funcid. The per-RTE metadata was a 3-element list
>> > (funcid, funcrettype, funccollation) but funcid was never read.
>> > Reduced to list_make2(funcrettype, funccollation); updated the
>> > consumer (linitial/lsecond) and both descriptive comments.
>> 
>> With funcid we could print actual function name in explain.
>> Now we print, for example,
>> 
>> Relations: ((public.distr1_part_3 d1_3) INNER JOIN 
>> (public.distr2_part_3
>> d2_3)) INNER JOIN (Function n)
>> 
>> If funcid is preserved, we could output actual function name instead 
>> of
>> alias. This is more similar to
>> how we show relation names. Attaching updated patch, which preserves
>> function names in explain.
>> 
>> After looking at it once more, I'm not convinced when we can get
>> not-FuncExpr in rtfunc->funcexpr.
>> So added more checks to function_rte_pushdown_ok() to avoid dealing 
>> with
>> such case.
> 
> I agree on your changes.  I've put some additional.
> 
> 1) Extracted initialization of stub fpinfo for function RTE into
> init_func_stub_fpinfo().  The stub now inherits fdw_startup_cost,
> fdw_tuple_cost, use_remote_estimate, fetch_size and async_capable from
> the foreign side, in addition to server and shippable_extensions.
> Without this, merge_fdw_options() and the cost estimator would pick up
> zeroed values of fdw_startup_cost and fdw_tuple_cost when the function
> RTEis on the outer side of the join, so the pushdown path appears to
> be artificially cheap.
> 2) Added a comment on the whole-row Var CASE WHEN wrapper in
> deparseColumnRef() explaining that it is a no-op under the current
> INNER-only policy but kept to stay correct for future outer-join and
> null-supply scenarios.  Please, check if you agree with this.
> 3) Documented the new pushdown case in postgres-fdw.sgml, listing the
> conditions under which a foreign-table x set-returning-function INNER
> join is absorbed into the remote query.
> 4) Added a regression test verifying that a STABLE (not IMMUTABLE)
> set- returning function is rejected for pushdown, alongside the
> existing VOLATILE-rejection test.
> 


Hi. I've updated comment a bit, as we currently have to handle NULL 
records correctly,
this is not a nice-to-have feature which we need for future changes to 
be more safe.
-- 
Best regards,
Alexander Pyhalov,
Postgres Professional

Attachments:

v13-0001-postgres_fdw-push-down-FUNCTION-RTE-into-foreign-joi.patch (text/x-diff, 87.2K) download From a67dbbd1aabce4eaf57211651b3c0a4ab57b088f Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Fri, 31 Jul 2026 07:54:37 +0300 Subject: [PATCH] postgres_fdw: push down FUNCTION RTE into foreign joins A foreign join planning hook now considers a (foreign-table x function-RTE) INNER join as a push-down candidate when the function expression is IMMUTABLE and otherwise shippable. The remote query absorbs the function call as a FROM-list item (e.g. unnest(...) AS f<rti>(c1, c2, ...)), so the foreign side returns only rows that match the function-produced set and the join executes entirely on the remote. An IMMUTABLE function gives the same result on any server, so the same function RTE can be a push-down candidate for several distinct foreign servers without semantic risk. To keep the planner state consistent across those independent attempts, the per-call stub fpinfo for the function side lives on the joinrel's PgFdwRelationInfo (new outer_func_fpinfo / inner_func_fpinfo), never on the function rel itself, and the function side is detected via rtekind rather than fdw_private. set_foreign_rel_properties() propagates fdwroutine onto a joinrel that pairs a foreign rel with an RTE_FUNCTION rel so GetForeignJoinPaths gets called; the FDW retains full control over whether to actually generate a path. deparseRangeTblRef and deparseColumnRef gain a FUNCTION-RTE branch that emits the function expression and resolves Vars to the generated column aliases. --- contrib/postgres_fdw/deparse.c | 156 ++++- .../postgres_fdw/expected/postgres_fdw.out | 654 ++++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 635 +++++++++++++++-- contrib/postgres_fdw/postgres_fdw.h | 12 + contrib/postgres_fdw/sql/postgres_fdw.sql | 274 ++++++++ doc/src/sgml/postgres-fdw.sgml | 18 + src/backend/optimizer/util/relnode.c | 24 + 7 files changed, 1716 insertions(+), 57 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 2dcc6c8af1b..b29adcfd785 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -68,6 +68,7 @@ typedef struct foreign_glob_cxt { PlannerInfo *root; /* global planner state */ RelOptInfo *foreignrel; /* the foreign relation we are planning for */ + PgFdwRelationInfo *fpinfo; /* the foreign server info we should rely on */ Relids relids; /* relids of base relations in the underlying * scan */ } foreign_glob_cxt; @@ -112,6 +113,7 @@ typedef struct deparse_expr_cxt appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno)) #define SUBQUERY_REL_ALIAS_PREFIX "s" #define SUBQUERY_COL_ALIAS_PREFIX "c" +#define FUNCTION_REL_ALIAS_PREFIX "f" /* * Functions to determine whether an expression can be evaluated safely on @@ -217,6 +219,7 @@ static void get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel, void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds) @@ -230,7 +233,7 @@ classifyConditions(PlannerInfo *root, { RestrictInfo *ri = lfirst_node(RestrictInfo, lc); - if (is_foreign_expr(root, baserel, ri->clause)) + if (is_foreign_expr(root, baserel, fpinfo, ri->clause)) *remote_conds = lappend(*remote_conds, ri); else *local_conds = lappend(*local_conds, ri); @@ -243,11 +246,11 @@ classifyConditions(PlannerInfo *root, bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr) { foreign_glob_cxt glob_cxt; foreign_loc_cxt loc_cxt; - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private); /* * Check that the expression consists of nodes that are safe to execute @@ -255,6 +258,7 @@ is_foreign_expr(PlannerInfo *root, */ glob_cxt.root = root; glob_cxt.foreignrel = baserel; + glob_cxt.fpinfo = fpinfo; /* * For an upper relation, use relids from its underneath scan relation, @@ -324,8 +328,8 @@ foreign_expr_walker(Node *node, if (node == NULL) return true; - /* May need server info from baserel's fdw_private struct */ - fpinfo = (PgFdwRelationInfo *) (glob_cxt->foreignrel->fdw_private); + /* May need server info from global context */ + fpinfo = glob_cxt->fpinfo; /* Set up inner_cxt for possible recursion to child nodes */ inner_cxt.collation = InvalidOid; @@ -2030,6 +2034,72 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, } } +/* + * Deparse a FUNCTION RTE absorbed into a foreign join. The function call(s) + * are emitted as a FROM-list item: + * + * <funcexpr> AS f<rti>(c1, c2, ..., cN) + * + * For multi-function RTEs (SQL ROWS FROM (f1(), f2(), ...)), each + * function call appears comma-separated inside ROWS FROM(...). Column + * aliases c1..cN cover the union of every function's columns, in the + * order they appear; that matches the column ordering of the RTE. + */ +static void +deparseFunctionRangeTblRef(StringInfo buf, PlannerInfo *root, + RelOptInfo *foreignrel, RelOptInfo *scanrel, + List **params_list) +{ + RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); + deparse_expr_cxt context; + ListCell *lc; + bool multi_func; + int total_cols = 0; + int i; + + Assert(rte->rtekind == RTE_FUNCTION); + Assert(!rte->funcordinality); + Assert(list_length(rte->functions) >= 1); + + multi_func = list_length(rte->functions) > 1; + + context.buf = buf; + context.root = root; + context.foreignrel = scanrel; + context.scanrel = scanrel; + context.params_list = params_list; + + if (multi_func) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (foreach_current_index(lc) > 0) + appendStringInfoString(buf, ", "); + deparseExpr((Expr *) rtfunc->funcexpr, &context); + total_cols += rtfunc->funccolcount; + } + + if (multi_func) + appendStringInfoChar(buf, ')'); + + /* Alias + generated column-name list. */ + appendStringInfo(buf, " %s%d", FUNCTION_REL_ALIAS_PREFIX, foreignrel->relid); + if (total_cols > 0) + { + appendStringInfoChar(buf, '('); + for (i = 1; i <= total_cols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + } +} + /* * Append FROM clause entry for the given relation into buf. * Conditions from lower-level SEMI-JOINs are appended to additional_conds @@ -2040,7 +2110,22 @@ deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **additional_conds, List **params_list) { - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + PgFdwRelationInfo *fpinfo; + + /* + * For a function RTE absorbed into a foreign join, deparse the function + * expression as a FROM-list item and return. The stub fpinfo set up by + * foreign_join_ok() may or may not be present here. + */ + if (foreignrel->rtekind == RTE_FUNCTION) + { + Assert(!make_subquery); + deparseFunctionRangeTblRef(buf, root, foreignrel, foreignrel, + params_list); + return; + } + + fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; /* Should only be called in these cases. */ Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel)); @@ -2712,6 +2797,67 @@ static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col) { + /* + * Function RTE columns: emit as f<varno>.c<varattno>, matching the + * aliases generated by deparseFunctionRangeTblRef(). A whole-row Var + * (varattno == 0) is rendered as ROW(f<varno>.c1, ..., f<varno>.c<N>) + * where N is the total column count of the function RTE (including all + * ROWS FROM (...) members). System attributes such as ctid have no + * meaning for function RTEs and are rejected. + */ + if (rte->rtekind == RTE_FUNCTION) + { + if (varattno == 0) + { + int ncols = list_length(rte->eref->colnames); + int i; + + /* + * The CASE WHEN wrapper distinguishes a NULL-supplied outer-join + * row (whole-row Var is NULL) from a row whose columns all happen + * to be NULL (whole-row Var is ROW(NULL, ..., NULL)). A bare + * ROW(...) would collapse those two cases to the latter. + * + * The current push-down policy only absorbs INNER joins with a + * function RTE, so the null-supplied case cannot arise from a + * remote outer join we emit ourselves. However we still have to + * emit the wrapper unconditionally: it is a no-op for INNER-join + * rows, but it keeps the deparsed SQL correct if a higher-level + * outer join propagates a NULL row through the foreign scan's tuple. + */ + if (qualify_col) + { + appendStringInfoString(buf, "CASE WHEN ("); + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfoString(buf, "*)::text IS NOT NULL THEN "); + } + + appendStringInfoString(buf, "ROW("); + for (i = 1; i <= ncols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d.%s%d", + FUNCTION_REL_ALIAS_PREFIX, varno, + SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + + if (qualify_col) + appendStringInfoString(buf, " END"); + return; + } + + if (varattno < 0) + elog(ERROR, + "system attribute reference to a function RTE is not supported in foreign join pushdown"); + + if (qualify_col) + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, varattno); + return; + } + /* We support fetching the remote side's CTID and OID. */ if (varattno == SelfItemPointerAttributeNumber) { diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index aaffcf31271..508618a26f4 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2885,6 +2885,660 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c (10 rows) ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: t1.c1, t1.c3 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1, t1.c3 + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r1."C 1", r1.c3 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{1,5,10,100}'::integer[]) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + c1 | c3 +-----+------- + 1 | 00001 + 5 | 00005 + 10 | 00010 + 100 | 00100 +(4 rows) + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Sort + Output: t1.c1 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1 + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.generate_series() g) + Remote SQL: SELECT r1."C 1" FROM ("S 1"."T 1" r1 INNER JOIN generate_series(1, 4) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + c1 +---- + 1 + 2 + 3 + 4 +(4 rows) + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on pg_catalog.generate_series g + Output: g.id + Function Call: generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +-- STABLE function must NOT be pushed down either: even though its result is +-- constant within one query, evaluating it on the remote server could yield +-- a different value than evaluating it locally. +CREATE FUNCTION f_stable(int) RETURNS SETOF int LANGUAGE plpgsql STABLE AS +$$ BEGIN RETURN QUERY SELECT generate_series(1, $1); END $$; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, f_stable(4) AS g(id) WHERE t1.c1 = g.id; + QUERY PLAN +--------------------------------------------------------- + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on public.f_stable g + Output: g.id + Function Call: f_stable(4) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +DROP FUNCTION f_stable(int); +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + QUERY PLAN +------------------------------------------------------------ + Hash Join + Output: t1.c1, u.ord + Hash Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" + -> Hash + Output: u.ord, u.id + -> Function Scan on pg_catalog.unnest u + Output: u.ord, u.id + Function Call: unnest('{1,5,10}'::integer[]) +(11 rows) + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: t1.c1, t2.c1 + Merge Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST + -> Sort + Output: t2.c1, u.id + Sort Key: t2.c1 + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{1,5,10,100}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(13 rows) + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: t1.c1, t2.c1 + Hash Cond: (t1.c1 = t2.c1) + -> Foreign Scan + Output: t1.c1, u.id + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r1."C 1", f3.c1 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r1."C 1" = f3.c1)))) + -> Hash + Output: t2.c1 + -> Foreign Scan on public.ft6 t2 + Output: t2.c1 + Remote SQL: SELECT c1 FROM "S 1"."T 4" +(12 rows) + +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: t1.c1, t2.c1 + Join Filter: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE ((c3 < '00010')) + -> Materialize + Output: t2.c1, u.id + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(12 rows) + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + n | a | b +---+---+----- + 2 | 2 | 102 + 3 | 3 | 103 + 4 | 4 | 104 +(3 rows) + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)) AND ((f1.c1 > 3)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); + QUERY PLAN +----------------------------------------------------------- + Hash Join + Output: n.n, r.a, r.b + Hash Cond: (r.a = n.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a, b FROM public.base_tbl_fn + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4}'::integer[]) + Filter: (n.n > f_local(3)) +(12 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +DROP FUNCTION f_local(int); +-- Check that a qual on the function RTE using a function from a shippable +-- extension is pushed down. plpgsql (not inlined) with the column as +-- argument (not const-folded) keeps the function call in the qual. +CREATE FUNCTION f_ext(int) RETURNS int AS $$ +BEGIN RETURN $1; END +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ext(int); +-- Force pushdown so the fixed-code plan is deterministically a Foreign +-- Scan; on the unfixed code the qual is classified local, the join is +-- refused, and the plan falls back to a local join instead. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and f_ext(n) > 3; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)) AND ((public.f_ext(f1.c1) > 3)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and f_ext(n) > 3 ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ext(int); +DROP FUNCTION f_ext(int); +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: s.* + Hash Cond: (rt.a = s.a) + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl_fn + -> Hash + Output: s.*, s.a + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() +(11 rows) + +DROP FUNCTION f_ret_record(); +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + a | b +----+----- + 23 | 123 + 24 | 999 + 25 | 125 +(3 rows) + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + a | b +----+--- + 24 | 5 +(1 row) + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + a | b | t +----+---+--------------------- + 24 | 7 | ("(2,3),(-2,-3)",1) +(1 row) + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: r.a, t.n, t.s + Sort Key: r.a + -> Foreign Scan + Output: r.a, t.n, t.s + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.generate_series()) t) + Remote SQL: SELECT r1.a, f2.c1, f2.c2 FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + a | n | s +---+---+---- + 3 | 3 | 11 + 6 | 6 | 12 + 9 | 9 | 13 +(3 rows) + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: ((t.*)::text), r.a + Sort Key: r.a + -> Foreign Scan + Output: (t.*)::text, r.a + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.generate_series()) t) + Remote SQL: SELECT CASE WHEN (f2.*)::text IS NOT NULL THEN ROW(f2.c1, f2.c2) END, r1.a FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + t | a +--------+--- + (3,11) | 3 + (6,12) | 6 + (9,13) | 9 +(3 rows) + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: u.*, ft5.c1, ft5.c2, ft4.c1, ft4.c2 + Relations: (public.ft5) LEFT JOIN ((public.ft4) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.unnest()) u)) + Remote SQL: SELECT CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END, r1.c1, r1.c2, r2.c1, r2.c2 FROM ("S 1"."T 4" r1 LEFT JOIN ("S 1"."T 3" r2 INNER JOIN ROWS FROM (unnest('{1,2}'::integer[]), unnest('{3,4}'::integer[])) f3(c1, c2) ON (((r2.c1 = f3.c1)))) ON (((r1.c1 = r2.c1)))) WHERE ((r1.c1 < 10)) ORDER BY r1.c1 ASC NULLS LAST +(4 rows) + +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + u | c1 | c2 | c1 | c2 +---+----+----+----+---- + | 3 | 4 | | + | 6 | 7 | | + | 9 | 10 | | +(3 rows) + +-- Same nullable-side whole-row Var, but with outer rows that both match +-- and miss the (foreign x function) inner join. A multi-column function +-- RTE is used so that the reference is a genuine whole-row Var (a single +-- scalar-returning function would collapse to its lone column). This +-- exercises the THEN ROW(...) side of deparseColumnRef()'s whole-row CASE +-- (matched rows reconstruct the composite) as well as the NULL side +-- (missed rows), confirming the executor rebuilds the anonymous composite +-- correctly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: l.a, t.* + Relations: (public.remote_tbl l) LEFT JOIN ((public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.unnest()) t)) + Remote SQL: SELECT r1.a, CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END FROM (public.base_tbl_fn r1 LEFT JOIN (public.base_tbl_fn r2 INNER JOIN ROWS FROM (unnest('{2,4}'::integer[]), unnest('{20,40}'::integer[])) f3(c1, c2) ON (((r2.a = f3.c1)))) ON (((r1.a = r2.a)))) WHERE ((r1.a < 6)) ORDER BY r1.a ASC NULLS LAST +(4 rows) + +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; + a | t +---+-------- + 1 | + 2 | (2,20) + 3 | + 4 | (4,40) + 5 | +(5 rows) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: s.a, s.b + Sort Key: s.a + CTE s + -> Nested Loop + Output: r1.a, r1.b + -> Foreign Scan on public.remote_tbl r1 + Output: r1.a, r1.b + Remote SQL: SELECT a, b FROM public.base_tbl_fn + -> Foreign Scan + Output: NULL::integer + Relations: (public.remote_tbl r2) INNER JOIN (public.f()) + Remote SQL: SELECT NULL FROM (public.base_tbl_fn r1 INNER JOIN public.f($1::integer) f2(c1) ON (TRUE)) LIMIT 1::bigint + -> CTE Scan on s + Output: s.a, s.b +(15 rows) + +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + a | b +----+----- + 1 | 101 + 2 | 102 + 3 | 103 + 4 | 104 + 5 | 105 + 6 | 106 + 7 | 107 + 8 | 108 + 9 | 109 + 10 | 110 + 11 | 111 + 12 | 112 + 13 | 113 + 14 | 114 + 15 | 115 + 16 | 116 + 17 | 117 + 18 | 118 + 19 | 119 + 20 | 120 + 21 | 121 + 22 | 122 + 23 | 123 + 24 | 7 + 25 | 125 + 26 | 126 + 27 | 127 + 28 | 128 + 29 | 129 + 30 | 130 +(30 rows) + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: r.a + Merge Cond: (t.n = r.a) + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]), generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Sort + Output: r.a + Sort Key: r.a + -> Foreign Scan on public.remote_tbl r + Output: r.a + Remote SQL: SELECT a FROM public.base_tbl_fn +(15 rows) + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Nested Loop + Output: r.a, t.x + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 3)) ORDER BY a ASC NULLS LAST + -> Function Scan on pg_catalog.unnest t + Output: t.x + Function Call: unnest(ARRAY[r.a]) +(8 rows) + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Merge Left Join + Output: r.a, t.n + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 5)) ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{1,2,3}'::integer[]) +(12 rows) + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + QUERY PLAN +-------------------------------------------------------------------------------- + Merge Semi Join + Output: r.a + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]) +(12 rows) + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 0ff4ec23164..de5680316e4 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -31,6 +31,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/appendinfo.h" +#include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" #include "optimizer/optimizer.h" @@ -88,6 +89,22 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of per-RTE function metadata, indexed by base RTI offset. Each + * element is either NULL (for non-RTE_FUNCTION rels in this scan) or a + * list of three-element lists (funcid, funcrettype, funccollation) -- one + * inner list per function in the RTE. Allows the executor to rebuild + * TupleDesc entries for whole-row references to function RTEs. + */ + FdwScanPrivateFunctions, + + /* + * Integer node: minimum base RT index covered by the scan, used to + * translate scan-local indexes to estate-rtable indexes after setrefs.c + * flattens rtables. + */ + FdwScanPrivateMinRTIndex, }; /* @@ -124,6 +141,11 @@ enum FdwModifyPrivateIndex * 2) Boolean flag showing if the remote query has a RETURNING clause * 3) Integer list of attribute numbers retrieved by RETURNING, if any * 4) Boolean flag showing if we set the command es_processed + * 5) Per-RTE function metadata (mirrors FdwScanPrivateFunctions; lets + * the executor rebuild TupleDesc entries for whole-row Vars over + * function RTEs absorbed into a foreign join) + * 6) Integer node: minimum base RT index of the scan (mirrors + * FdwScanPrivateMinRTIndex) */ enum FdwDirectModifyPrivateIndex { @@ -135,6 +157,10 @@ enum FdwDirectModifyPrivateIndex FdwDirectModifyPrivateRetrievedAttrs, /* set-processed flag (as a Boolean node) */ FdwDirectModifyPrivateSetProcessed, + /* Per-RTE function metadata, indexed by base RTI offset */ + FdwDirectModifyPrivateFunctions, + /* Integer node: minimum base RT index in the scan */ + FdwDirectModifyPrivateMinRTIndex, }; /* @@ -740,6 +766,9 @@ static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, static List *get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel); static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, Path *epq_path, List *restrictlist); static void add_foreign_grouping_paths(PlannerInfo *root, @@ -893,7 +922,7 @@ postgresGetForeignRelSize(PlannerInfo *root, * Identify which baserestrictinfo clauses can be sent to the remote * server and which can't. */ - classifyConditions(root, baserel, baserel->baserestrictinfo, + classifyConditions(root, baserel, fpinfo, baserel->baserestrictinfo, &fpinfo->remote_conds, &fpinfo->local_conds); /* @@ -1297,7 +1326,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1373,7 +1402,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1513,7 +1542,7 @@ postgresGetForeignPlan(PlannerInfo *root, remote_exprs = lappend(remote_exprs, rinfo->clause); else if (list_member_ptr(fpinfo->local_conds, rinfo)) local_exprs = lappend(local_exprs, rinfo->clause); - else if (is_foreign_expr(root, foreignrel, rinfo->clause)) + else if (is_foreign_expr(root, foreignrel, fpinfo, rinfo->clause)) remote_exprs = lappend(remote_exprs, rinfo->clause); else local_exprs = lappend(local_exprs, rinfo->clause); @@ -1634,9 +1663,26 @@ postgresGetForeignPlan(PlannerInfo *root, fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(fpinfo->fetch_size)); + + /* + * Position FdwScanPrivateRelations: either the EXPLAIN relation string + * (joins/upper rels) or a NULL placeholder, so that subsequent indexes + * stay valid for the base-rel scan case. + */ if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + /* + * FdwScanPrivateFunctions / FdwScanPrivateMinRTIndex carry the metadata + * the executor needs to rebuild TupleDesc entries for whole-row Vars + * pointing at RTE_FUNCTION rels absorbed into the foreign scan. + */ + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + fdw_private = lappend(fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1657,9 +1703,15 @@ postgresGetForeignPlan(PlannerInfo *root, /* * Construct a tuple descriptor for the scan tuples handled by a foreign join. + * + * 'rtfuncdata' is the FdwScanPrivateFunctions list saved at plan time, and + * 'rtoffset' is the difference between the executor's RT indexes and the + * scan-local RT indexes captured in that list. Both may be 0/NIL when the + * scan has no RTE_FUNCTION dependents. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, + List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1695,13 +1747,67 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * A whole-row Var points at a FUNCTION RTE absorbed into the + * foreign join. Synthesize an anonymous composite TupleDesc from + * the per-function return-type metadata we saved at plan time; + * the deparser emits these as ROW(f<rti>.c1, f<rti>.c2, ...). + * + * For an upperrel scan (the only path that reaches here) + * postgresGetForeignPlan always builds rtfuncdata via + * get_functions_data(), so it is never NIL; the per-RTE slot for + * the function RTE referenced by this Var must likewise be + * populated. + */ + List *funcdata; + TupleDesc rte_tupdesc; + int num_funcs; + int attnum; + ListCell *lc1, + *lc2; + + Assert(rtfuncdata != NIL); + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + Assert(funcdata != NIL); + num_funcs = list_length(funcdata); + Assert(num_funcs == list_length(rte->eref->colnames)); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc1, funcdata, lc2, rte->eref->colnames) + { + List *fdata = lfirst_node(List, lc1); + char *colname = strVal(lfirst(lc2)); + Oid funcrettype; + Oid funccollation; + + funcrettype = lsecond_node(Integer, fdata)->ival; + funccollation = lthird_node(Integer, fdata)->ival; + + /* get_functions_data() already validated the return type. */ + Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funccollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1737,14 +1843,30 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. For a join, scan the base relids until we + * find an RTE_RELATION (the foreign-table side); ignore any RTE_FUNCTION + * absorbed into the join, which contributes no relation OID to look up. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); + rte = NULL; if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte != NULL && rte->rtekind == RTE_RELATION) + break; + rte = NULL; + } + if (rte == NULL) + elog(ERROR, "could not locate a foreign relation RTE in foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1787,8 +1909,19 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwScanPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwScanPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, + rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2741,7 +2874,7 @@ postgresPlanDirectModify(PlannerInfo *root, if (attno <= InvalidAttrNumber) /* shouldn't happen */ elog(ERROR, "system-column update is not supported"); - if (!is_foreign_expr(root, foreignrel, (Expr *) tle->expr)) + if (!is_foreign_expr(root, foreignrel, fpinfo, (Expr *) tle->expr)) return false; } } @@ -2828,6 +2961,10 @@ postgresPlanDirectModify(PlannerInfo *root, makeBoolean((retrieved_attrs != NIL)), retrieved_attrs, makeBoolean(plan->canSetTag)); + fscan->fdw_private = lappend(fscan->fdw_private, + get_functions_data(root, foreignrel)); + fscan->fdw_private = lappend(fscan->fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Update the foreign-join-related fields. @@ -2941,7 +3078,26 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + /* + * DirectModify on a foreign join: use the per-RTE function + * metadata saved at plan time so a whole-row Var pointing at a + * function RTE absorbed into the join can be rebuilt into a + * usable TupleDesc (e.g. RETURNING t for a join with UNNEST(..., + * ...) AS t(bx, i)). + */ + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + + tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -3054,7 +3210,8 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_length(fdw_private) > FdwScanPrivateRelations && + list_nth(fdw_private, FdwScanPrivateRelations) != NULL) { StringInfoData relations; char *rawrelations; @@ -3104,25 +3261,90 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); - Assert(rte->rtekind == RTE_RELATION); - /* This logic should agree with explain.c's ExplainTargetRel */ - relname = get_rel_name(rte->relid); - if (es->verbose) - { - char *namespace; - namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); - appendStringInfo(&relations, "%s.%s", - quote_identifier(namespace), - quote_identifier(relname)); + if (rte->rtekind == RTE_FUNCTION) + { + List *rtfuncdata = list_nth(fdw_private, FdwScanPrivateFunctions); + List *funcdata; + bool multi_func; + bool first = true; + ListCell *lc; + + funcdata = list_nth(rtfuncdata, rti - rtoffset); + + multi_func = list_length(funcdata) > 1; + + if (multi_func) + appendStringInfoString(&relations, "ROWS FROM ("); + + foreach(lc, funcdata) + { + List *funcinfo; + Oid funcid; + + + if (!first) + appendStringInfoString(&relations, ", "); + + funcinfo = (List *) lfirst(lc); + + funcid = linitial_node(Integer, funcinfo)->ival; + /* Checked by function_rte_pushdown_ok() */ + Assert(OidIsValid(funcid)); + + /* Match RTE_RELATION behavior */ + relname = get_func_name(funcid); + if (relname == NULL) + elog(ERROR, "cache lookup failed for function %u", funcid); + if (es->verbose) + { + char *namespace; + Oid nsoid = get_func_namespace(funcid); + + namespace = get_namespace_name(nsoid); + if (namespace == NULL) + elog(ERROR, "cache lookup failed for namespace %u", nsoid); + + appendStringInfo(&relations, "%s.%s()", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfo(&relations, "%s()", quote_identifier(relname)); + + first = false; + } + /* Close ROWS FROM */ + if (multi_func) + appendStringInfoChar(&relations, ')'); } else - appendStringInfoString(&relations, - quote_identifier(relname)); + { + Assert(rte->rtekind == RTE_RELATION); + + /* + * This logic should agree with explain.c's + * ExplainTargetRel + */ + relname = get_rel_name(rte->relid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); + appendStringInfo(&relations, "%s.%s", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfoString(&relations, + quote_identifier(relname)); + } + refname = (char *) list_nth(es->rtable_names, rti - 1); if (refname == NULL) refname = rte->eref->aliasname; - if (strcmp(refname, relname) != 0) + if (relname == NULL || strcmp(refname, relname) != 0) appendStringInfo(&relations, " %s", quote_identifier(refname)); } @@ -3346,7 +3568,7 @@ estimate_path_cost_size(PlannerInfo *root, * param_join_conds might contain both clauses that are safe to send * across, and clauses that aren't. */ - classifyConditions(root, foreignrel, param_join_conds, + classifyConditions(root, foreignrel, fpinfo, param_join_conds, &remote_param_join_conds, &local_param_join_conds); /* Build the list of columns to be fetched from the foreign server. */ @@ -3479,8 +3701,17 @@ estimate_path_cost_size(PlannerInfo *root, /* For join we expect inner and outer relations set */ Assert(fpinfo->innerrel && fpinfo->outerrel); - fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; + /* + * For a FUNCTION RTE absorbed into the join, use the stub fpinfo + * we built in foreign_join_ok(), since the function rel itself + * has no fdw_private. + */ + fpinfo_i = fpinfo->inner_func_fpinfo ? + fpinfo->inner_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; + fpinfo_o = fpinfo->outer_func_fpinfo ? + fpinfo->outer_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; /* Estimate of number of rows in cross product */ nrows = fpinfo_i->rows * fpinfo_o->rows; @@ -6619,6 +6850,250 @@ semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, return ok; } +/* + * get_base_relids + * Return the set of base relids referenced by a foreign scan rel. + * + * For an upper rel we use the all-query relids minus the outer joins; + * otherwise the rel's own relids minus the outer joins. The result matches + * the relids that create_foreignscan_plan() ultimately uses for + * ForeignScan.fs_base_relids, so it is suitable for any tagging we want to + * store via plan-private state. + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + return bms_difference(relids, root->outer_join_rels); +} + +/* + * get_min_base_rti + * Lowest base RT index in the foreign scan rel. + * + * After setrefs.c flattens the rtable, the scan-local indexes saved in + * plan-private data can be translated to estate indexes by adding + * (ForeignScan.fs_base_relids min - this value). Captured at plan time + * because create_foreignscan_plan() computes the same value internally. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + +/* + * get_functions_data + * Build the per-RTE function metadata list saved as + * FdwScanPrivateFunctions. + * + * The result list is indexed by base RT index relative to the lowest base + * RT index of the scan. Each element is either NULL (for non-RTE_FUNCTION + * base rels in this scan) or a List of List of two Integer nodes: + * (funcrettype, funccollation) -- one inner list per RangeTblFunction. + * + * Only RTE_FUNCTION relids actually appearing in the foreign scan's + * fs_base_relids contribute; others are placeholders so that the consumer + * can index into the result by RTI offset. + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + Relids fscan_relids = get_base_relids(root, rel); + int i; + + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + List *funcdata = NIL; + ListCell *lc; + + if (rte == NULL || i == 0 || + !bms_is_member(i, fscan_relids) || + rte->rtekind != RTE_FUNCTION) + { + rtfuncdata = lappend(rtfuncdata, NULL); + continue; + } + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + Oid funcrettype; + Oid funccollation; + TupleDesc tupdesc; + Oid funcid; + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + /* + * function_rte_pushdown_ok() already rejected any function that + * doesn't return a well-defined scalar type, so this is a mere + * cross-check. + */ + Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID); + + funccollation = exprCollation(rtfunc->funcexpr); + + funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid; + + funcdata = lappend(funcdata, + list_make3(makeInteger(funcid), + makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + + return rtfuncdata; +} + +/* + * init_func_stub_fpinfo + * Build a stub PgFdwRelationInfo for a FUNCTION RTE that is being + * absorbed into a foreign join. + * + * A function RTE has no fdw_private of its own, but the joinrel-level cost + * estimator, deparser and merge_fdw_options() all read server-level options + * from the "outer" fpinfo unconditionally. So the stub must carry the same + * server, shippable_extensions, and cost-related options as the real foreign + * side of the join; otherwise the pushdown path is judged against zeroed + * fdw_startup_cost/fdw_tuple_cost/etc. and looks artificially cheap. + * + * The stub is meaningful only for the specific (foreign, function) pairing + * that produced it; it must live on the joinrel's PgFdwRelationInfo, never + * on the function rel's fdw_private, since the same function RTE may pair + * with different foreign servers in sibling joinrels. + */ +static PgFdwRelationInfo * +init_func_stub_fpinfo(const PgFdwRelationInfo *fpinfo_foreign, + RelOptInfo *funcrel) +{ + PgFdwRelationInfo *stub = palloc0_object(PgFdwRelationInfo); + + stub->pushdown_safe = true; + + /* Server-level options, inherited from the foreign side. */ + stub->server = fpinfo_foreign->server; + stub->shippable_extensions = fpinfo_foreign->shippable_extensions; + stub->fdw_startup_cost = fpinfo_foreign->fdw_startup_cost; + stub->fdw_tuple_cost = fpinfo_foreign->fdw_tuple_cost; + stub->use_remote_estimate = fpinfo_foreign->use_remote_estimate; + stub->fetch_size = fpinfo_foreign->fetch_size; + stub->async_capable = fpinfo_foreign->async_capable; + + /* Function-side identity and estimates from the local planner. */ + stub->relation_name = psprintf("%u", funcrel->relid); + stub->rows = funcrel->rows; + stub->width = funcrel->reltarget->width; + stub->retrieved_rows = funcrel->rows; + stub->rel_startup_cost = 0; + stub->rel_total_cost = 0; + + return stub; +} + +/* + * Check if a relation is a FUNCTION RTE that can be absorbed into a remote + * join. Every function in the RTE must + * + * - return a well-defined scalar type -- we don't ship records/composite + * since the remote server cannot reconstruct a column definition list + * and our deparser does not emit one; + * - have a shippable expression with no mutable subnodes -- is_foreign_expr() + * rejects volatile/stable functions through contain_mutable_functions(), + * so the IMMUTABLE-only restriction is implicit; + * - not contain SubPlans -- we'd otherwise need to ship sub-results to + * the remote, which we do not implement. + * + * WITH ORDINALITY is not supported yet. + */ +static bool +function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel, + RelOptInfo *fdwrel) +{ + RangeTblEntry *rte; + ListCell *lc; + + if (rel->rtekind != RTE_FUNCTION) + return false; + rte = planner_rt_fetch(rel->relid, root); + + /* + * build_simple_rel() copies rtekind straight from the RTE, so for a base + * rel rel->rtekind always matches the RTE's; the check above is therefore + * sufficient. + */ + Assert(rte->rtekind == RTE_FUNCTION); + + if (rte->funcordinality) + return false; + + /* + * Reject up-front any function RTE that lateral-references another + * relation: foreign-join push-down would need to parameterise the remote + * query per outer row, which we don't support, and even considering the + * path is expensive on the planner side. The surrounding lateral_relids + * check in postgresGetForeignJoinPaths() would normally bail out for the + * joinrel, but doing the check here avoids walking the function + * expression entirely. + * + * Note this rejects only lateral references to another relation at the + * same query level. A function argument referencing an outer query level + * (e.g. f(outer.col) inside a subquery) is a different case: it becomes a + * PARAM_EXEC Param, the function rel's lateral_relids is empty, and + * foreign_expr_walker() intentionally treats PARAM_EXEC as shippable. The + * remote query then carries a parameter placeholder, and postgres_fdw's + * ordinary parameter machinery re-sends it on each rescan -- i.e. it + * works as a normal parameterized foreign scan, which is fine. + */ + if (!bms_is_empty(rel->lateral_relids)) + return false; + + Assert(list_length(rte->functions) >= 1); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + TypeFuncClass functypclass; + Oid funcrettype; + TupleDesc tupdesc; + + /* Refuse to deal with strange funcexprs */ + if (!IsA(rtfunc->funcexpr, FuncExpr)) + return false; + + if (!OidIsValid(((FuncExpr *) rtfunc->funcexpr)->funcid)) + return false; + + functypclass = get_expr_result_type(rtfunc->funcexpr, + &funcrettype, &tupdesc); + if (functypclass != TYPEFUNC_SCALAR) + return false; + if (!OidIsValid(funcrettype) || + funcrettype == RECORDOID || + funcrettype == VOIDOID) + return false; + + if (contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, fdwrel, fdwrel->fdw_private, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -6634,6 +7109,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; + bool outer_is_function = false; + bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -6652,15 +7129,68 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, return false; /* - * If either of the joining relations is marked as unsafe to pushdown, the - * join can not be pushed down. + * Detect mixed (foreign x function-RTE) cases. Only INNER joins are + * supported initially. We dispatch on rtekind here so that the same + * function RTE can be absorbed into joins on multiple foreign servers + * (each call gets its own stub fpinfo and rechecks shippability for the + * specific server). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && + (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && + fpinfo_o->pushdown_safe && + function_rte_pushdown_ok(root, innerrel, outerrel)) + { + inner_is_function = true; + } + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) + { + outer_is_function = true; + } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } + + /* + * If one side is a function RTE, allocate a stub fpinfo so the rest of + * this function and the cost estimator can treat it uniformly. We hand + * the stub to the joinrel's deparser via the same path the foreign side + * uses, but we never permanently attach it to the function rel's + * fdw_private (different joinrels may pair the same function RTE with + * different foreign servers). + */ + if (inner_is_function) + { + fpinfo_i = init_func_stub_fpinfo(fpinfo_o, innerrel); + + /* + * Classify the function rel's own baserestrictinfo now, so that the + * local_conds check below can bail out if any of it is unshippable. + * We classify against the stub, not the joinrel's fpinfo, because the + * latter's server/shippable_extensions aren't populated until + * merge_fdw_options() runs further down. + */ + classifyConditions(root, innerrel, fpinfo_i, innerrel->baserestrictinfo, + &fpinfo_i->remote_conds, &fpinfo_i->local_conds); + fpinfo->inner_func_fpinfo = fpinfo_i; + } + else if (outer_is_function) + { + fpinfo_o = init_func_stub_fpinfo(fpinfo_i, outerrel); + + /* See the comment in the inner_is_function branch above. */ + classifyConditions(root, outerrel, fpinfo_o, outerrel->baserestrictinfo, + &fpinfo_o->remote_conds, &fpinfo_o->local_conds); + fpinfo->outer_func_fpinfo = fpinfo_o; + } /* * If joining relations have local conditions, those conditions are @@ -6698,7 +7228,7 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, foreach(lc, extra->restrictlist) { RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc); - bool is_remote_clause = is_foreign_expr(root, joinrel, + bool is_remote_clause = is_foreign_expr(root, joinrel, fpinfo, rinfo->clause); if (IS_OUTER_JOIN(jointype) && @@ -7396,7 +7926,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * If any GROUP BY expression is not shippable, then we cannot * push down aggregation to the foreign server. */ - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; /* @@ -7424,7 +7954,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * Non-grouping expression we need to compute. Can we ship it * as-is to the foreign server? */ - if (is_foreign_expr(root, grouped_rel, expr) && + if (is_foreign_expr(root, grouped_rel, fpinfo, expr) && !is_foreign_param(root, grouped_rel, expr)) { /* Yes, so add to tlist as-is; OK to suppress duplicates */ @@ -7444,7 +7974,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * don't have to check is_foreign_param, since that certainly * won't return true for any such expression.) */ - if (!is_foreign_expr(root, grouped_rel, (Expr *) aggvars)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, (Expr *) aggvars)) return false; /* @@ -7496,7 +8026,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, grouped_rel->relids, NULL, NULL); - if (is_foreign_expr(root, grouped_rel, expr)) + if (is_foreign_expr(root, grouped_rel, fpinfo, expr)) fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo); else fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo); @@ -7533,7 +8063,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, */ if (IsA(expr, Aggref)) { - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; tlist = add_to_flat_tlist(tlist, list_make1(expr)); @@ -8046,8 +8576,8 @@ add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel, * Also, the LIMIT/OFFSET cannot be pushed down, if their expressions are * not safe to remote. */ - if (!is_foreign_expr(root, input_rel, (Expr *) parse->limitOffset) || - !is_foreign_expr(root, input_rel, (Expr *) parse->limitCount)) + if (!is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitOffset) || + !is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitCount)) return; /* Safe to push down */ @@ -8693,7 +9223,7 @@ find_em_for_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel) if (bms_is_subset(em->em_relids, rel->relids) && !bms_is_empty(em->em_relids) && bms_is_empty(bms_intersect(em->em_relids, fpinfo->hidden_subquery_rels)) && - is_foreign_expr(root, rel, em->em_expr)) + is_foreign_expr(root, rel, fpinfo, em->em_expr)) return em; } @@ -8715,6 +9245,7 @@ EquivalenceMember * find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel) { + PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private; PathTarget *target = rel->reltarget; ListCell *lc1; int i; @@ -8764,7 +9295,7 @@ find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, continue; /* Check that expression (including relabels!) is shippable */ - if (is_foreign_expr(root, rel, em->em_expr)) + if (is_foreign_expr(root, rel, fpinfo, em->em_expr)) return em; } diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..da7da1c2ea9 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -106,6 +106,16 @@ typedef struct PgFdwRelationInfo /* joinclauses contains only JOIN/ON conditions for an outer join */ List *joinclauses; /* List of RestrictInfo */ + /* + * If a FUNCTION RTE was absorbed into this join, these point at the stub + * PgFdwRelationInfo for the function side (paired with the + * outerrel/innerrel), so the cost estimator and deparser can find it + * without consulting the function rel's fdw_private. At most one of + * outer_func_fpinfo/inner_func_fpinfo is set. + */ + struct PgFdwRelationInfo *outer_func_fpinfo; + struct PgFdwRelationInfo *inner_func_fpinfo; + /* Upper relation information */ UpperRelationKind stage; @@ -183,11 +193,13 @@ extern char *pgfdw_application_name; /* in deparse.c */ extern void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds); extern bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr); extern bool is_foreign_param(PlannerInfo *root, RelOptInfo *baserel, diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 267d3c1a7e7..f218471947d 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -790,6 +790,280 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + +-- STABLE function must NOT be pushed down either: even though its result is +-- constant within one query, evaluating it on the remote server could yield +-- a different value than evaluating it locally. +CREATE FUNCTION f_stable(int) RETURNS SETOF int LANGUAGE plpgsql STABLE AS +$$ BEGIN RETURN QUERY SELECT generate_series(1, $1); END $$; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, f_stable(4) AS g(id) WHERE t1.c1 = g.id; +DROP FUNCTION f_stable(int); + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); + +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + +DROP FUNCTION f_local(int); + +-- Check that a qual on the function RTE using a function from a shippable +-- extension is pushed down. plpgsql (not inlined) with the column as +-- argument (not const-folded) keeps the function call in the qual. +CREATE FUNCTION f_ext(int) RETURNS int AS $$ +BEGIN RETURN $1; END +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ext(int); +-- Force pushdown so the fixed-code plan is deterministically a Foreign +-- Scan; on the unfixed code the qual is classified local, the join is +-- refused, and the plan falls back to a local join instead. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and f_ext(n) > 3; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and f_ext(n) > 3 ORDER BY r.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ext(int); +DROP FUNCTION f_ext(int); + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; +DROP FUNCTION f_ret_record(); + +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + +-- Same nullable-side whole-row Var, but with outer rows that both match +-- and miss the (foreign x function) inner join. A multi-column function +-- RTE is used so that the reference is a genuine whole-row Var (a single +-- scalar-returning function would collapse to its lone column). This +-- exercises the THEN ROW(...) side of deparseColumnRef()'s whole-row CASE +-- (matched rows reconstruct the composite) as well as the NULL side +-- (missed rows), confirming the executor rebuilds the anonymous composite +-- correctly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; + +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); + +EXPLAIN (VERBOSE, COSTS OFF) +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; +WITH s AS MATERIALIZED (SELECT r1.* FROM remote_tbl r1 +JOIN LATERAL +(SELECT r2.a FROM remote_tbl r2, f(r1.a) LIMIT 1) s +ON true) +SELECT * FROM s ORDER BY 1; + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); + +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml index b81f33732fb..cfb19f823ca 100644 --- a/doc/src/sgml/postgres-fdw.sgml +++ b/doc/src/sgml/postgres-fdw.sgml @@ -1191,6 +1191,24 @@ CREATE SUBSCRIPTION my_subscription SERVER subscription_server PUBLICATION testp <literal>WHERE</literal> clauses. </para> + <para> + An <literal>INNER JOIN</literal> between a foreign table and a set-returning + function appearing as a <literal>FROM</literal>-list item can likewise be + pushed down: the function call is absorbed into the remote query so that + only rows matching the function's output are fetched. This is attempted + only when the function is <literal>IMMUTABLE</literal> (so evaluating it on + the remote server is guaranteed to produce the same result as evaluating + it locally), its arguments and any restriction clauses on it are + shippable, and none of the following disqualifying conditions applies: + the join type is not <literal>INNER</literal>; the function is used with + <literal>WITH ORDINALITY</literal>; the function returns a + <type>record</type> type without an accompanying column definition list; + or the function laterally references another relation at the same query + level. A function argument that is a parameter from an enclosing query + level is allowed and is transmitted to the remote server as a query + parameter. + </para> + <para> The query that is actually sent to the remote server for execution can be examined using <command>EXPLAIN VERBOSE</command>. diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 3fc2c2f71d0..f21ae1baeb2 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -746,6 +746,30 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if (OidIsValid(outer_rel->serverid) && + inner_rel->rtekind == RTE_FUNCTION) + { + /* + * One side is a foreign relation, the other side is a function RTE. + * If the function is IMMUTABLE, the FDW can absorb the function call + * into the remote query (the result is identical regardless of which + * server evaluates it). Let the FDW decide whether the join is + * actually shippable; here we just propagate the FDW routine so the + * FDW gets a chance. + */ + joinrel->serverid = outer_rel->serverid; + joinrel->userid = outer_rel->userid; + joinrel->useridiscurrent = outer_rel->useridiscurrent; + joinrel->fdwroutine = outer_rel->fdwroutine; + } + else if (OidIsValid(inner_rel->serverid) && + outer_rel->rtekind == RTE_FUNCTION) + { + joinrel->serverid = inner_rel->serverid; + joinrel->userid = inner_rel->userid; + joinrel->useridiscurrent = inner_rel->useridiscurrent; + joinrel->fdwroutine = inner_rel->fdwroutine; + } } /* -- 2.43.0
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-08-15 00:49                               ` Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Korotkov @ 2026-08-15 00:49 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi!

> Hi. I've updated comment a bit, as we currently have to handle NULL
> records correctly,
> this is not a nice-to-have feature which we need for future changes to
> be more safe.

Thank you. I've further improved that comment.  Also, I've revised the
cost calculation in init_func_stub_fpinfo() to reflect the cost of the
function execution on the remote side.  I have to edit the regression
test query to reliably exercise the pushdown.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

v14-0001-postgres_fdw-push-down-FUNCTION-RTE-into-foreign.patch (application/octet-stream, 87.6K) download From 46d242ad85a7ae1712f3b907aeae7da8ad1e2184 Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Fri, 31 Jul 2026 07:54:37 +0300 Subject: [PATCH v14] postgres_fdw: push down FUNCTION RTE into foreign joins A foreign join planning hook now considers a (foreign-table x function-RTE) INNER join as a push-down candidate when the function expression is IMMUTABLE and otherwise shippable. The remote query absorbs the function call as a FROM-list item (e.g. unnest(...) AS f<rti>(c1, c2, ...)), so the foreign side returns only rows that match the function-produced set and the join executes entirely on the remote. An IMMUTABLE function gives the same result on any server, so the same function RTE can be a push-down candidate for several distinct foreign servers without semantic risk. To keep the planner state consistent across those independent attempts, the per-call stub fpinfo for the function side lives on the joinrel's PgFdwRelationInfo (new outer_func_fpinfo / inner_func_fpinfo), never on the function rel itself, and the function side is detected via rtekind rather than fdw_private. set_foreign_rel_properties() propagates fdwroutine onto a joinrel that pairs a foreign rel with an RTE_FUNCTION rel so GetForeignJoinPaths gets called; the FDW retains full control over whether to actually generate a path. deparseRangeTblRef and deparseColumnRef gain a FUNCTION-RTE branch that emits the function expression and resolves Vars to the generated column aliases. --- contrib/postgres_fdw/deparse.c | 157 ++++- .../postgres_fdw/expected/postgres_fdw.out | 627 +++++++++++++++++ contrib/postgres_fdw/postgres_fdw.c | 641 ++++++++++++++++-- contrib/postgres_fdw/postgres_fdw.h | 12 + contrib/postgres_fdw/sql/postgres_fdw.sql | 274 ++++++++ doc/src/sgml/postgres-fdw.sgml | 18 + src/backend/optimizer/util/relnode.c | 25 + 7 files changed, 1697 insertions(+), 57 deletions(-) diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c index 9d1932230e7..673b678826c 100644 --- a/contrib/postgres_fdw/deparse.c +++ b/contrib/postgres_fdw/deparse.c @@ -68,6 +68,7 @@ typedef struct foreign_glob_cxt { PlannerInfo *root; /* global planner state */ RelOptInfo *foreignrel; /* the foreign relation we are planning for */ + PgFdwRelationInfo *fpinfo; /* the foreign server info we should rely on */ Relids relids; /* relids of base relations in the underlying * scan */ } foreign_glob_cxt; @@ -112,6 +113,7 @@ typedef struct deparse_expr_cxt appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno)) #define SUBQUERY_REL_ALIAS_PREFIX "s" #define SUBQUERY_COL_ALIAS_PREFIX "c" +#define FUNCTION_REL_ALIAS_PREFIX "f" /* * Functions to determine whether an expression can be evaluated safely on @@ -217,6 +219,7 @@ static void get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel, void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds) @@ -230,7 +233,7 @@ classifyConditions(PlannerInfo *root, { RestrictInfo *ri = lfirst_node(RestrictInfo, lc); - if (is_foreign_expr(root, baserel, ri->clause)) + if (is_foreign_expr(root, baserel, fpinfo, ri->clause)) *remote_conds = lappend(*remote_conds, ri); else *local_conds = lappend(*local_conds, ri); @@ -243,11 +246,11 @@ classifyConditions(PlannerInfo *root, bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr) { foreign_glob_cxt glob_cxt; foreign_loc_cxt loc_cxt; - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private); /* * Check that the expression consists of nodes that are safe to execute @@ -255,6 +258,7 @@ is_foreign_expr(PlannerInfo *root, */ glob_cxt.root = root; glob_cxt.foreignrel = baserel; + glob_cxt.fpinfo = fpinfo; /* * For an upper relation, use relids from its underneath scan relation, @@ -324,8 +328,8 @@ foreign_expr_walker(Node *node, if (node == NULL) return true; - /* May need server info from baserel's fdw_private struct */ - fpinfo = (PgFdwRelationInfo *) (glob_cxt->foreignrel->fdw_private); + /* May need server info from global context */ + fpinfo = glob_cxt->fpinfo; /* Set up inner_cxt for possible recursion to child nodes */ inner_cxt.collation = InvalidOid; @@ -2050,6 +2054,72 @@ deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, } } +/* + * Deparse a FUNCTION RTE absorbed into a foreign join. The function call(s) + * are emitted as a FROM-list item: + * + * <funcexpr> AS f<rti>(c1, c2, ..., cN) + * + * For multi-function RTEs (SQL ROWS FROM (f1(), f2(), ...)), each + * function call appears comma-separated inside ROWS FROM(...). Column + * aliases c1..cN cover the union of every function's columns, in the + * order they appear; that matches the column ordering of the RTE. + */ +static void +deparseFunctionRangeTblRef(StringInfo buf, PlannerInfo *root, + RelOptInfo *foreignrel, RelOptInfo *scanrel, + List **params_list) +{ + RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root); + deparse_expr_cxt context; + ListCell *lc; + bool multi_func; + int total_cols = 0; + int i; + + Assert(rte->rtekind == RTE_FUNCTION); + Assert(!rte->funcordinality); + Assert(list_length(rte->functions) >= 1); + + multi_func = list_length(rte->functions) > 1; + + context.buf = buf; + context.root = root; + context.foreignrel = scanrel; + context.scanrel = scanrel; + context.params_list = params_list; + + if (multi_func) + appendStringInfoString(buf, "ROWS FROM ("); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + + if (foreach_current_index(lc) > 0) + appendStringInfoString(buf, ", "); + deparseExpr((Expr *) rtfunc->funcexpr, &context); + total_cols += rtfunc->funccolcount; + } + + if (multi_func) + appendStringInfoChar(buf, ')'); + + /* Alias + generated column-name list. */ + appendStringInfo(buf, " %s%d", FUNCTION_REL_ALIAS_PREFIX, foreignrel->relid); + if (total_cols > 0) + { + appendStringInfoChar(buf, '('); + for (i = 1; i <= total_cols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + } +} + /* * Append FROM clause entry for the given relation into buf. * Conditions from lower-level SEMI-JOINs are appended to additional_conds @@ -2060,7 +2130,22 @@ deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **additional_conds, List **params_list) { - PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; + PgFdwRelationInfo *fpinfo; + + /* + * For a function RTE absorbed into a foreign join, deparse the function + * expression as a FROM-list item and return. The stub fpinfo set up by + * foreign_join_ok() may or may not be present here. + */ + if (foreignrel->rtekind == RTE_FUNCTION) + { + Assert(!make_subquery); + deparseFunctionRangeTblRef(buf, root, foreignrel, foreignrel, + params_list); + return; + } + + fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private; /* Should only be called in these cases. */ Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel)); @@ -2732,6 +2817,68 @@ static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col) { + /* + * Function RTE columns: emit as f<varno>.c<varattno>, matching the + * aliases generated by deparseFunctionRangeTblRef(). A whole-row Var + * (varattno == 0) is rendered as ROW(f<varno>.c1, ..., f<varno>.c<N>) + * where N is the total column count of the function RTE (including all + * ROWS FROM (...) members). System attributes such as ctid have no + * meaning for function RTEs and are rejected. + */ + if (rte->rtekind == RTE_FUNCTION) + { + if (varattno == 0) + { + int ncols = list_length(rte->eref->colnames); + int i; + + /* + * The CASE WHEN wrapper distinguishes a NULL-supplied outer-join + * row (whole-row Var is NULL) from a row whose columns all happen + * to be NULL (whole-row Var is ROW(NULL, ..., NULL)). A bare + * ROW(...) would collapse those two cases to the latter. + * + * Both cases arise already. Only INNER joins with a function RTE + * are absorbed, but the resulting join may itself end up on the + * nullable side of an outer join that we push down as well, and + * then the remote query supplies NULLs for the whole function + * side. Without the wrapper such a row would come back as + * ROW(NULL, ..., NULL), that is, as if the function had returned + * a row of NULLs rather than no row at all. + */ + if (qualify_col) + { + appendStringInfoString(buf, "CASE WHEN ("); + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfoString(buf, "*)::text IS NOT NULL THEN "); + } + + appendStringInfoString(buf, "ROW("); + for (i = 1; i <= ncols; i++) + { + if (i > 1) + appendStringInfoString(buf, ", "); + appendStringInfo(buf, "%s%d.%s%d", + FUNCTION_REL_ALIAS_PREFIX, varno, + SUBQUERY_COL_ALIAS_PREFIX, i); + } + appendStringInfoChar(buf, ')'); + + if (qualify_col) + appendStringInfoString(buf, " END"); + return; + } + + if (varattno < 0) + elog(ERROR, + "system attribute reference to a function RTE is not supported in foreign join pushdown"); + + if (qualify_col) + appendStringInfo(buf, "%s%d.", FUNCTION_REL_ALIAS_PREFIX, varno); + appendStringInfo(buf, "%s%d", SUBQUERY_COL_ALIAS_PREFIX, varattno); + return; + } + /* We support fetching the remote side's CTID and OID. */ if (varattno == SelfItemPointerAttributeNumber) { diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index d5390ef62d0..7c09c52b8ea 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2960,6 +2960,633 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c (10 rows) ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: t1.c1, t1.c3 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1, t1.c3 + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r1."C 1", r1.c3 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{1,5,10,100}'::integer[]) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + c1 | c3 +-----+------- + 1 | 00001 + 5 | 00005 + 10 | 00010 + 100 | 00100 +(4 rows) + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------- + Sort + Output: t1.c1 + Sort Key: t1.c1 + -> Foreign Scan + Output: t1.c1 + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.generate_series() g) + Remote SQL: SELECT r1."C 1" FROM ("S 1"."T 1" r1 INNER JOIN generate_series(1, 4) f2(c1) ON (((r1."C 1" = f2.c1)))) +(7 rows) + +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + c1 +---- + 1 + 2 + 3 + 4 +(4 rows) + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + QUERY PLAN +------------------------------------------------------------------------------------------------ + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on pg_catalog.generate_series g + Output: g.id + Function Call: generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +-- STABLE function must NOT be pushed down either: even though its result is +-- constant within one query, evaluating it on the remote server could yield +-- a different value than evaluating it locally. +CREATE FUNCTION f_stable(int) RETURNS SETOF int LANGUAGE plpgsql STABLE AS +$$ BEGIN RETURN QUERY SELECT generate_series(1, $1); END $$; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, f_stable(4) AS g(id) WHERE t1.c1 = g.id; + QUERY PLAN +--------------------------------------------------------- + Hash Join + Output: t1.c1 + Hash Cond: (g.id = t1.c1) + -> Function Scan on public.f_stable g + Output: g.id + Function Call: f_stable(4) + -> Hash + Output: t1.c1 + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" +(11 rows) + +DROP FUNCTION f_stable(int); +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + QUERY PLAN +------------------------------------------------------------ + Hash Join + Output: t1.c1, u.ord + Hash Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" + -> Hash + Output: u.ord, u.id + -> Function Scan on pg_catalog.unnest u + Output: u.ord, u.id + Function Call: unnest('{1,5,10}'::integer[]) +(11 rows) + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: t1.c1, t2.c1 + Merge Cond: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST + -> Sort + Output: t2.c1, u.id + Sort Key: t2.c1 + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{1,5,10,100}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(13 rows) + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Hash Join + Output: t1.c1, t2.c1 + Hash Cond: (t1.c1 = t2.c1) + -> Foreign Scan + Output: t1.c1, u.id + Relations: (public.ft1 t1) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r1."C 1", f3.c1 FROM ("S 1"."T 1" r1 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r1."C 1" = f3.c1)))) + -> Hash + Output: t2.c1 + -> Foreign Scan on public.ft6 t2 + Output: t2.c1 + Remote SQL: SELECT c1 FROM "S 1"."T 4" +(12 rows) + +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------- + Nested Loop + Output: t1.c1, t2.c1 + Join Filter: (t1.c1 = u.id) + -> Foreign Scan on public.ft1 t1 + Output: t1.c1 + Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE ((c3 < '00010')) + -> Materialize + Output: t2.c1, u.id + -> Foreign Scan + Output: t2.c1, u.id + Relations: (public.ft6 t2) INNER JOIN (pg_catalog.unnest() u) + Remote SQL: SELECT r2.c1, f3.c1 FROM ("S 1"."T 4" r2 INNER JOIN unnest('{3,6,9,12,15,18}'::integer[]) f3(c1) ON (((r2.c1 = f3.c1)))) +(12 rows) + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + n | a | b +---+---+----- + 2 | 2 | 102 + 3 | 3 | 103 + 4 | 4 | 104 +(3 rows) + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------ + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)) AND ((f1.c1 > 3)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); + QUERY PLAN +----------------------------------------------------------- + Hash Join + Output: n.n, r.a, r.b + Hash Cond: (r.a = n.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a, b FROM public.base_tbl_fn + -> Hash + Output: n.n + -> Function Scan on pg_catalog.unnest n + Output: n.n + Function Call: unnest('{2,3,4}'::integer[]) + Filter: (n.n > f_local(3)) +(12 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +DROP FUNCTION f_local(int); +-- Check that a qual on the function RTE using a function from a shippable +-- extension is pushed down. plpgsql (not inlined) with the column as +-- argument (not const-folded) keeps the function call in the qual. +CREATE FUNCTION f_ext(int) RETURNS int AS $$ +BEGIN RETURN $1; END +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ext(int); +-- Force pushdown so the fixed-code plan is deterministically a Foreign +-- Scan; on the unfixed code the qual is classified local, the join is +-- refused, and the plan falls back to a local join instead. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and f_ext(n) > 3; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: n.n, r.a, r.b + Relations: (pg_catalog.unnest() n) INNER JOIN (public.remote_tbl r) + Remote SQL: SELECT f1.c1, r2.a, r2.b FROM (unnest('{2,3,4}'::integer[]) f1(c1) INNER JOIN public.base_tbl_fn r2 ON (((f1.c1 = r2.a)) AND ((public.f_ext(f1.c1) > 3)))) +(4 rows) + +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and f_ext(n) > 3 ORDER BY r.a; + n | a | b +---+---+----- + 4 | 4 | 104 +(1 row) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ext(int); +DROP FUNCTION f_ext(int); +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; + QUERY PLAN +------------------------------------------------------ + Hash Join + Output: s.* + Hash Cond: (rt.a = s.a) + -> Foreign Scan on public.remote_tbl rt + Output: rt.a, rt.b + Remote SQL: SELECT a FROM public.base_tbl_fn + -> Hash + Output: s.*, s.a + -> Function Scan on public.f_ret_record s + Output: s.*, s.a + Function Call: f_ret_record() +(11 rows) + +DROP FUNCTION f_ret_record(); +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + a | b +----+----- + 23 | 123 + 24 | 999 + 25 | 125 +(3 rows) + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + a | b +----+--- + 24 | 5 +(1 row) + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + a | b | t +----+---+--------------------- + 24 | 7 | ("(2,3),(-2,-3)",1) +(1 row) + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Sort + Output: r.a, t.n, t.s + Sort Key: r.a + -> Foreign Scan + Output: r.a, t.n, t.s + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.generate_series()) t) + Remote SQL: SELECT r1.a, f2.c1, f2.c2 FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + a | n | s +---+---+---- + 3 | 3 | 11 + 6 | 6 | 12 + 9 | 9 | 13 +(3 rows) + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Sort + Output: ((t.*)::text), r.a + Sort Key: r.a + -> Foreign Scan + Output: (t.*)::text, r.a + Relations: (public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.generate_series()) t) + Remote SQL: SELECT CASE WHEN (f2.*)::text IS NOT NULL THEN ROW(f2.c1, f2.c2) END, r1.a FROM (public.base_tbl_fn r1 INNER JOIN ROWS FROM (unnest('{3,6,9}'::integer[]), generate_series(11, 13)) f2(c1, c2) ON (((r1.a = f2.c1)))) +(7 rows) + +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + t | a +--------+--- + (3,11) | 3 + (6,12) | 6 + (9,13) | 9 +(3 rows) + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: u.*, ft5.c1, ft5.c2, ft4.c1, ft4.c2 + Relations: (public.ft5) LEFT JOIN ((public.ft4) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.unnest()) u)) + Remote SQL: SELECT CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END, r1.c1, r1.c2, r2.c1, r2.c2 FROM ("S 1"."T 4" r1 LEFT JOIN ("S 1"."T 3" r2 INNER JOIN ROWS FROM (unnest('{1,2}'::integer[]), unnest('{3,4}'::integer[])) f3(c1, c2) ON (((r2.c1 = f3.c1)))) ON (((r1.c1 = r2.c1)))) WHERE ((r1.c1 < 10)) ORDER BY r1.c1 ASC NULLS LAST +(4 rows) + +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + u | c1 | c2 | c1 | c2 +---+----+----+----+---- + | 3 | 4 | | + | 6 | 7 | | + | 9 | 10 | | +(3 rows) + +-- Same nullable-side whole-row Var, but with outer rows that both match +-- and miss the (foreign x function) inner join. A multi-column function +-- RTE is used so that the reference is a genuine whole-row Var (a single +-- scalar-returning function would collapse to its lone column). This +-- exercises the THEN ROW(...) side of deparseColumnRef()'s whole-row CASE +-- (matched rows reconstruct the composite) as well as the NULL side +-- (missed rows), confirming the executor rebuilds the anonymous composite +-- correctly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan + Output: l.a, t.* + Relations: (public.remote_tbl l) LEFT JOIN ((public.remote_tbl r) INNER JOIN (ROWS FROM (pg_catalog.unnest(), pg_catalog.unnest()) t)) + Remote SQL: SELECT r1.a, CASE WHEN (f3.*)::text IS NOT NULL THEN ROW(f3.c1, f3.c2) END FROM (public.base_tbl_fn r1 LEFT JOIN (public.base_tbl_fn r2 INNER JOIN ROWS FROM (unnest('{2,4}'::integer[]), unnest('{20,40}'::integer[])) f3(c1, c2) ON (((r2.a = f3.c1)))) ON (((r1.a = r2.a)))) WHERE ((r1.a < 6)) ORDER BY r1.a ASC NULLS LAST +(4 rows) + +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; + a | t +---+-------- + 1 | + 2 | (2,20) + 3 | + 4 | (4,40) + 5 | +(5 rows) + +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); +-- The correlated subquery keeps r1 in an enclosing query level, so the +-- function argument reaches the remote side as a query parameter. The +-- restriction on the function's own column is pushed down as well. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r1.a FROM remote_tbl r1 +WHERE EXISTS (SELECT 1 FROM remote_tbl r2, f(r1.a) g + WHERE r2.a = g AND g > 20); + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------- + Foreign Scan on public.remote_tbl r1 + Output: r1.a + Filter: EXISTS(SubPlan exists_1) + Remote SQL: SELECT a FROM public.base_tbl_fn + SubPlan exists_1 + -> Foreign Scan + Relations: (public.remote_tbl r2) INNER JOIN (public.f() g) + Remote SQL: SELECT NULL FROM (public.base_tbl_fn r1 INNER JOIN public.f($1::integer) f2(c1) ON (((r1.a = f2.c1)) AND ((f2.c1 > 20)))) +(8 rows) + +SELECT r1.a FROM remote_tbl r1 +WHERE EXISTS (SELECT 1 FROM remote_tbl r2, f(r1.a) g + WHERE r2.a = g AND g > 20) +ORDER BY r1.a; + a +---- + 21 + 22 + 23 + 24 + 25 + 26 + 27 + 28 + 29 + 30 +(10 rows) + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------ + Merge Join + Output: r.a + Merge Cond: (t.n = r.a) + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]), generate_series(1, (4 + ((random() * '0'::double precision))::integer)) + -> Sort + Output: r.a + Sort Key: r.a + -> Foreign Scan on public.remote_tbl r + Output: r.a + Remote SQL: SELECT a FROM public.base_tbl_fn +(15 rows) + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Nested Loop + Output: r.a, t.x + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 3)) ORDER BY a ASC NULLS LAST + -> Function Scan on pg_catalog.unnest t + Output: t.x + Function Call: unnest(ARRAY[r.a]) +(8 rows) + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + QUERY PLAN +------------------------------------------------------------------------------------------------- + Merge Left Join + Output: r.a, t.n + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn WHERE ((a <= 5)) ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{1,2,3}'::integer[]) +(12 rows) + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + QUERY PLAN +-------------------------------------------------------------------------------- + Merge Semi Join + Output: r.a + Merge Cond: (r.a = t.n) + -> Foreign Scan on public.remote_tbl r + Output: r.a, r.b + Remote SQL: SELECT a FROM public.base_tbl_fn ORDER BY a ASC NULLS LAST + -> Sort + Output: t.n + Sort Key: t.n + -> Function Scan on pg_catalog.unnest t + Output: t.n + Function Call: unnest('{3,6,9}'::integer[]) +(12 rows) + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 0469a761a9d..63a8e248b8d 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -30,6 +30,7 @@ #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/appendinfo.h" +#include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/inherit.h" #include "optimizer/optimizer.h" @@ -90,6 +91,22 @@ enum FdwScanPrivateIndex * of join, added when the scan is join */ FdwScanPrivateRelations, + + /* + * List of per-RTE function metadata, indexed by base RTI offset. Each + * element is either NULL (for non-RTE_FUNCTION rels in this scan) or a + * list of three-element lists (funcid, funcrettype, funccollation) -- one + * inner list per function in the RTE. Allows the executor to rebuild + * TupleDesc entries for whole-row references to function RTEs. + */ + FdwScanPrivateFunctions, + + /* + * Integer node: minimum base RT index covered by the scan, used to + * translate scan-local indexes to estate-rtable indexes after setrefs.c + * flattens rtables. + */ + FdwScanPrivateMinRTIndex, }; /* @@ -126,6 +143,11 @@ enum FdwModifyPrivateIndex * 2) Boolean flag showing if the remote query has a RETURNING clause * 3) Integer list of attribute numbers retrieved by RETURNING, if any * 4) Boolean flag showing if we set the command es_processed + * 5) Per-RTE function metadata (mirrors FdwScanPrivateFunctions; lets + * the executor rebuild TupleDesc entries for whole-row Vars over + * function RTEs absorbed into a foreign join) + * 6) Integer node: minimum base RT index of the scan (mirrors + * FdwScanPrivateMinRTIndex) */ enum FdwDirectModifyPrivateIndex { @@ -137,6 +159,10 @@ enum FdwDirectModifyPrivateIndex FdwDirectModifyPrivateRetrievedAttrs, /* set-processed flag (as a Boolean node) */ FdwDirectModifyPrivateSetProcessed, + /* Per-RTE function metadata, indexed by base RTI offset */ + FdwDirectModifyPrivateFunctions, + /* Integer node: minimum base RT index in the scan */ + FdwDirectModifyPrivateMinRTIndex, }; /* @@ -619,6 +645,9 @@ static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, static List *get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel); static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel); +static Relids get_base_relids(PlannerInfo *root, RelOptInfo *rel); +static int get_min_base_rti(PlannerInfo *root, RelOptInfo *rel); +static List *get_functions_data(PlannerInfo *root, RelOptInfo *rel); static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, Path *epq_path, List *restrictlist); static void add_foreign_grouping_paths(PlannerInfo *root, @@ -772,7 +801,7 @@ postgresGetForeignRelSize(PlannerInfo *root, * Identify which baserestrictinfo clauses can be sent to the remote * server and which can't. */ - classifyConditions(root, baserel, baserel->baserestrictinfo, + classifyConditions(root, baserel, fpinfo, baserel->baserestrictinfo, &fpinfo->remote_conds, &fpinfo->local_conds); /* @@ -1176,7 +1205,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1252,7 +1281,7 @@ postgresGetForeignPaths(PlannerInfo *root, continue; /* See if it is safe to send to remote */ - if (!is_foreign_expr(root, baserel, rinfo->clause)) + if (!is_foreign_expr(root, baserel, fpinfo, rinfo->clause)) continue; /* Calculate required outer rels for the resulting path */ @@ -1392,7 +1421,7 @@ postgresGetForeignPlan(PlannerInfo *root, remote_exprs = lappend(remote_exprs, rinfo->clause); else if (list_member_ptr(fpinfo->local_conds, rinfo)) local_exprs = lappend(local_exprs, rinfo->clause); - else if (is_foreign_expr(root, foreignrel, rinfo->clause)) + else if (is_foreign_expr(root, foreignrel, fpinfo, rinfo->clause)) remote_exprs = lappend(remote_exprs, rinfo->clause); else local_exprs = lappend(local_exprs, rinfo->clause); @@ -1513,9 +1542,26 @@ postgresGetForeignPlan(PlannerInfo *root, fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(fpinfo->fetch_size)); + + /* + * Position FdwScanPrivateRelations: either the EXPLAIN relation string + * (joins/upper rels) or a NULL placeholder, so that subsequent indexes + * stay valid for the base-rel scan case. + */ if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel)) fdw_private = lappend(fdw_private, makeString(fpinfo->relation_name)); + else + fdw_private = lappend(fdw_private, NULL); + + /* + * FdwScanPrivateFunctions / FdwScanPrivateMinRTIndex carry the metadata + * the executor needs to rebuild TupleDesc entries for whole-row Vars + * pointing at RTE_FUNCTION rels absorbed into the foreign scan. + */ + fdw_private = lappend(fdw_private, get_functions_data(root, foreignrel)); + fdw_private = lappend(fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Create the ForeignScan node for the given relation. @@ -1536,9 +1582,15 @@ postgresGetForeignPlan(PlannerInfo *root, /* * Construct a tuple descriptor for the scan tuples handled by a foreign join. + * + * 'rtfuncdata' is the FdwScanPrivateFunctions list saved at plan time, and + * 'rtoffset' is the difference between the executor's RT indexes and the + * scan-local RT indexes captured in that list. Both may be 0/NIL when the + * scan has no RTE_FUNCTION dependents. */ static TupleDesc -get_tupdesc_for_join_scan_tuples(ForeignScanState *node) +get_tupdesc_for_join_scan_tuples(ForeignScanState *node, + List *rtfuncdata, int rtoffset) { ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan; EState *estate = node->ss.ps.state; @@ -1574,13 +1626,67 @@ get_tupdesc_for_join_scan_tuples(ForeignScanState *node) if (!IsA(var, Var) || var->varattno != 0) continue; rte = list_nth(estate->es_range_table, var->varno - 1); - if (rte->rtekind != RTE_RELATION) - continue; - reltype = get_rel_type_id(rte->relid); - if (!OidIsValid(reltype)) - continue; - att->atttypid = reltype; - /* shouldn't need to change anything else */ + + if (rte->rtekind == RTE_RELATION) + { + reltype = get_rel_type_id(rte->relid); + if (!OidIsValid(reltype)) + continue; + att->atttypid = reltype; + /* shouldn't need to change anything else */ + } + else if (rte->rtekind == RTE_FUNCTION) + { + /* + * A whole-row Var points at a FUNCTION RTE absorbed into the + * foreign join. Synthesize an anonymous composite TupleDesc from + * the per-function return-type metadata we saved at plan time; + * the deparser emits these as ROW(f<rti>.c1, f<rti>.c2, ...). + * + * For an upperrel scan (the only path that reaches here) + * postgresGetForeignPlan always builds rtfuncdata via + * get_functions_data(), so it is never NIL; the per-RTE slot for + * the function RTE referenced by this Var must likewise be + * populated. + */ + List *funcdata; + TupleDesc rte_tupdesc; + int num_funcs; + int attnum; + ListCell *lc1, + *lc2; + + Assert(rtfuncdata != NIL); + funcdata = list_nth(rtfuncdata, var->varno - rtoffset); + Assert(funcdata != NIL); + num_funcs = list_length(funcdata); + Assert(num_funcs == list_length(rte->eref->colnames)); + rte_tupdesc = CreateTemplateTupleDesc(num_funcs); + + attnum = 1; + forboth(lc1, funcdata, lc2, rte->eref->colnames) + { + List *fdata = lfirst_node(List, lc1); + char *colname = strVal(lfirst(lc2)); + Oid funcrettype; + Oid funccollation; + + funcrettype = lsecond_node(Integer, fdata)->ival; + funccollation = lthird_node(Integer, fdata)->ival; + + /* get_functions_data() already validated the return type. */ + Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID); + + TupleDescInitEntry(rte_tupdesc, (AttrNumber) attnum, colname, + funcrettype, -1, 0); + TupleDescInitEntryCollation(rte_tupdesc, (AttrNumber) attnum, + funccollation); + attnum++; + } + + assign_record_type_typmod(rte_tupdesc); + att->atttypmod = rte_tupdesc->tdtypmod; + } } return tupdesc; } @@ -1616,14 +1722,30 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) /* * Identify which user to do the remote access as. This should match what - * ExecCheckPermissions() does. + * ExecCheckPermissions() does. For a join, scan the base relids until we + * find an RTE_RELATION (the foreign-table side); ignore any RTE_FUNCTION + * absorbed into the join, which contributes no relation OID to look up. */ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId(); + rte = NULL; if (fsplan->scan.scanrelid > 0) + { rtindex = fsplan->scan.scanrelid; + rte = exec_rt_fetch(rtindex, estate); + } else - rtindex = bms_next_member(fsplan->fs_base_relids, -1); - rte = exec_rt_fetch(rtindex, estate); + { + rtindex = -1; + while ((rtindex = bms_next_member(fsplan->fs_base_relids, rtindex)) >= 0) + { + rte = exec_rt_fetch(rtindex, estate); + if (rte != NULL && rte->rtekind == RTE_RELATION) + break; + rte = NULL; + } + if (rte == NULL) + elog(ERROR, "could not locate a foreign relation RTE in foreign scan"); + } /* Get info about foreign table. */ table = GetForeignTable(rte->relid); @@ -1666,8 +1788,19 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags) } else { + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwScanPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwScanPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + fsstate->rel = NULL; - fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node); + fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, + rtoffset); } fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc); @@ -2615,7 +2748,7 @@ postgresPlanDirectModify(PlannerInfo *root, if (attno <= InvalidAttrNumber) /* shouldn't happen */ elog(ERROR, "system-column update is not supported"); - if (!is_foreign_expr(root, foreignrel, (Expr *) tle->expr)) + if (!is_foreign_expr(root, foreignrel, fpinfo, (Expr *) tle->expr)) return false; } } @@ -2702,6 +2835,10 @@ postgresPlanDirectModify(PlannerInfo *root, makeBoolean((retrieved_attrs != NIL)), retrieved_attrs, makeBoolean(plan->canSetTag)); + fscan->fdw_private = lappend(fscan->fdw_private, + get_functions_data(root, foreignrel)); + fscan->fdw_private = lappend(fscan->fdw_private, + makeInteger(get_min_base_rti(root, foreignrel))); /* * Update the foreign-join-related fields. @@ -2815,7 +2952,26 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags) TupleDesc tupdesc; if (fsplan->scan.scanrelid == 0) - tupdesc = get_tupdesc_for_join_scan_tuples(node); + { + /* + * DirectModify on a foreign join: use the per-RTE function + * metadata saved at plan time so a whole-row Var pointing at a + * function RTE absorbed into the join can be rebuilt into a + * usable TupleDesc (e.g. RETURNING t for a join with UNNEST(..., + * ...) AS t(bx, i)). + */ + List *rtfuncdata = (List *) list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateFunctions); + int min_base_rti = intVal(list_nth(fsplan->fdw_private, + FdwDirectModifyPrivateMinRTIndex)); + int rtoffset = bms_next_member(fsplan->fs_base_relids, -1) - + min_base_rti; + + Assert(min_base_rti > 0); + Assert(rtoffset >= 0); + + tupdesc = get_tupdesc_for_join_scan_tuples(node, rtfuncdata, rtoffset); + } else tupdesc = RelationGetDescr(dmstate->rel); @@ -2928,7 +3084,8 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) * We do that here, not when the plan is created, because we can't know * what aliases ruleutils.c will assign at plan creation time. */ - if (list_length(fdw_private) > FdwScanPrivateRelations) + if (list_length(fdw_private) > FdwScanPrivateRelations && + list_nth(fdw_private, FdwScanPrivateRelations) != NULL) { StringInfoData relations; char *rawrelations; @@ -2978,25 +3135,90 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) rti += rtoffset; Assert(bms_is_member(rti, plan->fs_base_relids)); rte = rt_fetch(rti, es->rtable); - Assert(rte->rtekind == RTE_RELATION); - /* This logic should agree with explain.c's ExplainTargetRel */ - relname = get_rel_name(rte->relid); - if (es->verbose) - { - char *namespace; - namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); - appendStringInfo(&relations, "%s.%s", - quote_identifier(namespace), - quote_identifier(relname)); + if (rte->rtekind == RTE_FUNCTION) + { + List *rtfuncdata = list_nth(fdw_private, FdwScanPrivateFunctions); + List *funcdata; + bool multi_func; + bool first = true; + ListCell *lc; + + funcdata = list_nth(rtfuncdata, rti - rtoffset); + + multi_func = list_length(funcdata) > 1; + + if (multi_func) + appendStringInfoString(&relations, "ROWS FROM ("); + + foreach(lc, funcdata) + { + List *funcinfo; + Oid funcid; + + + if (!first) + appendStringInfoString(&relations, ", "); + + funcinfo = (List *) lfirst(lc); + + funcid = linitial_node(Integer, funcinfo)->ival; + /* Checked by function_rte_pushdown_ok() */ + Assert(OidIsValid(funcid)); + + /* Match RTE_RELATION behavior */ + relname = get_func_name(funcid); + if (relname == NULL) + elog(ERROR, "cache lookup failed for function %u", funcid); + if (es->verbose) + { + char *namespace; + Oid nsoid = get_func_namespace(funcid); + + namespace = get_namespace_name(nsoid); + if (namespace == NULL) + elog(ERROR, "cache lookup failed for namespace %u", nsoid); + + appendStringInfo(&relations, "%s.%s()", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfo(&relations, "%s()", quote_identifier(relname)); + + first = false; + } + /* Close ROWS FROM */ + if (multi_func) + appendStringInfoChar(&relations, ')'); } else - appendStringInfoString(&relations, - quote_identifier(relname)); + { + Assert(rte->rtekind == RTE_RELATION); + + /* + * This logic should agree with explain.c's + * ExplainTargetRel + */ + relname = get_rel_name(rte->relid); + if (es->verbose) + { + char *namespace; + + namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid)); + appendStringInfo(&relations, "%s.%s", + quote_identifier(namespace), + quote_identifier(relname)); + } + else + appendStringInfoString(&relations, + quote_identifier(relname)); + } + refname = (char *) list_nth(es->rtable_names, rti - 1); if (refname == NULL) refname = rte->eref->aliasname; - if (strcmp(refname, relname) != 0) + if (relname == NULL || strcmp(refname, relname) != 0) appendStringInfo(&relations, " %s", quote_identifier(refname)); } @@ -3220,7 +3442,7 @@ estimate_path_cost_size(PlannerInfo *root, * param_join_conds might contain both clauses that are safe to send * across, and clauses that aren't. */ - classifyConditions(root, foreignrel, param_join_conds, + classifyConditions(root, foreignrel, fpinfo, param_join_conds, &remote_param_join_conds, &local_param_join_conds); /* Build the list of columns to be fetched from the foreign server. */ @@ -3353,8 +3575,17 @@ estimate_path_cost_size(PlannerInfo *root, /* For join we expect inner and outer relations set */ Assert(fpinfo->innerrel && fpinfo->outerrel); - fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; + /* + * For a FUNCTION RTE absorbed into the join, use the stub fpinfo + * we built in foreign_join_ok(), since the function rel itself + * has no fdw_private. + */ + fpinfo_i = fpinfo->inner_func_fpinfo ? + fpinfo->inner_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private; + fpinfo_o = fpinfo->outer_func_fpinfo ? + fpinfo->outer_func_fpinfo : + (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private; /* Estimate of number of rows in cross product */ nrows = fpinfo_i->rows * fpinfo_o->rows; @@ -6565,6 +6796,256 @@ semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, return ok; } +/* + * get_base_relids + * Return the set of base relids referenced by a foreign scan rel. + * + * For an upper rel we use the all-query relids minus the outer joins; + * otherwise the rel's own relids minus the outer joins. The result matches + * the relids that create_foreignscan_plan() ultimately uses for + * ForeignScan.fs_base_relids, so it is suitable for any tagging we want to + * store via plan-private state. + */ +static Relids +get_base_relids(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids; + + if (rel->reloptkind == RELOPT_UPPER_REL) + relids = root->all_query_rels; + else + relids = rel->relids; + + return bms_difference(relids, root->outer_join_rels); +} + +/* + * get_min_base_rti + * Lowest base RT index in the foreign scan rel. + * + * After setrefs.c flattens the rtable, the scan-local indexes saved in + * plan-private data can be translated to estate indexes by adding + * (ForeignScan.fs_base_relids min - this value). Captured at plan time + * because create_foreignscan_plan() computes the same value internally. + */ +static int +get_min_base_rti(PlannerInfo *root, RelOptInfo *rel) +{ + Relids relids = get_base_relids(root, rel); + + return bms_next_member(relids, -1); +} + +/* + * get_functions_data + * Build the per-RTE function metadata list saved as + * FdwScanPrivateFunctions. + * + * The result list is indexed by base RT index relative to the lowest base + * RT index of the scan. Each element is either NULL (for non-RTE_FUNCTION + * base rels in this scan) or a List of List of two Integer nodes: + * (funcrettype, funccollation) -- one inner list per RangeTblFunction. + * + * Only RTE_FUNCTION relids actually appearing in the foreign scan's + * fs_base_relids contribute; others are placeholders so that the consumer + * can index into the result by RTI offset. + */ +static List * +get_functions_data(PlannerInfo *root, RelOptInfo *rel) +{ + List *rtfuncdata = NIL; + Relids fscan_relids = get_base_relids(root, rel); + int i; + + for (i = 0; i < root->simple_rel_array_size; i++) + { + RangeTblEntry *rte = root->simple_rte_array[i]; + List *funcdata = NIL; + ListCell *lc; + + if (rte == NULL || i == 0 || + !bms_is_member(i, fscan_relids) || + rte->rtekind != RTE_FUNCTION) + { + rtfuncdata = lappend(rtfuncdata, NULL); + continue; + } + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + Oid funcrettype; + Oid funccollation; + TupleDesc tupdesc; + Oid funcid; + + get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); + + /* + * function_rte_pushdown_ok() already rejected any function that + * doesn't return a well-defined scalar type, so this is a mere + * cross-check. + */ + Assert(OidIsValid(funcrettype) && funcrettype != RECORDOID); + + funccollation = exprCollation(rtfunc->funcexpr); + + funcid = ((FuncExpr *) rtfunc->funcexpr)->funcid; + + funcdata = lappend(funcdata, + list_make3(makeInteger(funcid), + makeInteger(funcrettype), + makeInteger(funccollation))); + } + + rtfuncdata = lappend(rtfuncdata, funcdata); + } + + return rtfuncdata; +} + +/* + * init_func_stub_fpinfo + * Build a stub PgFdwRelationInfo for a FUNCTION RTE that is being + * absorbed into a foreign join. + * + * A function RTE has no fdw_private of its own, but the joinrel-level cost + * estimator, deparser and merge_fdw_options() all read server-level options + * from the "outer" fpinfo unconditionally. So the stub must carry the same + * server, shippable_extensions, and cost-related options as the real foreign + * side of the join; otherwise the pushdown path is judged against zeroed + * fdw_startup_cost/fdw_tuple_cost/etc. and looks artificially cheap. + * + * The stub is meaningful only for the specific (foreign, function) pairing + * that produced it; it must live on the joinrel's PgFdwRelationInfo, never + * on the function rel's fdw_private, since the same function RTE may pair + * with different foreign servers in sibling joinrels. + */ +static PgFdwRelationInfo * +init_func_stub_fpinfo(const PgFdwRelationInfo *fpinfo_foreign, + RelOptInfo *funcrel) +{ + PgFdwRelationInfo *stub = palloc0_object(PgFdwRelationInfo); + + stub->pushdown_safe = true; + + /* Server-level options, inherited from the foreign side. */ + stub->server = fpinfo_foreign->server; + stub->shippable_extensions = fpinfo_foreign->shippable_extensions; + stub->fdw_startup_cost = fpinfo_foreign->fdw_startup_cost; + stub->fdw_tuple_cost = fpinfo_foreign->fdw_tuple_cost; + stub->use_remote_estimate = fpinfo_foreign->use_remote_estimate; + stub->fetch_size = fpinfo_foreign->fetch_size; + stub->async_capable = fpinfo_foreign->async_capable; + + /* Function-side identity and estimates from the local planner. */ + stub->relation_name = psprintf("%u", funcrel->relid); + stub->rows = funcrel->rows; + stub->width = funcrel->reltarget->width; + stub->retrieved_rows = funcrel->rows; + /* + * The function is executed on the remote server, so these must carry its + * cost the same way a foreign rel's do: what producing the rows costs the + * far side, before connection setup and data transfer are added. The + * local path for the same function is our best estimate of that. + */ + stub->rel_startup_cost = funcrel->cheapest_total_path->startup_cost; + stub->rel_total_cost = funcrel->cheapest_total_path->total_cost; + + return stub; +} + +/* + * Check if a relation is a FUNCTION RTE that can be absorbed into a remote + * join. Every function in the RTE must + * + * - return a well-defined scalar type -- we don't ship records/composite + * since the remote server cannot reconstruct a column definition list + * and our deparser does not emit one; + * - have a shippable expression with no mutable subnodes -- is_foreign_expr() + * rejects volatile/stable functions through contain_mutable_functions(), + * so the IMMUTABLE-only restriction is implicit; + * - not contain SubPlans -- we'd otherwise need to ship sub-results to + * the remote, which we do not implement. + * + * WITH ORDINALITY is not supported yet. + */ +static bool +function_rte_pushdown_ok(PlannerInfo *root, RelOptInfo *rel, + RelOptInfo *fdwrel) +{ + RangeTblEntry *rte; + ListCell *lc; + + if (rel->rtekind != RTE_FUNCTION) + return false; + rte = planner_rt_fetch(rel->relid, root); + + /* + * build_simple_rel() copies rtekind straight from the RTE, so for a base + * rel rel->rtekind always matches the RTE's; the check above is therefore + * sufficient. + */ + Assert(rte->rtekind == RTE_FUNCTION); + + if (rte->funcordinality) + return false; + + /* + * Reject up-front any function RTE that lateral-references another + * relation: foreign-join push-down would need to parameterise the remote + * query per outer row, which we don't support, and even considering the + * path is expensive on the planner side. The surrounding lateral_relids + * check in postgresGetForeignJoinPaths() would normally bail out for the + * joinrel, but doing the check here avoids walking the function + * expression entirely. + * + * Note this rejects only lateral references to another relation at the + * same query level. A function argument referencing an outer query level + * (e.g. f(outer.col) inside a subquery) is a different case: it becomes a + * PARAM_EXEC Param, the function rel's lateral_relids is empty, and + * foreign_expr_walker() intentionally treats PARAM_EXEC as shippable. The + * remote query then carries a parameter placeholder, and postgres_fdw's + * ordinary parameter machinery re-sends it on each rescan -- i.e. it + * works as a normal parameterized foreign scan, which is fine. + */ + if (!bms_is_empty(rel->lateral_relids)) + return false; + + Assert(list_length(rte->functions) >= 1); + + foreach(lc, rte->functions) + { + RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + TypeFuncClass functypclass; + Oid funcrettype; + TupleDesc tupdesc; + + /* Refuse to deal with strange funcexprs */ + if (!IsA(rtfunc->funcexpr, FuncExpr)) + return false; + + if (!OidIsValid(((FuncExpr *) rtfunc->funcexpr)->funcid)) + return false; + + functypclass = get_expr_result_type(rtfunc->funcexpr, + &funcrettype, &tupdesc); + if (functypclass != TYPEFUNC_SCALAR) + return false; + if (!OidIsValid(funcrettype) || + funcrettype == RECORDOID || + funcrettype == VOIDOID) + return false; + + if (contain_subplans(rtfunc->funcexpr)) + return false; + if (!is_foreign_expr(root, fdwrel, fdwrel->fdw_private, (Expr *) rtfunc->funcexpr)) + return false; + } + + return true; +} + /* * Assess whether the join between inner and outer relations can be pushed down * to the foreign server. As a side effect, save information we obtain in this @@ -6580,6 +7061,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; + bool outer_is_function = false; + bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -6598,15 +7081,68 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, return false; /* - * If either of the joining relations is marked as unsafe to pushdown, the - * join can not be pushed down. + * Detect mixed (foreign x function-RTE) cases. Only INNER joins are + * supported initially. We dispatch on rtekind here so that the same + * function RTE can be absorbed into joins on multiple foreign servers + * (each call gets its own stub fpinfo and rechecks shippability for the + * specific server). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && + (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && + fpinfo_o->pushdown_safe && + function_rte_pushdown_ok(root, innerrel, outerrel)) + { + inner_is_function = true; + } + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) + { + outer_is_function = true; + } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } + + /* + * If one side is a function RTE, allocate a stub fpinfo so the rest of + * this function and the cost estimator can treat it uniformly. We hand + * the stub to the joinrel's deparser via the same path the foreign side + * uses, but we never permanently attach it to the function rel's + * fdw_private (different joinrels may pair the same function RTE with + * different foreign servers). + */ + if (inner_is_function) + { + fpinfo_i = init_func_stub_fpinfo(fpinfo_o, innerrel); + + /* + * Classify the function rel's own baserestrictinfo now, so that the + * local_conds check below can bail out if any of it is unshippable. + * We classify against the stub, not the joinrel's fpinfo, because the + * latter's server/shippable_extensions aren't populated until + * merge_fdw_options() runs further down. + */ + classifyConditions(root, innerrel, fpinfo_i, innerrel->baserestrictinfo, + &fpinfo_i->remote_conds, &fpinfo_i->local_conds); + fpinfo->inner_func_fpinfo = fpinfo_i; + } + else if (outer_is_function) + { + fpinfo_o = init_func_stub_fpinfo(fpinfo_i, outerrel); + + /* See the comment in the inner_is_function branch above. */ + classifyConditions(root, outerrel, fpinfo_o, outerrel->baserestrictinfo, + &fpinfo_o->remote_conds, &fpinfo_o->local_conds); + fpinfo->outer_func_fpinfo = fpinfo_o; + } /* * If joining relations have local conditions, those conditions are @@ -6644,7 +7180,7 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, foreach(lc, extra->restrictlist) { RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc); - bool is_remote_clause = is_foreign_expr(root, joinrel, + bool is_remote_clause = is_foreign_expr(root, joinrel, fpinfo, rinfo->clause); if (IS_OUTER_JOIN(jointype) && @@ -7342,7 +7878,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * If any GROUP BY expression is not shippable, then we cannot * push down aggregation to the foreign server. */ - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; /* @@ -7370,7 +7906,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * Non-grouping expression we need to compute. Can we ship it * as-is to the foreign server? */ - if (is_foreign_expr(root, grouped_rel, expr) && + if (is_foreign_expr(root, grouped_rel, fpinfo, expr) && !is_foreign_param(root, grouped_rel, expr)) { /* Yes, so add to tlist as-is; OK to suppress duplicates */ @@ -7390,7 +7926,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, * don't have to check is_foreign_param, since that certainly * won't return true for any such expression.) */ - if (!is_foreign_expr(root, grouped_rel, (Expr *) aggvars)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, (Expr *) aggvars)) return false; /* @@ -7442,7 +7978,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, grouped_rel->relids, NULL, NULL); - if (is_foreign_expr(root, grouped_rel, expr)) + if (is_foreign_expr(root, grouped_rel, fpinfo, expr)) fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo); else fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo); @@ -7479,7 +8015,7 @@ foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, */ if (IsA(expr, Aggref)) { - if (!is_foreign_expr(root, grouped_rel, expr)) + if (!is_foreign_expr(root, grouped_rel, fpinfo, expr)) return false; tlist = add_to_flat_tlist(tlist, list_make1(expr)); @@ -7992,8 +8528,8 @@ add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel, * Also, the LIMIT/OFFSET cannot be pushed down, if their expressions are * not safe to remote. */ - if (!is_foreign_expr(root, input_rel, (Expr *) parse->limitOffset) || - !is_foreign_expr(root, input_rel, (Expr *) parse->limitCount)) + if (!is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitOffset) || + !is_foreign_expr(root, input_rel, ifpinfo, (Expr *) parse->limitCount)) return; /* Safe to push down */ @@ -8639,7 +9175,7 @@ find_em_for_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel) if (bms_is_subset(em->em_relids, rel->relids) && !bms_is_empty(em->em_relids) && bms_is_empty(bms_intersect(em->em_relids, fpinfo->hidden_subquery_rels)) && - is_foreign_expr(root, rel, em->em_expr)) + is_foreign_expr(root, rel, fpinfo, em->em_expr)) return em; } @@ -8661,6 +9197,7 @@ EquivalenceMember * find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel) { + PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private; PathTarget *target = rel->reltarget; ListCell *lc1; int i; @@ -8710,7 +9247,7 @@ find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, continue; /* Check that expression (including relabels!) is shippable */ - if (is_foreign_expr(root, rel, em->em_expr)) + if (is_foreign_expr(root, rel, fpinfo, em->em_expr)) return em; } diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h index a2bb1ff352c..da7da1c2ea9 100644 --- a/contrib/postgres_fdw/postgres_fdw.h +++ b/contrib/postgres_fdw/postgres_fdw.h @@ -106,6 +106,16 @@ typedef struct PgFdwRelationInfo /* joinclauses contains only JOIN/ON conditions for an outer join */ List *joinclauses; /* List of RestrictInfo */ + /* + * If a FUNCTION RTE was absorbed into this join, these point at the stub + * PgFdwRelationInfo for the function side (paired with the + * outerrel/innerrel), so the cost estimator and deparser can find it + * without consulting the function rel's fdw_private. At most one of + * outer_func_fpinfo/inner_func_fpinfo is set. + */ + struct PgFdwRelationInfo *outer_func_fpinfo; + struct PgFdwRelationInfo *inner_func_fpinfo; + /* Upper relation information */ UpperRelationKind stage; @@ -183,11 +193,13 @@ extern char *pgfdw_application_name; /* in deparse.c */ extern void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, List *input_conds, List **remote_conds, List **local_conds); extern bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, + PgFdwRelationInfo *fpinfo, Expr *expr); extern bool is_foreign_param(PlannerInfo *root, RelOptInfo *baserel, diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql index 1d771391c07..6571a18ba0c 100644 --- a/contrib/postgres_fdw/sql/postgres_fdw.sql +++ b/contrib/postgres_fdw/sql/postgres_fdw.sql @@ -825,6 +825,280 @@ SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; ALTER VIEW v4 OWNER TO regress_view_owner; +-- =================================================================== +-- Foreign-join with FUNCTION RTE pushdown (IMMUTABLE functions only) +-- =================================================================== +-- IMMUTABLE function: unnest of constant array can be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; +SELECT t1.c1, t1.c3 FROM ft1 t1, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id ORDER BY t1.c1; + +-- IMMUTABLE function: generate_series with constant args +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4) AS g(id) +WHERE t1.c1 = g.id ORDER BY t1.c1; + +-- VOLATILE function (random) must NOT be pushed down +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, generate_series(1, 4 + (random() * 0)::int) AS g(id) +WHERE t1.c1 = g.id; + +-- STABLE function must NOT be pushed down either: even though its result is +-- constant within one query, evaluating it on the remote server could yield +-- a different value than evaluating it locally. +CREATE FUNCTION f_stable(int) RETURNS SETOF int LANGUAGE plpgsql STABLE AS +$$ BEGIN RETURN QUERY SELECT generate_series(1, $1); END $$; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1 FROM ft1 t1, f_stable(4) AS g(id) WHERE t1.c1 = g.id; +DROP FUNCTION f_stable(int); + +-- WITH ORDINALITY must NOT be pushed down (limitation of this implementation) +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, u.ord +FROM ft1 t1, unnest(ARRAY[1, 5, 10]::int[]) WITH ORDINALITY AS u(id, ord) +WHERE t1.c1 = u.id; + +-- Same function RTE joined with two different foreign servers: planner picks +-- one absorption + a local join with the second foreign server. The fact +-- that the function is IMMUTABLE makes this safe even if both sides chose to +-- absorb it independently. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[1, 5, 10, 100]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id ORDER BY t1.c1; + +-- Cost-based selection between two foreign servers: ft1 ("S 1"."T 1") has +-- 1000 rows, ft6 ("S 1"."T 4") has ~33 rows. The same query shape gets a +-- different push-down target depending on a predicate that changes the +-- effective cardinality of one side -- the function "jumps" to whichever +-- foreign scan benefits more from being pre-filtered. +ANALYZE ft1; +ANALYZE ft6; +-- No extra predicate: ft1 is the bigger side, function absorbed there. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id; +-- Selective predicate on ft1.c3 (not in the eqclass) shrinks ft1 to a +-- handful of remote rows; now ft6 is effectively the bigger side and the +-- function is absorbed into ft6 instead. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t1.c1, t2.c1 +FROM ft1 t1, ft6 t2, unnest(ARRAY[3, 6, 9, 12, 15, 18]::int[]) AS u(id) +WHERE t1.c1 = u.id AND t2.c1 = u.id AND t1.c3 < '00010'; + +-- The remaining scenarios reuse a dedicated foreign table to cover the +-- corner cases of FUNCTION RTE push-down: function-first FROM, record +-- return type rejection, whole-row reference, UPDATE...FROM..., and +-- multi-function ROWS FROM. +CREATE TABLE base_tbl_fn (a int, b int); +INSERT INTO base_tbl_fn + SELECT g, g + 100 FROM generate_series(1, 30) g; +CREATE FOREIGN TABLE remote_tbl (a int, b int) + SERVER loopback OPTIONS (table_name 'base_tbl_fn'); + +-- The function RTE appears first in FROM; the foreign relation must be +-- found by scanning fs_base_relids for an RTE_RELATION rather than +-- using scan->fs_relid blindly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n ORDER BY r.a; + +-- Function RTE is restricted, shippable conditions +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > 3; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > 3 ORDER BY r.a; + +-- Function RTE is restricted, nonshippable conditions +CREATE FUNCTION f_local(int) RETURNS int AS $$ +BEGIN +RETURN $1; +END +$$ LANGUAGE plpgsql; + +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and n > f_local(3); +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and n > f_local(3) ORDER BY r.a; + +DROP FUNCTION f_local(int); + +-- Check that a qual on the function RTE using a function from a shippable +-- extension is pushed down. plpgsql (not inlined) with the column as +-- argument (not const-folded) keeps the function call in the qual. +CREATE FUNCTION f_ext(int) RETURNS int AS $$ +BEGIN RETURN $1; END +$$ LANGUAGE plpgsql IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f_ext(int); +-- Force pushdown so the fixed-code plan is deterministically a Foreign +-- Scan; on the unfixed code the qual is classified local, the join is +-- refused, and the plan falls back to a local join instead. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r WHERE r.a = n and f_ext(n) > 3; +SELECT * FROM unnest(array[2, 3, 4]) n, remote_tbl r +WHERE r.a = n and f_ext(n) > 3 ORDER BY r.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; +ALTER EXTENSION postgres_fdw DROP FUNCTION f_ext(int); +DROP FUNCTION f_ext(int); + +-- A function returning record (composite) is forbidden; pushing it +-- would yield a remote "column definition list is required" error. +-- function_rte_pushdown_ok() rejects it via TYPEFUNC_SCALAR. +CREATE OR REPLACE FUNCTION f_ret_record() RETURNS record AS $$ + SELECT (1, 2)::record +$$ LANGUAGE SQL IMMUTABLE; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT s FROM remote_tbl rt, f_ret_record() AS s(a int, b int) +WHERE s.a = rt.a; +DROP FUNCTION f_ret_record(); + +-- UPDATE ... FROM unnest() with a complex element type; area(box) +-- yields the value to match. The locking machinery for the +-- non-relation RTE generates a whole-row Var that deparseColumnRef +-- emits as ROW(f<rti>.c1, ...). +UPDATE remote_tbl r SET b = 999 +FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) +WHERE r.a = area(t.bx); +SELECT * FROM remote_tbl WHERE a IN (23, 24, 25) ORDER BY a; + +-- The same shape with CASE and RETURNING; exercises the DirectModify +-- path and the executor's tuple-desc reconstruction. +UPDATE remote_tbl r + SET b = CASE WHEN random() >= 0 THEN 5 ELSE 0 END + FROM unnest(array[box '((2,3),(-2,-3))']) AS t(bx) + WHERE r.a = area(t.bx) RETURNING a, b; + +-- RETURNING a whole-row reference to the function RTE. Without the +-- per-RTE function metadata being preserved on the DirectModify path +-- (FdwDirectModifyPrivateFunctions / FdwDirectModifyPrivateMinRTIndex), +-- this would fail with "input of anonymous composite types is not +-- implemented". +UPDATE remote_tbl r SET b = 7 + FROM unnest(array[box '((2,3),(-2,-3))'], + array[int '1']) AS t(bx, i) + WHERE r.a = area(t.bx) RETURNING a, b, t; + +-- ROWS FROM (...) with several functions. Force pushdown because the +-- cost model otherwise picks a local plan. +SET enable_hashjoin = off; +SET enable_mergejoin = off; +SET enable_nestloop = off; +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT r.a, t.n, t.s + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Whole-row Var on the absorbed function side (e.g. via a cast to +-- text). Exercises both deparseColumnRef whole-row branch and the +-- get_tupdesc_for_join_scan_tuples() RTE_FUNCTION metadata path. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; +SELECT t::text, r.a + FROM remote_tbl r, ROWS FROM (unnest(array[3, 6, 9]), + generate_series(11, 13)) AS t(n, s) + WHERE r.a = t.n ORDER BY r.a; + +-- Check whole-row Var represented by function on the nullable +-- left join side +EXPLAIN (VERBOSE, COSTS OFF) +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; +SELECT u, ft5.c1, ft5.c2, ft4.c1, ft4.c2 FROM ft5 LEFT JOIN +(ft4 JOIN unnest(array[1,2], array[3,4]) as u (u1, u2) ON ft4.c1=u1) +ON ft5.c1 = ft4.c1 WHERE ft5.c1 < 10 ORDER BY ft5.c1; + +-- Same nullable-side whole-row Var, but with outer rows that both match +-- and miss the (foreign x function) inner join. A multi-column function +-- RTE is used so that the reference is a genuine whole-row Var (a single +-- scalar-returning function would collapse to its lone column). This +-- exercises the THEN ROW(...) side of deparseColumnRef()'s whole-row CASE +-- (matched rows reconstruct the composite) as well as the NULL side +-- (missed rows), confirming the executor rebuilds the anonymous composite +-- correctly. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; +SELECT l.a, t FROM remote_tbl l + LEFT JOIN (remote_tbl r JOIN unnest(array[2, 4], array[20, 40]) AS t(x, y) + ON r.a = t.x) + ON l.a = r.a + WHERE l.a < 6 ORDER BY l.a; +RESET enable_hashjoin; +RESET enable_mergejoin; +RESET enable_nestloop; + +-- Check foreign join with parameterized function +CREATE OR REPLACE FUNCTION f(int) RETURNS SETOF int LANGUAGE plpgsql ROWS 10 AS 'BEGIN RETURN QUERY SELECT generate_series(1,$1) ; END' IMMUTABLE; +ALTER EXTENSION postgres_fdw ADD FUNCTION f(INTEGER); + +-- The correlated subquery keeps r1 in an enclosing query level, so the +-- function argument reaches the remote side as a query parameter. The +-- restriction on the function's own column is pushed down as well. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r1.a FROM remote_tbl r1 +WHERE EXISTS (SELECT 1 FROM remote_tbl r2, f(r1.a) g + WHERE r2.a = g AND g > 20); +SELECT r1.a FROM remote_tbl r1 +WHERE EXISTS (SELECT 1 FROM remote_tbl r2, f(r1.a) g + WHERE r2.a = g AND g > 20) +ORDER BY r1.a; + +ALTER EXTENSION postgres_fdw DROP FUNCTION f(INTEGER); +DROP FUNCTION f(INTEGER); + +-- Volatile function in ROWS FROM disqualifies the whole RTE. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r, + ROWS FROM (unnest(array[3, 6, 9]), + generate_series(1, 4 + (random() * 0)::int)) AS t(n, s) + WHERE r.a = t.n; + +-- LATERAL function referencing a foreign Var: postgres_fdw's +-- foreign-join pushdown rejects this via the joinrel->lateral_relids +-- check; the plan is therefore a local NestLoop + FunctionScan. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.x FROM remote_tbl r, LATERAL unnest(array[r.a]) AS t(x) +WHERE r.a <= 3 ORDER BY r.a; + +-- Outer joins with the function RTE are not pushed down (only INNER +-- joins are supported by function_rte_pushdown_ok()). +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a, t.n FROM remote_tbl r + LEFT JOIN unnest(array[1, 2, 3]) AS t(n) ON r.a = t.n + WHERE r.a <= 5 ORDER BY r.a; + +-- SEMI join (EXISTS) with a function RTE is also not pushed down. +EXPLAIN (VERBOSE, COSTS OFF) +SELECT r.a FROM remote_tbl r + WHERE EXISTS (SELECT 1 FROM unnest(array[3, 6, 9]) AS t(n) WHERE t.n = r.a) + ORDER BY r.a; + +DROP FOREIGN TABLE remote_tbl; +DROP TABLE base_tbl_fn; + -- ==================================================================== -- Check that userid to use when querying the remote table is correctly -- propagated into foreign rels present in subqueries under an UNION ALL diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml index 171a009b610..87b1433aacb 100644 --- a/doc/src/sgml/postgres-fdw.sgml +++ b/doc/src/sgml/postgres-fdw.sgml @@ -1200,6 +1200,24 @@ CREATE SUBSCRIPTION my_subscription SERVER subscription_server PUBLICATION testp <literal>WHERE</literal> clauses. </para> + <para> + An <literal>INNER JOIN</literal> between a foreign table and a set-returning + function appearing as a <literal>FROM</literal>-list item can likewise be + pushed down: the function call is absorbed into the remote query so that + only rows matching the function's output are fetched. This is attempted + only when the function is <literal>IMMUTABLE</literal> (so evaluating it on + the remote server is guaranteed to produce the same result as evaluating + it locally), its arguments and any restriction clauses on it are + shippable, and none of the following disqualifying conditions applies: + the join type is not <literal>INNER</literal>; the function is used with + <literal>WITH ORDINALITY</literal>; the function returns a + <type>record</type> type without an accompanying column definition list; + or the function laterally references another relation at the same query + level. A function argument that is a parameter from an enclosing query + level is allowed and is transmitted to the remote server as a query + parameter. + </para> + <para> The query that is actually sent to the remote server for execution can be examined using <command>EXPLAIN VERBOSE</command>. diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 687e923c46c..ee69f81945f 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -746,6 +746,31 @@ set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, joinrel->fdwroutine = outer_rel->fdwroutine; } } + else if (OidIsValid(outer_rel->serverid) && + inner_rel->rtekind == RTE_FUNCTION) + { + /* + * One side is a foreign relation, the other side is a function RTE. + * If the function is IMMUTABLE, the FDW can absorb the function call + * into the remote query (the result is identical regardless of which + * server evaluates it). Let the FDW decide whether the join is + * actually shippable; here we just propagate the FDW routine so the + * FDW gets a chance. + */ + joinrel->serverid = outer_rel->serverid; + joinrel->userid = outer_rel->userid; + joinrel->useridiscurrent = outer_rel->useridiscurrent; + joinrel->fdwroutine = outer_rel->fdwroutine; + } + else if (OidIsValid(inner_rel->serverid) && + outer_rel->rtekind == RTE_FUNCTION) + { + /* Same as just above, with the two sides swapped. */ + joinrel->serverid = inner_rel->serverid; + joinrel->userid = inner_rel->userid; + joinrel->useridiscurrent = inner_rel->useridiscurrent; + joinrel->fdwroutine = inner_rel->fdwroutine; + } } /* -- 2.55.0
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
@ 2026-08-17 06:57                                 ` Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-17 09:42                                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Pyhalov @ 2026-08-17 06:57 UTC (permalink / raw)
  To: Alexander Korotkov <aekorotkov@gmail.com>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Alexander Korotkov писал(а) 2026-08-15 03:49:
> Hi!
> 
>> Hi. I've updated comment a bit, as we currently have to handle NULL
>> records correctly,
>> this is not a nice-to-have feature which we need for future changes to
>> be more safe.
> 
> Thank you. I've further improved that comment.  Also, I've revised the
> cost calculation in init_func_stub_fpinfo() to reflect the cost of the
> function execution on the remote side.  I have to edit the regression
> test query to reliably exercise the pushdown.
> 
> ------
> Regards,
> Alexander Korotkov
> Supabase

Hi.
Looks good to me.
-- 
Best regards,
Alexander Pyhalov,
Postgres Professional






^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-08-17 09:42                                   ` Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-19 14:15                                     ` Re: Function scan FDW pushdown Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Korotkov @ 2026-08-17 09:42 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi!

On Mon, Aug 17, 2026 at 9:57 AM Alexander Pyhalov
<a.pyhalov@postgrespro.ru> wrote:
>
> Alexander Korotkov писал(а) 2026-08-15 03:49:
> > Hi!
> >
> >> Hi. I've updated comment a bit, as we currently have to handle NULL
> >> records correctly,
> >> this is not a nice-to-have feature which we need for future changes to
> >> be more safe.
> >
> > Thank you. I've further improved that comment.  Also, I've revised the
> > cost calculation in init_func_stub_fpinfo() to reflect the cost of the
> > function execution on the remote side.  I have to edit the regression
> > test query to reliably exercise the pushdown.
> >
> > ------
> > Regards,
> > Alexander Korotkov
> > Supabase
>
> Hi.
> Looks good to me.

Good.  I'm going to push this if no objections.

------
Regards,
Alexander Korotkov
Supabase






^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-17 09:42                                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
@ 2026-08-19 14:15                                     ` Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
  2026-08-19 14:21                                       ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  0 siblings, 1 reply; 36+ messages in thread

From: Anthonin Bonnefoy @ 2026-08-19 14:15 UTC (permalink / raw)
  To: Alexander Korotkov <aekorotkov@gmail.com>; +Cc: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

It seems like this patch introduced a compilation warning[0]:

postgres_fdw.c: In function 'postgresExplainForeignScan':
postgres_fdw.c:3221:36: error: 'relname' may be used uninitialized
[-Werror=maybe-uninitialized]
 3221 |                                 if (relname == NULL ||
strcmp(refname, relname) != 0)
      |                                    ^
postgres_fdw.c:3132:45: note: 'relname' was declared here
 3132 |                                 char       *relname;
      |                                             ^~~~~~~

Setting relname to NULL during declaration fixes the warning and seems
to be the expected behavior?

[0]: https://github.com/postgres/postgres/actions/runs/32244563943/job/96042498375

Regards,
Anthonin Bonnefoy

Attachments:

v1-0001-Fix-compilation-warning-after-0ee83dd4.patch (application/octet-stream, 795B) download From d749027a1970ddcb717d3a10cc98c29ad9101813 Mon Sep 17 00:00:00 2001 From: Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com> Date: Wed, 19 Aug 2026 16:00:40 +0200 Subject: Fix compilation warning after 0ee83dd4 --- contrib/postgres_fdw/postgres_fdw.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 6aaae58eff9..95b8fdc2240 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -3129,7 +3129,7 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) { int rti = strtol(ptr, &ptr, 10); RangeTblEntry *rte; - char *relname; + char *relname = NULL; char *refname; rti += rtoffset; -- 2.55.0
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-17 09:42                                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-19 14:15                                     ` Re: Function scan FDW pushdown Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
@ 2026-08-19 14:21                                       ` Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-19 14:31                                         ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-28 13:18                                         ` Re: Function scan FDW pushdown Karina Litskevich <litskevichkarina@gmail.com>
  0 siblings, 2 replies; 36+ messages in thread

From: Alexander Pyhalov @ 2026-08-19 14:21 UTC (permalink / raw)
  To: Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>; +Cc: Alexander Korotkov <aekorotkov@gmail.com>; solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Anthonin Bonnefoy писал(а) 2026-08-19 17:15:
> Hi,
> 
> It seems like this patch introduced a compilation warning[0]:
> 
> postgres_fdw.c: In function 'postgresExplainForeignScan':
> postgres_fdw.c:3221:36: error: 'relname' may be used uninitialized
> [-Werror=maybe-uninitialized]
>  3221 |                                 if (relname == NULL ||
> strcmp(refname, relname) != 0)
>       |                                    ^
> postgres_fdw.c:3132:45: note: 'relname' was declared here
>  3132 |                                 char       *relname;
>       |                                             ^~~~~~~
> 
> Setting relname to NULL during declaration fixes the warning and seems
> to be the expected behavior?
> 
> [0]: 
> https://github.com/postgres/postgres/actions/runs/32244563943/job/96042498375
> 
> Regards,
> Anthonin Bonnefoy

Yes, you are correct. Sorry, missed this fix...
-- 
Best regards,
Alexander Pyhalov,
Postgres Professional






^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-17 09:42                                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-19 14:15                                     ` Re: Function scan FDW pushdown Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
  2026-08-19 14:21                                       ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-08-19 14:31                                         ` Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-24 15:12                                           ` Re: Function scan FDW pushdown Sami Imseih <samimseih@gmail.com>
  1 sibling, 1 reply; 36+ messages in thread

From: Alexander Korotkov @ 2026-08-19 14:31 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>; solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Aug 19, 2026 at 5:21 PM Alexander Pyhalov
<a.pyhalov@postgrespro.ru> wrote:
> Anthonin Bonnefoy писал(а) 2026-08-19 17:15:
> > Hi,
> >
> > It seems like this patch introduced a compilation warning[0]:
> >
> > postgres_fdw.c: In function 'postgresExplainForeignScan':
> > postgres_fdw.c:3221:36: error: 'relname' may be used uninitialized
> > [-Werror=maybe-uninitialized]
> >  3221 |                                 if (relname == NULL ||
> > strcmp(refname, relname) != 0)
> >       |                                    ^
> > postgres_fdw.c:3132:45: note: 'relname' was declared here
> >  3132 |                                 char       *relname;
> >       |                                             ^~~~~~~
> >
> > Setting relname to NULL during declaration fixes the warning and seems
> > to be the expected behavior?
> >
> > [0]:
> > https://github.com/postgres/postgres/actions/runs/32244563943/job/96042498375
> >
> > Regards,
> > Anthonin Bonnefoy
>
> Yes, you are correct. Sorry, missed this fix...

Sorry, I missed that too.  Pushed.

------
Regards,
Alexander Korotkov
Supabase






^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-17 09:42                                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-19 14:15                                     ` Re: Function scan FDW pushdown Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
  2026-08-19 14:21                                       ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-19 14:31                                         ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
@ 2026-08-24 15:12                                           ` Sami Imseih <samimseih@gmail.com>
  0 siblings, 0 replies; 36+ messages in thread

From: Sami Imseih @ 2026-08-24 15:12 UTC (permalink / raw)
  To: Alexander Korotkov <aekorotkov@gmail.com>; +Cc: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>; solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

I am raising this [1] here, in case it was missed.

The unnest function portion of the test introduced in this commit
is unstable. [1] includes a patch to fix this.

[1] https://www.postgresql.org/message-id/flat/CAA5RZ0uC%3DGOihOKcF7o3JVETF3e-Fkc4OUO5NbqMEKCTeSN-dQ%40m...

--
Sami Imseih
Amazon Web Services (AWS)






^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-17 09:42                                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-19 14:15                                     ` Re: Function scan FDW pushdown Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
  2026-08-19 14:21                                       ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
@ 2026-08-28 13:18                                         ` Karina Litskevich <litskevichkarina@gmail.com>
  2026-08-29 19:21                                           ` Re: Function scan FDW pushdown Marina Polyakova <m.polyakova@postgrespro.ru>
  1 sibling, 1 reply; 36+ messages in thread

From: Karina Litskevich @ 2026-08-28 13:18 UTC (permalink / raw)
  To: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; +Cc: Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>; Alexander Korotkov <aekorotkov@gmail.com>; solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi!

Here is another compilation warning that seems to be caused by this patch.

postgres_fdw.c: In function ‘foreign_join_ok’:
postgres_fdw.c:7135:46: error: ‘fpinfo_i’ may be used uninitialized
[-Werror=maybe-uninitialized]
 7135 |         if (fpinfo_o->local_conds || fpinfo_i->local_conds)
      |                                      ~~~~~~~~^~~~~~~~~~~~~
postgres_fdw.c:7044:28: note: ‘fpinfo_i’ was declared here
 7044 |         PgFdwRelationInfo *fpinfo_i;
      |                            ^~~~~~~~

Best regards,
Karina Litskevich
Postgres Professional: http://postgrespro.com/

^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-17 09:42                                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-19 14:15                                     ` Re: Function scan FDW pushdown Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
  2026-08-19 14:21                                       ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-28 13:18                                         ` Re: Function scan FDW pushdown Karina Litskevich <litskevichkarina@gmail.com>
@ 2026-08-29 19:21                                           ` Marina Polyakova <m.polyakova@postgrespro.ru>
  2026-09-01 22:11                                             ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Marina Polyakova @ 2026-08-29 19:21 UTC (permalink / raw)
  To: Karina Litskevich <litskevichkarina@gmail.com>; +Cc: Alexander Pyhalov <a.pyhalov@postgrespro.ru>; Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>; Alexander Korotkov <aekorotkov@gmail.com>; solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hello!

I got this warning with gcc-13 ([1], [2]) and CFLAGS=-Og (both -O0 and 
-O1 work fine). Both gcc-12 [3] and gcc-14 [4] work fine with 
CFLAGS=-Og. IMO this compiler warning is strange because the attached 
patch with a simple code reordering fixes it.

[1] https://github.com/gcc-mirror/gcc/releases/tag/releases%2Fgcc-13.3.0
[2] https://github.com/gcc-mirror/gcc/releases/tag/releases%2Fgcc-13.4.0
[3] Ubuntu 12.3.0-1ubuntu1~22.04.3 12.3.0
[4] https://github.com/gcc-mirror/gcc/releases/tag/releases%2Fgcc-14.4.0

On 2026-08-28 16:18, Karina Litskevich wrote:
> Hi!
> 
> Here is another compilation warning that seems to be caused by this
> patch.
> 
> postgres_fdw.c: In function ‘foreign_join_ok’:
> postgres_fdw.c:7135:46: error: ‘fpinfo_i’ may be used
> uninitialized [-Werror=maybe-uninitialized]
>  7135 |         if (fpinfo_o->local_conds || fpinfo_i->local_conds)
>       |                                      ~~~~~~~~^~~~~~~~~~~~~
> postgres_fdw.c:7044:28: note: ‘fpinfo_i’ was declared here
>  7044 |         PgFdwRelationInfo *fpinfo_i;
>       |                            ^~~~~~~~
> 
> Best regards,
> Karina Litskevich
> Postgres Professional: http://postgrespro.com/

-- 
Marina Polyakova
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

Attachments:

diff_fix_warning.patch (text/x-diff, 2.9K) download diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 9269418a074c3bce26af742d8fbb3550b65e130e..fb61e6e7978c4c9ad683a8d36c4cca08eafcba7d 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -7044,8 +7044,6 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; - bool outer_is_function = false; - bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -7075,34 +7073,6 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && fpinfo_o->pushdown_safe && function_rte_pushdown_ok(root, innerrel, outerrel)) - { - inner_is_function = true; - } - else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && - (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && - fpinfo_i->pushdown_safe && - function_rte_pushdown_ok(root, outerrel, innerrel)) - { - outer_is_function = true; - } - else - { - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; - } - - /* - * If one side is a function RTE, allocate a stub fpinfo so the rest of - * this function and the cost estimator can treat it uniformly. We hand - * the stub to the joinrel's deparser via the same path the foreign side - * uses, but we never permanently attach it to the function rel's - * fdw_private (different joinrels may pair the same function RTE with - * different foreign servers). - */ - if (inner_is_function) { fpinfo_i = init_func_stub_fpinfo(fpinfo_o, innerrel); @@ -7117,7 +7087,10 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, &fpinfo_i->remote_conds, &fpinfo_i->local_conds); fpinfo->inner_func_fpinfo = fpinfo_i; } - else if (outer_is_function) + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && + fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) { fpinfo_o = init_func_stub_fpinfo(fpinfo_i, outerrel); @@ -7126,6 +7099,14 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, &fpinfo_o->remote_conds, &fpinfo_o->local_conds); fpinfo->outer_func_fpinfo = fpinfo_o; } + else + { + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; + } /* * If joining relations have local conditions, those conditions are
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-17 09:42                                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-19 14:15                                     ` Re: Function scan FDW pushdown Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
  2026-08-19 14:21                                       ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-28 13:18                                         ` Re: Function scan FDW pushdown Karina Litskevich <litskevichkarina@gmail.com>
  2026-08-29 19:21                                           ` Re: Function scan FDW pushdown Marina Polyakova <m.polyakova@postgrespro.ru>
@ 2026-09-01 22:11                                             ` Alexander Korotkov <aekorotkov@gmail.com>
  2026-09-02 03:08                                               ` Re: Function scan FDW pushdown Marina Polyakova <m.polyakova@postgrespro.ru>
  0 siblings, 1 reply; 36+ messages in thread

From: Alexander Korotkov @ 2026-09-01 22:11 UTC (permalink / raw)
  To: Marina Polyakova <m.polyakova@postgrespro.ru>; +Cc: Karina Litskevich <litskevichkarina@gmail.com>; Alexander Pyhalov <a.pyhalov@postgrespro.ru>; Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>; solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Sat, Aug 29, 2026 at 10:21 PM Marina Polyakova
<m.polyakova@postgrespro.ru> wrote:
> I got this warning with gcc-13 ([1], [2]) and CFLAGS=-Og (both -O0 and
> -O1 work fine). Both gcc-12 [3] and gcc-14 [4] work fine with
> CFLAGS=-Og. IMO this compiler warning is strange because the attached
> patch with a simple code reordering fixes it.
>
> [1] https://github.com/gcc-mirror/gcc/releases/tag/releases%2Fgcc-13.3.0
> [2] https://github.com/gcc-mirror/gcc/releases/tag/releases%2Fgcc-13.4.0
> [3] Ubuntu 12.3.0-1ubuntu1~22.04.3 12.3.0
> [4] https://github.com/gcc-mirror/gcc/releases/tag/releases%2Fgcc-14.4.0
>
> On 2026-08-28 16:18, Karina Litskevich wrote:
> > Hi!
> >
> > Here is another compilation warning that seems to be caused by this
> > patch.
> >
> > postgres_fdw.c: In function ‘foreign_join_ok’:
> > postgres_fdw.c:7135:46: error: ‘fpinfo_i’ may be used
> > uninitialized [-Werror=maybe-uninitialized]
> >  7135 |         if (fpinfo_o->local_conds || fpinfo_i->local_conds)
> >       |                                      ~~~~~~~~^~~~~~~~~~~~~
> > postgres_fdw.c:7044:28: note: ‘fpinfo_i’ was declared here
> >  7044 |         PgFdwRelationInfo *fpinfo_i;
> >       |                            ^~~~~~~~

Yes, compiler may fail to trace invariants of
inner_is_function/outer_is_function flags usage. I suggest to remove
them altogether.  See the attached patch.  I think this code also
becomes a bit more readable.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

v1-0001-postgres_fdw-Fix-may-be-used-uninitialized-warnin.patch (application/octet-stream, 5.0K) download From 336124160b13cecdfa3824d7a3df8143bf93081e Mon Sep 17 00:00:00 2001 From: Alexander Korotkov <akorotkov@postgresql.org> Date: Tue, 1 Sep 2026 22:55:13 +0300 Subject: [PATCH v1] postgres_fdw: Fix "may be used uninitialized" warning in foreign_join_ok() Commit 0ee83dd4a99 detected the mixed foreign x function-RTE cases in one if/else chain that only set a pair of bool flags, then acted on those flags in a second chain. fpinfo_o and fpinfo_i are each assigned in one chain and read in the other, so proving them initialized requires correlating the flags with the assignments. gcc 13 with -Og does not manage that and reports fpinfo_i as possibly uninitialized; clang's -Wconditional-uninitialized likewise reports both variables. The flags served no purpose beyond deferring the work, so merge the two chains and read both fdw_private pointers up front, unconditionally. A function rel never has an fdw_private of its own, so the pointer is simply NULL until the stub replaces it, and each branch now assigns and uses the two variables in one place. Reported-by: Karina Litskevich <litskevichkarina@gmail.com> Reported-by: Marina Polyakova <m.polyakova@postgrespro.ru> Discussion: https://postgr.es/m/CACiT8iamoL-%3D792e6JK2uCVvwDhfCg7DXHhvqN0P33jhGg2-8A%40mail.gmail.com --- contrib/postgres_fdw/postgres_fdw.c | 53 +++++++++++------------------ 1 file changed, 19 insertions(+), 34 deletions(-) diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index 9269418a074..47197a733ff 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -7044,8 +7044,6 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, PgFdwRelationInfo *fpinfo_i; ListCell *lc; List *joinclauses; - bool outer_is_function = false; - bool inner_is_function = false; /* * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins. @@ -7069,40 +7067,22 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, * function RTE can be absorbed into joins on multiple foreign servers * (each call gets its own stub fpinfo and rechecks shippability for the * specific server). + * + * A function rel has no fdw_private of its own, so when one side is a + * function RTE we replace its NULL fpinfo with a stub, and the rest of + * this function and the cost estimator can then treat both sides + * uniformly. We hand the stub to the joinrel's deparser via the same + * path the foreign side uses, but we never permanently attach it to the + * function rel's fdw_private (different joinrels may pair the same + * function RTE with different foreign servers). */ fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private; + fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; + fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; + if (jointype == JOIN_INNER && innerrel->rtekind == RTE_FUNCTION && - (fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private) && - fpinfo_o->pushdown_safe && + fpinfo_o && fpinfo_o->pushdown_safe && function_rte_pushdown_ok(root, innerrel, outerrel)) - { - inner_is_function = true; - } - else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && - (fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private) && - fpinfo_i->pushdown_safe && - function_rte_pushdown_ok(root, outerrel, innerrel)) - { - outer_is_function = true; - } - else - { - fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private; - fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private; - if (!fpinfo_o || !fpinfo_o->pushdown_safe || - !fpinfo_i || !fpinfo_i->pushdown_safe) - return false; - } - - /* - * If one side is a function RTE, allocate a stub fpinfo so the rest of - * this function and the cost estimator can treat it uniformly. We hand - * the stub to the joinrel's deparser via the same path the foreign side - * uses, but we never permanently attach it to the function rel's - * fdw_private (different joinrels may pair the same function RTE with - * different foreign servers). - */ - if (inner_is_function) { fpinfo_i = init_func_stub_fpinfo(fpinfo_o, innerrel); @@ -7117,15 +7097,20 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, &fpinfo_i->remote_conds, &fpinfo_i->local_conds); fpinfo->inner_func_fpinfo = fpinfo_i; } - else if (outer_is_function) + else if (jointype == JOIN_INNER && outerrel->rtekind == RTE_FUNCTION && + fpinfo_i && fpinfo_i->pushdown_safe && + function_rte_pushdown_ok(root, outerrel, innerrel)) { fpinfo_o = init_func_stub_fpinfo(fpinfo_i, outerrel); - /* See the comment in the inner_is_function branch above. */ + /* See the comment in the branch above. */ classifyConditions(root, outerrel, fpinfo_o, outerrel->baserestrictinfo, &fpinfo_o->remote_conds, &fpinfo_o->local_conds); fpinfo->outer_func_fpinfo = fpinfo_o; } + else if (!fpinfo_o || !fpinfo_o->pushdown_safe || + !fpinfo_i || !fpinfo_i->pushdown_safe) + return false; /* * If joining relations have local conditions, those conditions are -- 2.55.0
^ permalink raw reply [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-17 09:42                                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-19 14:15                                     ` Re: Function scan FDW pushdown Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
  2026-08-19 14:21                                       ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-28 13:18                                         ` Re: Function scan FDW pushdown Karina Litskevich <litskevichkarina@gmail.com>
  2026-08-29 19:21                                           ` Re: Function scan FDW pushdown Marina Polyakova <m.polyakova@postgrespro.ru>
  2026-09-01 22:11                                             ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
@ 2026-09-02 03:08                                               ` Marina Polyakova <m.polyakova@postgrespro.ru>
  2026-09-02 12:50                                                 ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  0 siblings, 1 reply; 36+ messages in thread

From: Marina Polyakova @ 2026-09-02 03:08 UTC (permalink / raw)
  To: Alexander Korotkov <aekorotkov@gmail.com>; +Cc: Karina Litskevich <litskevichkarina@gmail.com>; Alexander Pyhalov <a.pyhalov@postgrespro.ru>; Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>; solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

The attached patch fixes the warning with CFLAGS=-Og and gcc-13 
described above, and removes outer_is_function/inner_is_function 
variables which were used only once. Thank you!

On 2026-09-02 01:11, Alexander Korotkov wrote:
> On Sat, Aug 29, 2026 at 10:21 PM Marina Polyakova
> <m.polyakova@postgrespro.ru> wrote:
>> I got this warning with gcc-13 ([1], [2]) and CFLAGS=-Og (both -O0 and
>> -O1 work fine). Both gcc-12 [3] and gcc-14 [4] work fine with
>> CFLAGS=-Og. IMO this compiler warning is strange because the attached
>> patch with a simple code reordering fixes it.
>> 
>> [1] 
>> https://github.com/gcc-mirror/gcc/releases/tag/releases%2Fgcc-13.3.0
>> [2] 
>> https://github.com/gcc-mirror/gcc/releases/tag/releases%2Fgcc-13.4.0
>> [3] Ubuntu 12.3.0-1ubuntu1~22.04.3 12.3.0
>> [4] 
>> https://github.com/gcc-mirror/gcc/releases/tag/releases%2Fgcc-14.4.0
>> 
>> On 2026-08-28 16:18, Karina Litskevich wrote:
>> > Hi!
>> >
>> > Here is another compilation warning that seems to be caused by this
>> > patch.
>> >
>> > postgres_fdw.c: In function ‘foreign_join_ok’:
>> > postgres_fdw.c:7135:46: error: ‘fpinfo_i’ may be used
>> > uninitialized [-Werror=maybe-uninitialized]
>> >  7135 |         if (fpinfo_o->local_conds || fpinfo_i->local_conds)
>> >       |                                      ~~~~~~~~^~~~~~~~~~~~~
>> > postgres_fdw.c:7044:28: note: ‘fpinfo_i’ was declared here
>> >  7044 |         PgFdwRelationInfo *fpinfo_i;
>> >       |                            ^~~~~~~~
> 
> Yes, compiler may fail to trace invariants of
> inner_is_function/outer_is_function flags usage. I suggest to remove
> them altogether.  See the attached patch.  I think this code also
> becomes a bit more readable.
> 
> ------
> Regards,
> Alexander Korotkov
> Supabase

-- 
Best regards,
Marina Polyakova
Postgres Professional: http://www.postgrespro.com






^ permalink  raw  reply  [nested|flat] 36+ messages in thread

* Re: Function scan FDW pushdown
  2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
  2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-17 09:42                                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-08-19 14:15                                     ` Re: Function scan FDW pushdown Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
  2026-08-19 14:21                                       ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
  2026-08-28 13:18                                         ` Re: Function scan FDW pushdown Karina Litskevich <litskevichkarina@gmail.com>
  2026-08-29 19:21                                           ` Re: Function scan FDW pushdown Marina Polyakova <m.polyakova@postgrespro.ru>
  2026-09-01 22:11                                             ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
  2026-09-02 03:08                                               ` Re: Function scan FDW pushdown Marina Polyakova <m.polyakova@postgrespro.ru>
@ 2026-09-02 12:50                                                 ` Alexander Korotkov <aekorotkov@gmail.com>
  0 siblings, 0 replies; 36+ messages in thread

From: Alexander Korotkov @ 2026-09-02 12:50 UTC (permalink / raw)
  To: Marina Polyakova <m.polyakova@postgrespro.ru>; +Cc: Karina Litskevich <litskevichkarina@gmail.com>; Alexander Pyhalov <a.pyhalov@postgrespro.ru>; Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>; solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>; Álvaro Herrera <alvherre@kurilemu.de>; g.kashkin@postgrespro.ru, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Sep 2, 2026 at 6:08 AM Marina Polyakova
<m.polyakova@postgrespro.ru> wrote:
> The attached patch fixes the warning with CFLAGS=-Og and gcc-13
> described above, and removes outer_is_function/inner_is_function
> variables which were used only once. Thank you!

Pushed, thank you!

------
Regards,
Alexander Korotkov
Supabase






^ permalink  raw  reply  [nested|flat] 36+ messages in thread


end of thread, other threads:[~2026-09-02 12:50 UTC | newest]

Thread overview: 36+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2019-11-28 22:08 [PATCH 2/6] silence compiler warning Alvaro Herrera <alvherre@alvh.no-ip.org>
2021-05-20 17:43 Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2021-06-15 13:15 ` Re: Function scan FDW pushdown Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2021-10-04 07:42   ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2024-11-05 16:11     ` Re: Function scan FDW pushdown g.kashkin@postgrespro.ru
2025-08-05 21:32       ` Re: Function scan FDW pushdown Álvaro Herrera <alvherre@kurilemu.de>
2026-03-18 12:08 Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2026-05-06 06:59 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2026-05-08 05:17   ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
2026-05-08 06:03     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2026-05-10 22:22       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
2026-05-11 06:01         ` Re: Function scan FDW pushdown solaimurugan vellaipandiyan <drsolaimurugan.v@gmail.com>
2026-05-11 12:02           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
2026-05-12 08:09         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2026-05-18 10:34           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
2026-05-18 20:06             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2026-05-19 13:00               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
2026-05-19 15:25                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2026-05-19 18:21                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
2026-05-20 10:17                     ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2026-07-06 14:11                       ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
2026-07-07 10:25                         ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2026-07-30 21:19                           ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
2026-07-31 06:19                             ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2026-08-15 00:49                               ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
2026-08-17 06:57                                 ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2026-08-17 09:42                                   ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
2026-08-19 14:15                                     ` Re: Function scan FDW pushdown Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
2026-08-19 14:21                                       ` Re: Function scan FDW pushdown Alexander Pyhalov <a.pyhalov@postgrespro.ru>
2026-08-19 14:31                                         ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
2026-08-24 15:12                                           ` Re: Function scan FDW pushdown Sami Imseih <samimseih@gmail.com>
2026-08-28 13:18                                         ` Re: Function scan FDW pushdown Karina Litskevich <litskevichkarina@gmail.com>
2026-08-29 19:21                                           ` Re: Function scan FDW pushdown Marina Polyakova <m.polyakova@postgrespro.ru>
2026-09-01 22:11                                             ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>
2026-09-02 03:08                                               ` Re: Function scan FDW pushdown Marina Polyakova <m.polyakova@postgrespro.ru>
2026-09-02 12:50                                                 ` Re: Function scan FDW pushdown Alexander Korotkov <aekorotkov@gmail.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox