pg.ddx.io pgsql-hackers@postgresql.org mailing list archive
help / color / mirror / Atom feedexplain plans for foreign servers
31+ messages / 11 participants
[nested] [flat]
* explain plans for foreign servers
@ 2024-11-11 15:42 dinesh salve <cooltodinesh@gmail.com>
0 siblings, 4 replies; 31+ messages in thread
From: dinesh salve @ 2024-11-11 15:42 UTC (permalink / raw)
To: pgsql-hackers
Hi Hackers,
I am working on a feature in postgres_fdw extension to show plans used by
remote postgresql servers in the output of the EXPLAIN command.
I think this will help end users understand query execution plans used by
remote servers. Sample output for table people where people_1 is local
partition and people_2 is remote partition would look like -
postgres:5432> explain select * from "test"."people";
QUERY PLAN
Append (cost=0.00..399.75 rows=2270 width=46)
→ Seq Scan on "people.people_1" people_1 (cost=0.00..21.00 rows=1100
width=46)
→ Foreign Scan on "people.people_2" people_2 (cost=100.00..367.40
rows=1170 width=46)
Remote Plan
Seq Scan on "people.people_2" (cost=0.00..21.00 rows=1100
width=46)
(5 rows)
I would like community inputs on below high level thoughts:
1. To enable this feature, either we can introduce a new option in EXPLAIN
command e.g. (fetch_remote_plans true) or control this behaviour using a
guc defined in postgres_fdw extension. I am more inclined towards guc
as this feature is for extension postgres_fdw. Adding the EXPLAIN command
option might force other FDW extensions to handle this.
2. For ANALYZE = false, the idea is that postgres_fdw would create a
connection to a remote server, prepare SQL to send over connection and
store received plans in ExplainState.
3. For ANALYZE = true, idea is that postgres_fdw would set a new guc over
connection to remote server, remote server postgres_fdw would read this guc
and send back used query plan as a NOTICE (similar to auto_explain
extension does) with custom header which postgres_fdw extension
understands. . We also have an opportunity to introduce a new message type
in the protocol to send back explain plans but it might look like too much
work for this feature. Open to ideas here.
Dinesh Salve
SDE@AWS
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2024-11-12 00:33 Andy Fan <zhihuifan1213@163.com>
parent: dinesh salve <cooltodinesh@gmail.com>
3 siblings, 0 replies; 31+ messages in thread
From: Andy Fan @ 2024-11-12 00:33 UTC (permalink / raw)
To: dinesh salve <cooltodinesh@gmail.com>; +Cc: pgsql-hackers
dinesh salve <cooltodinesh@gmail.com> writes:
Hi,
>
> I am working on a feature in postgres_fdw extension to show plans used
> by remote postgresql servers in the output of the EXPLAIN command.
>
> I think this will help end users understand query execution plans used
> by remote servers. Sample output for table people where people_1 is
> local partition and people_2 is remote partition would look like
This looks nice! Especially for the people who want a FDW based sharding
cluster.
> I would like community inputs on below high level thoughts:
>
> 1. To enable this feature, either we can introduce a new option in
> EXPLAIN command e.g. (fetch_remote_plans true) or control this
> behaviour using a guc defined in postgres_fdw extension. I am more
> inclined towards guc as this feature is for extension
> postgres_fdw. Adding the EXPLAIN command option might force other FDW
> extensions to handle this.
+1.
> 2. For ANALYZE = false, the idea is that postgres_fdw would create a
> connection to a remote server, prepare SQL to send over connection and
> store received plans in ExplainState.
> 3. For ANALYZE = true, idea is that postgres_fdw would set a new guc
> over connection to remote server, remote server postgres_fdw would
> read this guc and send back used query plan as a NOTICE (similar to
> auto_explain extension does) with custom header which postgres_fdw
> extension understands. We also have an opportunity to introduce a new
> message type in the protocol to send back explain plans but it might
> look like too much work for this feature. Open to ideas here.
This generally looks good to me. Looking forward a patch for the
details.
--
Best Regards
Andy Fan
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2024-11-12 10:46 Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
parent: dinesh salve <cooltodinesh@gmail.com>
3 siblings, 1 reply; 31+ messages in thread
From: Ashutosh Bapat @ 2024-11-12 10:46 UTC (permalink / raw)
To: dinesh salve <cooltodinesh@gmail.com>; +Cc: pgsql-hackers
On Mon, Nov 11, 2024 at 9:12 PM dinesh salve <cooltodinesh@gmail.com> wrote:
>
>
> Hi Hackers,
>
> I am working on a feature in postgres_fdw extension to show plans used by remote postgresql servers in the output of the EXPLAIN command.
> I think this will help end users understand query execution plans used by remote servers. Sample output for table people where people_1 is local partition and people_2 is remote partition would look like -
>
> postgres:5432> explain select * from "test"."people";
> QUERY PLAN
> Append (cost=0.00..399.75 rows=2270 width=46)
> → Seq Scan on "people.people_1" people_1 (cost=0.00..21.00 rows=1100 width=46)
> → Foreign Scan on "people.people_2" people_2 (cost=100.00..367.40 rows=1170 width=46)
> Remote Plan
> Seq Scan on "people.people_2" (cost=0.00..21.00 rows=1100 width=46)
> (5 rows)
>
> I would like community inputs on below high level thoughts:
>
> 1. To enable this feature, either we can introduce a new option in EXPLAIN command e.g. (fetch_remote_plans true) or control this behaviour using a guc defined in postgres_fdw extension. I am more inclined towards guc as this feature is for extension postgres_fdw. Adding the EXPLAIN command option might force other FDW extensions to handle this.
>
> 2. For ANALYZE = false, the idea is that postgres_fdw would create a connection to a remote server, prepare SQL to send over connection and store received plans in ExplainState.
>
> 3. For ANALYZE = true, idea is that postgres_fdw would set a new guc over connection to remote server, remote server postgres_fdw would read this guc and send back used query plan as a NOTICE (similar to auto_explain extension does) with custom header which postgres_fdw extension understands. . We also have an opportunity to introduce a new message type in the protocol to send back explain plans but it might look like too much work for this feature. Open to ideas here.
If use_remote_estimates is enabled for a given foreign server,
postgres_fdw fetches EXPLAIN output and plugs those costs into the
local plan's costs. You could use that - display the remote plan only
when use_remote_estimates is enabled. However, there's no guarantee
that the plan so fetched will be the plan used by foreign server when
actually executing the query. Mostly likely that is true but no
guarantee. That's also true if the plan is fetched only for the final
query. Of course the EXPLAIN output differences between server
versions need to taken care of.
But the real question is usability. How do you plan to use it?
--
Best Wishes,
Ashutosh Bapat
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2024-11-22 21:02 dinesh salve <cooltodinesh@gmail.com>
parent: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 0 replies; 31+ messages in thread
From: dinesh salve @ 2024-11-22 21:02 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: pgsql-hackers
On Tue, Nov 12, 2024 at 4:16 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
wrote:
> On Mon, Nov 11, 2024 at 9:12 PM dinesh salve <cooltodinesh@gmail.com>
> wrote:
> >
> >
> > Hi Hackers,
> >
> > I am working on a feature in postgres_fdw extension to show plans used
> by remote postgresql servers in the output of the EXPLAIN command.
> > I think this will help end users understand query execution plans used
> by remote servers. Sample output for table people where people_1 is local
> partition and people_2 is remote partition would look like -
> >
> > postgres:5432> explain select * from "test"."people";
> > QUERY PLAN
> > Append (cost=0.00..399.75 rows=2270 width=46)
> > → Seq Scan on "people.people_1" people_1 (cost=0.00..21.00 rows=1100
> width=46)
> > → Foreign Scan on "people.people_2" people_2 (cost=100.00..367.40
> rows=1170 width=46)
> > Remote Plan
> > Seq Scan on "people.people_2" (cost=0.00..21.00 rows=1100
> width=46)
> > (5 rows)
> >
> > I would like community inputs on below high level thoughts:
> >
> > 1. To enable this feature, either we can introduce a new option in
> EXPLAIN command e.g. (fetch_remote_plans true) or control this behaviour
> using a guc defined in postgres_fdw extension. I am more inclined
> towards guc as this feature is for extension postgres_fdw. Adding the
> EXPLAIN command option might force other FDW extensions to handle this.
> >
> > 2. For ANALYZE = false, the idea is that postgres_fdw would create a
> connection to a remote server, prepare SQL to send over connection and
> store received plans in ExplainState.
> >
> > 3. For ANALYZE = true, idea is that postgres_fdw would set a new guc
> over connection to remote server, remote server postgres_fdw would read
> this guc and send back used query plan as a NOTICE (similar to auto_explain
> extension does) with custom header which postgres_fdw extension
> understands. . We also have an opportunity to introduce a new message type
> in the protocol to send back explain plans but it might look like too much
> work for this feature. Open to ideas here.
>
> If use_remote_estimates is enabled for a given foreign server,
> postgres_fdw fetches EXPLAIN output and plugs those costs into the
> local plan's costs. You could use that - display the remote plan only
> when use_remote_estimates is enabled. However, there's no guarantee
> that the plan so fetched will be the plan used by foreign server when
> actually executing the query. Mostly likely that is true but no
> guarantee. That's also true if the plan is fetched only for the final
> query. Of course the EXPLAIN output differences between server
> versions need to taken care of.
>
> But the real question is usability. How do you plan to use it?
> --
> Best Wishes,
> Ashutosh Bapat
>
Hi Ashutosh,
Thanks for the feedback.
1. As admins and devs need to look at plans from time to time, if a remote
plan is displayed only when use_remote_estimates is enabled, either the end
user needs to keep it enabled (at table or server level) all the time or
enable/disable when they want to view remote plans. I actually wanted to
decouple that action for the user and make it easy by just setting a guc ->
SET postgres_fdw.show_remote_explain_plans = on;
2. Yeah, plans are not guaranteed but this feature would give a high level
idea on overall query execution at one place. This could be pretty useful
when postgresql is used for sharding and tables are set up as partitions
and the end user wants to view overall query execution.
Dinesh Salve
SDE@AWS
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2024-11-25 16:53 Anton Shmigirilov <a.shmigirilov@postgrespro.ru>
parent: dinesh salve <cooltodinesh@gmail.com>
3 siblings, 1 reply; 31+ messages in thread
From: Anton Shmigirilov @ 2024-11-25 16:53 UTC (permalink / raw)
To: dinesh salve <cooltodinesh@gmail.com>; +Cc: pgsql-hackers
> Hi Hackers,
>
> I am working on a feature in postgres_fdw extension to show plans used by remote postgresql servers in the output of the EXPLAIN command.
> I think this will help end users understand query execution plans used by remote servers. Sample output for table people where people_1 is local partition and people_2 is remote partition would look like -
>
> postgres:5432> explain select * from "test"."people";
> QUERY PLAN
> Append (cost=0.00..399.75 rows=2270 width=46)
> → Seq Scan on "people.people_1" people_1 (cost=0.00..21.00 rows=1100 width=46)
> → Foreign Scan on "people.people_2" people_2 (cost=100.00..367.40 rows=1170 width=46)
> Remote Plan
> Seq Scan on "people.people_2" (cost=0.00..21.00 rows=1100 width=46)
> (5 rows)
>
> I would like community inputs on below high level thoughts:
>
> 1. To enable this feature, either we can introduce a new option in EXPLAIN command e.g. (fetch_remote_plans true) or control this behaviour using a guc defined in postgres_fdw extension. I am more inclined towards guc as this feature is for extension postgres_fdw. Adding the EXPLAIN command option might force other FDW extensions to handle this.
>
> 2. For ANALYZE = false, the idea is that postgres_fdw would create a connection to a remote server, prepare SQL to send over connection and store received plans in ExplainState.
>
> 3. For ANALYZE = true, idea is that postgres_fdw would set a new guc over connection to remote server, remote server postgres_fdw would read this guc and send back used query plan as a NOTICE (similar to auto_explain extension does) with custom header which postgres_fdw extension understands. . We also have an opportunity to introduce a new message type in the protocol to send back explain plans but it might look like too much work for this feature. Open to ideas here.
>
> Dinesh Salve
> SDE@AWS
Hi Dinesh,
Thank you for your proposal regarding explain for foreign servers.
I have been working on a similar feature and there are several considerations to take into account.
To enable this feature it is preferable to use GUC rather than the EXPLAIN option, as it simplifies regression testing. You can simply set it to off before most tests that involve plan checking, while leaving the rest unchanged. This leads to a reduction in the size of the differences.
If it is necessary to provide only the execution plan of the foreign query (without actual timing metrics), you should send EXPLAIN with ANALYZE set to OFF, regardless of the initial ANALYZE state. This approach will prevent the re-execution of the remote query (the SQL part of the ForeignScan node), which could potentially lead to side effects. It's safe to send ANALYZE ON during remote EXPLAIN only if your remote SQL is idempotent, i.e. doesn't change anything. That way you can't sent it for *Modify nodes, but it can be applicable for certain ForeignScans, such as those involving FunctionScan. In general, it is safer to enforce ANALYZE OFF in all cases.
Also you can't expose to main EXPLAIN some metrics obtained from remote side through the "remote" explain. For example, values such as actual time, planning time, execution time, and similar metrics cannot be exposed because they relates to events that occurred during the "EXPLAIN" communication, rather than during the actual planning and execution phases. Therefore, these times would likely mislead the user. I suppose it's better to enforce EXPLAIN with TIMING OFF and SUMMARY OFF when obtaining the remote portion of EXPLAIN.
While reconstructing (deparsing) the SQL query to send as part of EXPLAIN to the remote server, you can obtain SQL statements with placeholders (i.e. $1, $2, etc) instead of actual parameter values. It's syntactically incorrect SQL, which will lead to an error on the remote side. There are two ways to avoid this. You can use GENERIC_PLAN feature (v16+), which accepts dollar-parameters here. Another option is to use params_list == NULL in the deparseSelectStmtForRel() function to substitute dummy null values for placeholders, thereby generating syntactically correct SQL. The downside of this approach is the need to perform an additional deparse stage, which can be redundant.
However looking forward a patch, it is likely that some (or all) of my thoughts may become irrelevant.
--
Best regards,
Anton Shmigirilov,
Postgres Professional
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2024-12-14 12:49 dinesh salve <cooltodinesh@gmail.com>
parent: Anton Shmigirilov <a.shmigirilov@postgrespro.ru>
0 siblings, 0 replies; 31+ messages in thread
From: dinesh salve @ 2024-12-14 12:49 UTC (permalink / raw)
To: Anton Shmigirilov <a.shmigirilov@postgrespro.ru>; +Cc: pgsql-hackers; zhihuifan1213@163.com
On Mon, Nov 25, 2024 at 10:23 PM Anton Shmigirilov <
a.shmigirilov@postgrespro.ru> wrote:
>
> > Hi Hackers,
> >
> > I am working on a feature in postgres_fdw extension to show plans used
> by remote postgresql servers in the output of the EXPLAIN command.
> > I think this will help end users understand query execution plans used
> by remote servers. Sample output for table people where people_1 is local
> partition and people_2 is remote partition would look like -
> >
> > postgres:5432> explain select * from "test"."people";
> > QUERY PLAN
> > Append (cost=0.00..399.75 rows=2270 width=46)
> > → Seq Scan on "people.people_1" people_1 (cost=0.00..21.00 rows=1100
> width=46)
> > → Foreign Scan on "people.people_2" people_2 (cost=100.00..367.40
> rows=1170 width=46)
> > Remote Plan
> > Seq Scan on "people.people_2" (cost=0.00..21.00 rows=1100
> width=46)
> > (5 rows)
> >
> > I would like community inputs on below high level thoughts:
> >
> > 1. To enable this feature, either we can introduce a new option in
> EXPLAIN command e.g. (fetch_remote_plans true) or control this behaviour
> using a guc defined in postgres_fdw extension. I am more inclined
> towards guc as this feature is for extension postgres_fdw. Adding the
> EXPLAIN command option might force other FDW extensions to handle this.
> >
> > 2. For ANALYZE = false, the idea is that postgres_fdw would create a
> connection to a remote server, prepare SQL to send over connection and
> store received plans in ExplainState.
> >
> > 3. For ANALYZE = true, idea is that postgres_fdw would set a new guc
> over connection to remote server, remote server postgres_fdw would read
> this guc and send back used query plan as a NOTICE (similar to auto_explain
> extension does) with custom header which postgres_fdw extension
> understands. . We also have an opportunity to introduce a new message type
> in the protocol to send back explain plans but it might look like too much
> work for this feature. Open to ideas here.
> >
> > Dinesh Salve
> > SDE@AWS
>
> Hi Dinesh,
>
> Thank you for your proposal regarding explain for foreign servers.
>
> I have been working on a similar feature and there are several
> considerations to take into account.
>
> To enable this feature it is preferable to use GUC rather than the EXPLAIN
> option, as it simplifies regression testing. You can simply set it to off
> before most tests that involve plan checking, while leaving the rest
> unchanged. This leads to a reduction in the size of the differences.
>
> If it is necessary to provide only the execution plan of the foreign query
> (without actual timing metrics), you should send EXPLAIN with ANALYZE set
> to OFF, regardless of the initial ANALYZE state. This approach will prevent
> the re-execution of the remote query (the SQL part of the ForeignScan
> node), which could potentially lead to side effects. It's safe to send
> ANALYZE ON during remote EXPLAIN only if your remote SQL is idempotent,
> i.e. doesn't change anything. That way you can't sent it for *Modify nodes,
> but it can be applicable for certain ForeignScans, such as those involving
> FunctionScan. In general, it is safer to enforce ANALYZE OFF in all cases.
>
> Also you can't expose to main EXPLAIN some metrics obtained from remote
> side through the "remote" explain. For example, values such as actual time,
> planning time, execution time, and similar metrics cannot be exposed
> because they relates to events that occurred during the "EXPLAIN"
> communication, rather than during the actual planning and execution phases.
> Therefore, these times would likely mislead the user. I suppose it's better
> to enforce EXPLAIN with TIMING OFF and SUMMARY OFF when obtaining the
> remote portion of EXPLAIN.
>
> While reconstructing (deparsing) the SQL query to send as part of EXPLAIN
> to the remote server, you can obtain SQL statements with placeholders (i.e.
> $1, $2, etc) instead of actual parameter values. It's syntactically
> incorrect SQL, which will lead to an error on the remote side. There are
> two ways to avoid this. You can use GENERIC_PLAN feature (v16+), which
> accepts dollar-parameters here. Another option is to use params_list ==
> NULL in the deparseSelectStmtForRel() function to substitute dummy null
> values for placeholders, thereby generating syntactically correct SQL. The
> downside of this approach is the need to perform an additional deparse
> stage, which can be redundant.
>
> However looking forward a patch, it is likely that some (or all) of my
> thoughts may become irrelevant.
>
> --
> Best regards,
> Anton Shmigirilov,
> Postgres Professional
Hello Anton,
Yeah, using guc to enable this feature. I am using auto_explain style
design to get a query plan after foreign server executes it. I am
forwarding user EXPLAIN options to foreign as it is so as to ensure the
user gets expected output. I have prepared a patch which works for SELECT
commands and I am planning to work on other commands based on feedback
so that I invest in right direction. Appreciate if you could take a look
and share feedback. Attached the steps I used to test this as well. Looping
in Andy as he expressed interest in review :)
Dinesh Salve
SDE@AWS
Attachments:
test-foreign-explain-patch.txt (text/plain, 907B) download
CREATE EXTENSION postgres_fdw;
DO $d$
BEGIN
EXECUTE $$CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (dbname '$$||current_database()||$$',
port '$$||current_setting('port')||$$'
)$$;
END;
$d$;
CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw OPTIONS (port '5432', dbname 'postgres');
CREATE USER MAPPING FOR CURRENT_USER SERVER loopback;
CREATE TABLE format_fdw_parent (c1 int) PARTITION BY RANGE (c1);
CREATE TABLE local_fdw_0_10 PARTITION OF format_fdw_parent FOR VALUES FROM (0) TO (10);
CREATE TABLE foreign_fdw_10_20_remote (c1 int);
create foreign table foreign_fdw_10_20 partition of format_fdw_parent
FOR VALUES FROM (10) TO (20)
server loopback options (table_name 'foreign_fdw_10_20_remote');
explain select * from format_fdw_parent;
explain (analyze true, format json) select * from format_fdw_parent;
0001-enable-fetching-explain-plans-from-foreign-server.patch (application/octet-stream, 39.2K) download
From cd92b6eb9651956bbce30efb78aa2fc923379448 Mon Sep 17 00:00:00 2001
From: Dinesh Salve <salved@amazon.com>
Date: Sat, 14 Dec 2024 11:45:07 +0000
Subject: [PATCH] enable fetching explain plans from foreign server
---
contrib/postgres_fdw/Makefile | 3 +-
contrib/postgres_fdw/connection.c | 5 +
.../postgres_fdw/expected/postgres_fdw.out | 92 +++++
contrib/postgres_fdw/option.c | 4 +
contrib/postgres_fdw/postgres_fdw.c | 356 +++++++++++++++-
contrib/postgres_fdw/postgres_fdw.h | 3 +
.../postgres_fdw/postgres_fdw_auto_explain.c | 383 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 16 +
src/backend/commands/explain.c | 56 +--
src/include/commands/explain.h | 2 +
src/include/pg_config_ext.h | 8 +
src/include/stamp-ext-h | 1 +
12 files changed, 889 insertions(+), 40 deletions(-)
create mode 100644 contrib/postgres_fdw/postgres_fdw_auto_explain.c
create mode 100644 src/include/pg_config_ext.h
create mode 100644 src/include/stamp-ext-h
diff --git a/contrib/postgres_fdw/Makefile b/contrib/postgres_fdw/Makefile
index 88fdce40d6..a94d04c61e 100644
--- a/contrib/postgres_fdw/Makefile
+++ b/contrib/postgres_fdw/Makefile
@@ -7,7 +7,8 @@ OBJS = \
deparse.o \
option.o \
postgres_fdw.o \
- shippable.o
+ shippable.o \
+ postgres_fdw_auto_explain.o
PGFILEDESC = "postgres_fdw - foreign data wrapper for PostgreSQL"
PG_CPPFLAGS = -I$(libpq_srcdir)
diff --git a/contrib/postgres_fdw/connection.c b/contrib/postgres_fdw/connection.c
index 2326f391d3..5ac51380ae 100644
--- a/contrib/postgres_fdw/connection.c
+++ b/contrib/postgres_fdw/connection.c
@@ -704,6 +704,11 @@ configure_remote_session(PGconn *conn)
do_sql_command(conn, "SET extra_float_digits = 3");
else
do_sql_command(conn, "SET extra_float_digits = 2");
+
+ if (get_postgres_fdw_show_remote_explain_enabled())
+ {
+ do_sql_command(conn, "LOAD 'postgres_fdw'");
+ }
}
/*
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index bf322198a2..d139d2e8e0 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -442,6 +442,98 @@ SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
fixed |
(1 row)
+-- run same queries with postgres_fdw.show_remote_explain_plans set on
+SET postgres_fdw.show_remote_explain_plans = on;
+-- single table without alias
+EXPLAIN (COSTS OFF) SELECT * FROM ft1 ORDER BY c3, c1 OFFSET 100 LIMIT 10;
+ QUERY PLAN
+-----------------------------------
+ Foreign Scan on ft1
+ Remote Plan
+ Limit
+ -> Sort
+ Sort Key: c3, "C 1"
+ -> Seq Scan on "T 1"
+(6 rows)
+
+-- single table with alias - also test that tableoid sort is not pushed to remote side
+EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 ORDER BY t1.c3, t1.c1, t1.tableoid OFFSET 100 LIMIT 10;
+ QUERY PLAN
+-------------------------------------------------------------------------------------
+ Limit
+ Output: c1, c2, c3, c4, c5, c6, c7, c8, tableoid
+ -> Sort
+ Output: c1, c2, c3, c4, c5, c6, c7, c8, tableoid
+ Sort Key: t1.c3, t1.c1, t1.tableoid
+ -> Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8, tableoid
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1"
+ Remote Plan
+ Seq Scan on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+(11 rows)
+
+-- whole-row reference
+EXPLAIN (VERBOSE, COSTS OFF) SELECT t1 FROM ft1 t1 ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10;
+ QUERY PLAN
+--------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: t1.*, c3, c1
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" ORDER BY c3 ASC NULLS LAST, "C 1" ASC NULLS LAST LIMIT 10::bigint OFFSET 100::bigint
+ Remote Plan
+ Limit
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ -> Sort
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Sort Key: "T 1".c3, "T 1"."C 1"
+ -> Seq Scan on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+(11 rows)
+
+-- with WHERE clause
+EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101 AND t1.c6 = '1' AND t1.c7 >= '1';
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE ((c7 >= '1')) AND (("C 1" = 101)) AND ((c6 = '1'))
+ Remote Plan
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = 101)
+ Filter: (("T 1".c7 >= '1'::bpchar) AND (("T 1".c6)::text = '1'::text))
+(8 rows)
+
+-- with FOR UPDATE/SHARE
+EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = 101 FOR UPDATE;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8, t1.*
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101)) FOR UPDATE
+ Remote Plan
+ LockRows
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8, ctid
+ -> Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8, ctid
+ Index Cond: ("T 1"."C 1" = 101)
+(9 rows)
+
+EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = 102 FOR SHARE;
+ QUERY PLAN
+---------------------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8, t1.*
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 102)) FOR SHARE
+ Remote Plan
+ LockRows
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8, ctid
+ -> Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8, ctid
+ Index Cond: ("T 1"."C 1" = 102)
+(9 rows)
+
+SET postgres_fdw.show_remote_explain_plans = off;
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 232d85354b..f5762eeb6e 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -586,4 +586,8 @@ _PG_init(void)
NULL);
MarkGUCPrefixReserved("postgres_fdw");
+
+ /* Setup hooks and gucs. */
+ setup_postgres_fdw_gucs();
+ setup_postgres_fdw_hooks();
}
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index c0810fbd7c..7ebf65df6e 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -59,6 +59,9 @@ PG_MODULE_MAGIC;
/* If no remote estimates, assume a sort costs 20% extra */
#define DEFAULT_FDW_SORT_MULTIPLIER 1.2
+/* This is set implementation of post_parse_analyze_hook so that we know EXPLAIN command options. */
+extern ExplainState *pg_fdw_parsed_explain_state;
+
/*
* Indexes of FDW-private information stored in fdw_private lists.
*
@@ -170,6 +173,7 @@ typedef struct PgFdwScanState
MemoryContext temp_cxt; /* context for per-tuple temporary data */
int fetch_size; /* number of tuples per fetch */
+ StringInfo remote_explain_plan; /* EXPLAIN plan received from foreign server */
} PgFdwScanState;
/*
@@ -541,7 +545,14 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_o,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
-
+static void set_guc_boolean(PGconn *conn, char* guc, bool value);
+static void set_guc_string(PGconn *conn, char* guc, char* value);
+static void subscribe_postgres_fdw_notices(PGconn *conn, StringInfo explain_plans);
+static void postgres_fdw_explain_notice_processor(void *arg, const char *notice);
+bool static is_explain_query(const char *sql);
+static void enrich_foreign_plans(char *sql, ExplainState *es, UserMapping *inputUser);
+static UserMapping* get_remote_user(ForeignScanState *node);
+static void append_foreign_explain_plan(ExplainState *es, StringInfo explainPlan);
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -1516,20 +1527,7 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags)
fsstate = (PgFdwScanState *) palloc0(sizeof(PgFdwScanState));
node->fdw_state = fsstate;
- /*
- * Identify which user to do the remote access as. This should match what
- * ExecCheckPermissions() does.
- */
- userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId();
- if (fsplan->scan.scanrelid > 0)
- rtindex = fsplan->scan.scanrelid;
- else
- rtindex = bms_next_member(fsplan->fs_base_relids, -1);
- rte = exec_rt_fetch(rtindex, estate);
-
- /* Get info about foreign table. */
- table = GetForeignTable(rte->relid);
- user = GetUserMapping(userid, table->serverid);
+ user = get_remote_user(node);
/*
* Get connection to the foreign server. Connection manager will
@@ -1537,6 +1535,37 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags)
*/
fsstate->conn = GetConnection(user, false, &fsstate->conn_state);
+ /*
+ * If this is EXPLAIN command, set guc on remote connection to provide options to foreign server for plan generation.
+ */
+ if (is_explain_query(estate->es_sourceText) && get_postgres_fdw_show_remote_explain_enabled()) {
+ set_guc_boolean(fsstate->conn, "postgres_fdw.auto_explain_enabled", true);
+ set_guc_boolean(fsstate->conn, "postgres_fdw.analyze_enabled", pg_fdw_parsed_explain_state->analyze);
+
+ char *expected_explain_format;
+ switch (pg_fdw_parsed_explain_state->format)
+ {
+ case EXPLAIN_FORMAT_TEXT:
+ expected_explain_format = "text";
+ break;
+ case EXPLAIN_FORMAT_JSON:
+ expected_explain_format = "json";
+ break;
+ case EXPLAIN_FORMAT_YAML:
+ expected_explain_format = "yaml";
+ break;
+ case EXPLAIN_FORMAT_XML:
+ expected_explain_format = "xml";
+ break;
+ }
+ set_guc_string(fsstate->conn, "postgres_fdw.format_enabled", expected_explain_format);
+ set_guc_boolean(fsstate->conn, "postgres_fdw.settings_enabled", pg_fdw_parsed_explain_state->settings);
+ set_guc_boolean(fsstate->conn, "postgres_fdw.verbose_enabled", pg_fdw_parsed_explain_state->verbose);
+ set_guc_boolean(fsstate->conn, "postgres_fdw.buffers_enabled", pg_fdw_parsed_explain_state->buffers);
+ set_guc_boolean(fsstate->conn, "postgres_fdw.wal_enabled", pg_fdw_parsed_explain_state->wal);
+ set_guc_boolean(fsstate->conn, "postgres_fdw.timing_enabled", pg_fdw_parsed_explain_state->timing);
+ }
+
/* Assign a unique ID for my cursor */
fsstate->cursor_number = GetCursorNumber(fsstate->conn);
fsstate->cursor_exists = false;
@@ -1574,6 +1603,14 @@ postgresBeginForeignScan(ForeignScanState *node, int eflags)
fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc);
+ /*
+ * Subscribe to NOTICES received from foreign server.
+ */
+ if (get_postgres_fdw_show_remote_explain_enabled() && is_explain_query(estate->es_sourceText)) {
+ fsstate->remote_explain_plan = makeStringInfo();
+ subscribe_postgres_fdw_notices(fsstate->conn, fsstate->remote_explain_plan);
+ }
+
/*
* Prepare for processing of parameters used in remote query, if any.
*/
@@ -2822,6 +2859,114 @@ postgresEndDirectModify(ForeignScanState *node)
/* MemoryContext will be deleted automatically. */
}
+/*
+ * Append plan received from foreign server to ExplainState.
+ */
+static void
+append_foreign_explain_plan(ExplainState *es, StringInfo explainPlan)
+{
+ if (explainPlan->len)
+ {
+ /* Append "Remote Plan" header */
+ switch (es->format)
+ {
+ case EXPLAIN_FORMAT_TEXT:
+ appendStringInfoSpaces(es->str, es->indent * 2);
+ appendStringInfo(es->str, "Remote Plan\n");
+ break;
+ case EXPLAIN_FORMAT_JSON:
+ appendStringInfo(es->str, ",\n");
+ appendStringInfoSpaces(es->str, es->indent * 2);
+ appendStringInfo(es->str, "\"Remote Plan\": ");
+ break;
+ case EXPLAIN_FORMAT_XML:
+ appendStringInfoSpaces(es->str, es->indent * 2);
+ appendStringInfo(es->str, "<Remote-Plan>\n");
+ break;
+ case EXPLAIN_FORMAT_YAML:
+ appendStringInfo(es->str, "\n");
+ appendStringInfoSpaces(es->str, es->indent * 2);
+ appendStringInfo(es->str, "Remote-Plan:\n");
+ break;
+ }
+
+ /* Append fetched remote plan */
+ char *explainPlans = explainPlan->data;
+ if (explainPlans) {
+ // remove extra newlines at the end
+ char *last = explainPlans + explainPlan->len;
+ while (last > explainPlans && (*last == '\n' || *last == '\0'))
+ {
+ *last = '\0';
+ last--;
+ }
+ }
+
+ /* Fetch explain plan from { */
+ // why formatting changes are required
+ if (explainPlans && es->format == EXPLAIN_FORMAT_JSON)
+ {
+ // explainPlans = strchr(explainPlans, '{');
+ }
+ else if (es->format == EXPLAIN_FORMAT_YAML) {
+ explainPlans = strchr(explainPlans, 'P');
+ }
+ bool firstLine = true;
+ while (explainPlans && strlen(explainPlans) > 0)
+ {
+ // this is last line in JSON format
+ if (es->format == EXPLAIN_FORMAT_JSON && strcmp(explainPlans, "]") == 0) {
+ // appendStringInfoSpaces(es->str, es->indent * 2);
+ // appendStringInfoString(es->str,"}");
+ appendStringInfoSpaces(es->str, es->indent * 2);
+ appendStringInfoString(es->str,"]");
+ break;
+ }
+
+ /* add extra indent if not first line in json */
+ if (es->format == EXPLAIN_FORMAT_JSON && firstLine) {
+ firstLine = false;
+ }
+ else if (es->format == EXPLAIN_FORMAT_JSON) {
+ appendStringInfoSpaces(es->str, es->indent * 2);
+ }
+ else if (es->format == EXPLAIN_FORMAT_YAML) {
+ appendStringInfoSpaces(es->str, es->indent * 2 + 4);
+ }
+ else if (es->format == EXPLAIN_FORMAT_XML) {
+ appendStringInfoSpaces(es->str, es->indent * 2);
+ }
+ else {
+ appendStringInfoSpaces(es->str, es->indent * 2 + 2);
+ }
+
+ /* Temporarily replace earliest '\n' with '\0' to get current line */
+ char *curLine = strchr(explainPlans, '\n');
+ if (curLine)
+ *curLine = '\0';
+
+ if (curLine) /* if newline in curline, add '\n' at end */
+ appendStringInfo(es->str,"%s\n", explainPlans);
+ else
+ appendStringInfo(es->str,"%s", explainPlans);
+
+ /* Restore '\n' */
+ if (curLine)
+ *curLine = '\n';
+
+ explainPlans = curLine ? (curLine+1) : NULL;
+ }
+
+ /* Append remote plan footer */
+ switch (es->format)
+ {
+ case EXPLAIN_FORMAT_XML:
+ appendStringInfo(es->str, "</Remote-Plan>\n");
+ break;
+ }
+ }
+}
+
/*
* postgresExplainForeignScan
* Produce extra output for EXPLAIN of a ForeignScan on a foreign table
@@ -2831,6 +2976,7 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
List *fdw_private = plan->fdw_private;
+ EState *estate = node->ss.ps.state;
/*
* Identify foreign scans that are really joins or upper relations. The
@@ -2927,6 +3073,28 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
ExplainPropertyText("Remote SQL", sql, es);
}
+
+ if (get_postgres_fdw_show_remote_explain_enabled())
+ {
+ /* For analyze = false, we explicitly fetch query plans by executing EXPLAIN on remote shard. */
+ if (!es->analyze)
+ {
+ int rtindex;
+ char *sql;
+ sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
+ UserMapping *user = get_remote_user(node);
+ enrich_foreign_plans(sql, es, user);
+ }
+ else if (is_explain_query(node->ss.ps.state->es_sourceText)) {
+ PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
+ if (fsstate->remote_explain_plan->len > 0) {
+ append_foreign_explain_plan(es, fsstate->remote_explain_plan);
+ if (es->format == EXPLAIN_FORMAT_TEXT) {
+ appendStringInfo(es->str, "\n");
+ }
+ }
+ }
+ }
}
/*
@@ -3804,8 +3972,15 @@ static void
fetch_more_data(ForeignScanState *node)
{
PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
+ ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
+ EState *estate = node->ss.ps.state;
PGresult *volatile res = NULL;
MemoryContext oldcontext;
+ RangeTblEntry *rte;
+ Oid userid;
+ ForeignTable *table;
+ UserMapping *user;
+ int rtindex;
/*
* We'll store the tuples in the batch_cxt. First, flush the previous
@@ -7963,3 +8138,154 @@ get_batch_size_option(Relation rel)
return batch_size;
}
+
+/*
+ * Identify which user to do the remote access as. This should match what
+ * ExecCheckPermissions() does.
+ */
+static UserMapping*
+get_remote_user(ForeignScanState *node)
+{
+ ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
+ EState *estate = node->ss.ps.state;
+ Oid userid;
+ int rtindex;
+ RangeTblEntry *rte;
+ ForeignTable *table;
+
+ userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId();
+ if (fsplan->scan.scanrelid > 0)
+ rtindex = fsplan->scan.scanrelid;
+ else
+ rtindex = bms_next_member(fsplan->fs_base_relids, -1);
+ rte = exec_rt_fetch(rtindex, estate);
+
+ /* Get info about foreign table. */
+ table = GetForeignTable(rte->relid);
+ return GetUserMapping(userid, table->serverid);
+}
+
+/*
+ * Connect to remote shards and retreive the explain plans for the given sql.
+ */
+static void
+enrich_foreign_plans(char *sql, ExplainState *es, UserMapping *inputUser) {
+ PGresult *volatile res = NULL;
+ PGconn *conn;
+ StringInfoData sqlE, multiLineplans;
+
+ /* Prepare EXPLAIN command to be sent to foreign server. */
+ initStringInfo(&sqlE);
+ appendStringInfoString(&sqlE, "EXPLAIN (");
+ appendStringInfo(&sqlE, "ANALYZE %s", es->analyze? "true" : "false");
+ appendStringInfo(&sqlE, ", VERBOSE %s", es->verbose? "true" : "false");
+ appendStringInfo(&sqlE, ", COSTS %s", es->costs? "true" : "false");
+ appendStringInfo(&sqlE, ", SETTINGS %s", es->settings? "true" : "false");
+ appendStringInfo(&sqlE, ", BUFFERS %s", es->buffers? "true" : "false");
+
+ if (es->serialize == EXPLAIN_SERIALIZE_NONE) {
+ appendStringInfoString(&sqlE, ", SERIALIZE OFF");
+ }
+ else if (es->serialize == EXPLAIN_SERIALIZE_TEXT) {
+ appendStringInfoString(&sqlE, ", SERIALIZE TEXT");
+ }
+ else if (es->serialize == EXPLAIN_SERIALIZE_BINARY) {
+ appendStringInfoString(&sqlE, ", SERIALIZE BINARY");
+ }
+
+ appendStringInfo(&sqlE, ", WAL %s", es->wal? "true" : "false");
+ appendStringInfo(&sqlE, ", TIMING %s", es->timing? "true" : "false");
+ appendStringInfo(&sqlE, ", SUMMARY %s", es->summary? "true" : "false");
+ appendStringInfo(&sqlE, ", MEMORY %s", es->memory? "true" : "false");
+
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfoString(&sqlE, ", FORMAT TEXT");
+ }
+ else if (es->format == EXPLAIN_FORMAT_JSON)
+ {
+ appendStringInfoString(&sqlE, ", FORMAT JSON");
+ }
+ else if (es->format == EXPLAIN_FORMAT_XML)
+ {
+ appendStringInfoString(&sqlE, ", FORMAT XML");
+ }
+ else if (es->format == EXPLAIN_FORMAT_YAML)
+ {
+ appendStringInfoString(&sqlE, ", FORMAT YAML");
+ }
+ appendStringInfoString(&sqlE, ")");
+ appendStringInfoString(&sqlE, sql);
+
+ conn = GetConnection(inputUser, false, NULL);
+
+ PG_TRY();
+ {
+ // Run the query and collect the remote plan
+ res = pgfdw_exec_query(conn, sqlE.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(ERROR, res, conn, false, sql);
+ int numrows = PQntuples(res);
+
+ initStringInfo(&multiLineplans);
+ for (int i = 0; i < numrows; i++) {
+ appendStringInfoString(&multiLineplans, PQgetvalue(res, i, 0));
+ if (i != numrows - 1)
+ appendStringInfoString(&multiLineplans, "\n");
+ }
+ append_foreign_explain_plan(es, &multiLineplans);
+ }
+ PG_FINALLY();
+ {
+ if (res)
+ PQclear(res);
+ }
+ PG_END_TRY();
+
+ ReleaseConnection(conn);
+}
+
+static void set_guc_boolean(PGconn *conn, char* guc, bool value)
+{
+ int guc_sql_len = ((strlen("SET LOCAL = ") + strlen(guc)) * sizeof(char)) + sizeof(int);
+ char* guc_sql = palloc0(guc_sql_len + 1);
+ snprintf(guc_sql, guc_sql_len, "SET LOCAL %s = %d", guc, value);
+ do_sql_command(conn, guc_sql);
+}
+
+static void set_guc_string(PGconn *conn, char* guc, char* value)
+{
+ int guc_sql_len = ((strlen("SET LOCAL = ") + strlen(guc) + strlen(value)) * sizeof(char)) + sizeof(int);
+ char* guc_sql = palloc0(guc_sql_len + 1);
+ snprintf(guc_sql, guc_sql_len, "SET LOCAL %s = %s", guc, value);
+ do_sql_command(conn, guc_sql);
+}
+
+/*
+ * This is callback function for NOTICEs from remote shards for EXPLAIN ANALYZE queries.
+ */
+static void postgres_fdw_explain_notice_processor(void *arg, const char *notice) {
+ StringInfo explain_plans = (char **) arg;
+ // We might receive plans per batch of cursor, but we only need to store one.
+ // do we really need to handle len==0. report warn if we still recived. have test around this warn.
+ if (strstr(notice, "postgres_fdw_explain_plan") && explain_plans->len == 0) {
+ char *explain_plan_str = strchr(strchr(notice, ':') + 1, ':') + 1;
+ appendStringInfoString(explain_plans, explain_plan_str);
+ }
+}
+
+/*
+ * Remote shards sends the EXPLAIN PLANS as a NOTICE to the host shard when a guc is set for EXPLAIN ANALYZE queries.
+ * To listen to those NOTICEs, here we subscribe to NOTICEs on this connection and register callback so that
+ * callback function is called instead of defaultNoticeProcessor.
+ */
+static void subscribe_postgres_fdw_notices(PGconn *conn, StringInfo explain_plans) {
+ PQsetNoticeProcessor(conn, postgres_fdw_explain_notice_processor, explain_plans);
+}
+
+/*
+ * Return true if this is EXPLAIN query.
+ */
+bool static is_explain_query(const char *sql) {
+ return pg_strncasecmp("EXPLAIN", sql, 7) == 0;
+}
\ No newline at end of file
diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h
index 9e501660d1..7c105ade83 100644
--- a/contrib/postgres_fdw/postgres_fdw.h
+++ b/contrib/postgres_fdw/postgres_fdw.h
@@ -257,4 +257,7 @@ extern const char *get_jointype_name(JoinType jointype);
extern bool is_builtin(Oid objectId);
extern bool is_shippable(Oid objectId, Oid classId, PgFdwRelationInfo *fpinfo);
+extern void setup_postgres_fdw_hooks(void);
+extern void setup_postgres_fdw_gucs(void);
+
#endif /* POSTGRES_FDW_H */
diff --git a/contrib/postgres_fdw/postgres_fdw_auto_explain.c b/contrib/postgres_fdw/postgres_fdw_auto_explain.c
new file mode 100644
index 0000000000..699792e031
--- /dev/null
+++ b/contrib/postgres_fdw/postgres_fdw_auto_explain.c
@@ -0,0 +1,383 @@
+/*-------------------------------------------------------------------------
+ *
+ * postgres_fdw_auto_explain.c
+ *
+ *
+ * Copyright (c) 2008-2024, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * contrib/postgres_fdw/postgres_fdw_auto_explain.c
+ *
+ *-------------------------------------------------------------------------
+ */
+#include "postgres.h"
+
+#include <limits.h>
+
+#include "access/parallel.h"
+#include "commands/explain.h"
+#include "common/pg_prng.h"
+#include "executor/instrument.h"
+#include "utils/guc.h"
+#include "parser/analyze.h"
+
+/* GUC variables */
+static bool postgres_fdw_show_remote_explain_plans = false;
+static bool postgres_fdw_auto_explain_enabled = false;
+static bool postgres_fdw_analyze = false;
+static bool postgres_fdw_verbose = false;
+static bool postgres_fdw_buffers = false;
+static bool postgres_fdw_wal = false;
+static bool postgres_fdw_triggers = false;
+static bool postgres_fdw_timing = true;
+static bool postgres_fdw_settings = false;
+static int postgres_fdw_format = EXPLAIN_FORMAT_TEXT;
+
+
+static const struct config_enum_entry format_options[] = {
+ {"text", EXPLAIN_FORMAT_TEXT, false},
+ {"xml", EXPLAIN_FORMAT_XML, false},
+ {"json", EXPLAIN_FORMAT_JSON, false},
+ {"yaml", EXPLAIN_FORMAT_YAML, false},
+ {NULL, 0, false}
+};
+
+/* Current nesting depth of ExecutorRun calls */
+static int nesting_level = 0;
+
+#define auto_explain_enabled() \
+ (postgres_fdw_auto_explain_enabled && nesting_level == 1)
+
+
+/* Saved hook values in case of unload */
+static ExecutorStart_hook_type prev_ExecutorStart = NULL;
+static ExecutorRun_hook_type prev_ExecutorRun = NULL;
+static ExecutorFinish_hook_type prev_ExecutorFinish = NULL;
+static ExecutorEnd_hook_type prev_ExecutorEnd = NULL;
+static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
+
+ExplainState *pg_fdw_parsed_explain_state;
+static bool pg_fdw_load_initialized = false;
+
+static void explain_ExecutorStart(QueryDesc *queryDesc, int eflags);
+static void explain_ExecutorRun(QueryDesc *queryDesc,
+ ScanDirection direction,
+ uint64 count, bool execute_once);
+static void explain_ExecutorFinish(QueryDesc *queryDesc);
+static void explain_ExecutorEnd(QueryDesc *queryDesc);
+static void postgres_fdw_post_parse_analyze(ParseState *pstate, Query *query, JumbleState *jstate);
+bool get_postgres_fdw_show_remote_explain_enabled();
+
+void setup_postgres_fdw_hooks()
+{
+ prev_ExecutorStart = ExecutorStart_hook;
+ ExecutorStart_hook = explain_ExecutorStart;
+ prev_ExecutorRun = ExecutorRun_hook;
+ ExecutorRun_hook = explain_ExecutorRun;
+ prev_ExecutorFinish = ExecutorFinish_hook;
+ ExecutorFinish_hook = explain_ExecutorFinish;
+ prev_ExecutorEnd = ExecutorEnd_hook;
+ ExecutorEnd_hook = explain_ExecutorEnd;
+
+ prev_post_parse_analyze_hook = post_parse_analyze_hook;
+ post_parse_analyze_hook = postgres_fdw_post_parse_analyze;
+ pg_fdw_load_initialized = true;
+}
+
+void setup_postgres_fdw_gucs()
+{
+ DefineCustomBoolVariable("postgres_fdw.show_remote_explain_plans",
+ "If enabled, plan from foreign server is embeded in EXPLAIN command output",
+ NULL,
+ &postgres_fdw_show_remote_explain_plans,
+ false,
+ PGC_SIGHUP | PGC_USERSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ DefineCustomBoolVariable("postgres_fdw.auto_explain_enabled",
+ "If enabled, explain plan is sent as a NOTICE",
+ NULL,
+ &postgres_fdw_auto_explain_enabled,
+ false,
+ PGC_USERSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ DefineCustomBoolVariable("postgres_fdw.analyze_enabled",
+ "Use EXPLAIN ANALYZE for plan logging.",
+ NULL,
+ &postgres_fdw_analyze,
+ false,
+ PGC_USERSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ DefineCustomBoolVariable("postgres_fdw.settings_enabled",
+ "Log modified configuration parameters affecting query planning.",
+ NULL,
+ &postgres_fdw_settings,
+ false,
+ PGC_USERSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ DefineCustomBoolVariable("postgres_fdw.verbose_enabled",
+ "Use EXPLAIN VERBOSE for plan logging.",
+ NULL,
+ &postgres_fdw_verbose,
+ false,
+ PGC_SUSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ DefineCustomBoolVariable("postgres_fdw.buffers_enabled",
+ "Log buffers usage.",
+ NULL,
+ &postgres_fdw_buffers,
+ false,
+ PGC_SUSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ DefineCustomBoolVariable("postgres_fdw.wal_enabled",
+ "Log WAL usage.",
+ NULL,
+ &postgres_fdw_wal,
+ false,
+ PGC_SUSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ DefineCustomBoolVariable("postgres_fdw.triggers_enabled",
+ "Include trigger statistics in plans.",
+ "This has no effect unless analyze is also set.",
+ &postgres_fdw_triggers,
+ false,
+ PGC_SUSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ DefineCustomEnumVariable("postgres_fdw.format_enabled",
+ "EXPLAIN format to be used for plan logging.",
+ NULL,
+ &postgres_fdw_format,
+ EXPLAIN_FORMAT_TEXT,
+ format_options,
+ PGC_SUSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ DefineCustomBoolVariable("postgres_fdw.timing_enabled",
+ "Collect timing data, not just row counts.",
+ NULL,
+ &postgres_fdw_timing,
+ true,
+ PGC_SUSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+}
+
+static void
+postgres_fdw_post_parse_analyze(ParseState *pstate, Query *query, JumbleState *jstate)
+{
+ if (prev_post_parse_analyze_hook)
+ prev_post_parse_analyze_hook(pstate, query, jstate);
+
+ if (query->utilityStmt != NULL && IsA(query->utilityStmt, ExplainStmt)) {
+ pg_fdw_parsed_explain_state = NULL;
+ ExplainStmt *stmt = (ExplainStmt *) query->utilityStmt;
+ pg_fdw_parsed_explain_state = ParseExplainStmtOptions(pstate, stmt->options);
+ }
+}
+
+/*
+ * ExecutorStart hook: start up logging if needed
+ */
+static void
+explain_ExecutorStart(QueryDesc *queryDesc, int eflags)
+{
+ if (auto_explain_enabled())
+ {
+ /* Enable per-node instrumentation iff analyze is required. */
+ if (postgres_fdw_analyze && (eflags & EXEC_FLAG_EXPLAIN_ONLY) == 0)
+ {
+ if (postgres_fdw_timing)
+ queryDesc->instrument_options |= INSTRUMENT_TIMER;
+ else
+ queryDesc->instrument_options |= INSTRUMENT_ROWS;
+ if (postgres_fdw_buffers)
+ queryDesc->instrument_options |= INSTRUMENT_BUFFERS;
+ if (postgres_fdw_wal)
+ queryDesc->instrument_options |= INSTRUMENT_WAL;
+ }
+ }
+
+ if (prev_ExecutorStart)
+ prev_ExecutorStart(queryDesc, eflags);
+ else
+ standard_ExecutorStart(queryDesc, eflags);
+
+ if (auto_explain_enabled())
+ {
+ /*
+ * Set up to track total elapsed time in ExecutorRun. Make sure the
+ * space is allocated in the per-query context so it will go away at
+ * ExecutorEnd.
+ */
+ if (queryDesc->totaltime == NULL)
+ {
+ MemoryContext oldcxt;
+
+ oldcxt = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
+ queryDesc->totaltime = InstrAlloc(1, INSTRUMENT_ALL, false);
+ MemoryContextSwitchTo(oldcxt);
+ }
+ }
+}
+
+/*
+ * ExecutorRun hook: all we need do is track nesting depth
+ */
+static void
+explain_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction,
+ uint64 count, bool execute_once)
+{
+ nesting_level++;
+ PG_TRY();
+ {
+ if (prev_ExecutorRun)
+ prev_ExecutorRun(queryDesc, direction, count);
+ else
+ standard_ExecutorRun(queryDesc, direction, count);
+
+ if (auto_explain_enabled()) {
+ // send explain plans
+ ExplainState *es = NewExplainState();
+
+ es->analyze = (queryDesc->instrument_options && postgres_fdw_analyze);
+ es->verbose = postgres_fdw_verbose;
+ es->buffers = (es->analyze && postgres_fdw_buffers);
+ es->wal = (es->analyze && postgres_fdw_wal);
+ es->timing = (es->analyze && postgres_fdw_timing);
+ es->summary = es->analyze;
+ /* No support for MEMORY */
+ /* es->memory = false; */
+ es->format = postgres_fdw_format;
+ es->settings = postgres_fdw_settings;
+
+ ExplainBeginOutput(es);
+ ExplainQueryParameters(es, queryDesc->params, log_parameter_max_length);
+ ExplainPrintPlan(es, queryDesc);
+ if (es->analyze && postgres_fdw_triggers)
+ ExplainPrintTriggers(es, queryDesc);
+ if (es->costs)
+ ExplainPrintJITSummary(es, queryDesc);
+ ExplainEndOutput(es);
+
+ /* Remove last line break */
+ if (es->str->len > 0 && es->str->data[es->str->len - 1] == '\n')
+ es->str->data[--es->str->len] = '\0';
+
+ /* Fix JSON to output an object */
+ if (postgres_fdw_format == EXPLAIN_FORMAT_JSON)
+ {
+ es->str->data[0] = '{';
+ es->str->data[es->str->len - 1] = '}';
+ }
+
+ /*
+ * Note: we rely on the existing logging of context or
+ * debug_query_string to identify just which statement is being
+ * reported. This isn't ideal but trying to do it here would
+ * often result in duplication.
+ */
+ ereport(LOG,
+ (errmsg("postgres_fdw_auto_explain_enabled:%d", postgres_fdw_auto_explain_enabled),
+ errhidestmt(true)));
+ ereport(LOG,
+ (errmsg("sending explain plan to caller:%s", es->str->data),
+ errhidestmt(true)));
+ // receive token from source server and add that in response so that no other code can impact this.
+ ereport(NOTICE,
+ (errmsg("postgres_fdw_explain_plan:%s", es->str->data),
+ errhidestmt(true)));
+ }
+ }
+ PG_FINALLY();
+ {
+ nesting_level--;
+ }
+ PG_END_TRY();
+}
+
+/*
+ * ExecutorFinish hook: all we need do is track nesting depth
+ */
+static void
+explain_ExecutorFinish(QueryDesc *queryDesc)
+{
+ nesting_level++;
+ PG_TRY();
+ {
+ if (prev_ExecutorFinish)
+ prev_ExecutorFinish(queryDesc);
+ else
+ standard_ExecutorFinish(queryDesc);
+ }
+ PG_FINALLY();
+ {
+ nesting_level--;
+ }
+ PG_END_TRY();
+}
+
+/*
+ * ExecutorEnd hook: log results if needed
+ */
+static void
+explain_ExecutorEnd(QueryDesc *queryDesc)
+{
+ if (prev_ExecutorEnd)
+ prev_ExecutorEnd(queryDesc);
+ else
+ standard_ExecutorEnd(queryDesc);
+}
+
+bool get_postgres_fdw_show_remote_explain_enabled()
+{
+ if (postgres_fdw_show_remote_explain_plans) {
+ /*
+ * Check if extension is loaded and we have required hooks initialized. This happens when postgres_fdw wasn't
+ * already loaded and this is first SQL who need to access foreign server.
+ */
+ if (!pg_fdw_load_initialized) {
+ ereport(ERROR,
+ (errmsg("postgres_fdw.show_remote_explain_plans is set but extension postgres_fdw is not loaded yet."),
+ errhidestmt(true)));
+ return false;
+ }
+ return true;
+ }
+ return false;
+}
\ No newline at end of file
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 3900522ccb..caf4264f0d 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -285,6 +285,22 @@ SELECT * FROM ft1 t1 WHERE t1.c3 = (SELECT MAX(c3) FROM ft2 t2) ORDER BY c1;
WITH t1 AS (SELECT * FROM ft1 WHERE c1 <= 10) SELECT t2.c1, t2.c2, t2.c3, t2.c4 FROM t1, ft2 t2 WHERE t1.c1 = t2.c1 ORDER BY t1.c1;
-- fixed values
SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
+
+-- run same queries with postgres_fdw.show_remote_explain_plans set on
+SET postgres_fdw.show_remote_explain_plans = on;
+-- single table without alias
+EXPLAIN (COSTS OFF) SELECT * FROM ft1 ORDER BY c3, c1 OFFSET 100 LIMIT 10;
+-- single table with alias - also test that tableoid sort is not pushed to remote side
+EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 ORDER BY t1.c3, t1.c1, t1.tableoid OFFSET 100 LIMIT 10;
+-- whole-row reference
+EXPLAIN (VERBOSE, COSTS OFF) SELECT t1 FROM ft1 t1 ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10;
+-- with WHERE clause
+EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101 AND t1.c6 = '1' AND t1.c7 >= '1';
+-- with FOR UPDATE/SHARE
+EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = 101 FOR UPDATE;
+EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = 102 FOR SHARE;
+SET postgres_fdw.show_remote_explain_plans = off;
+
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
diff --git a/src/backend/commands/explain.c b/src/backend/commands/explain.c
index a201ed3082..d3b2386572 100644
--- a/src/backend/commands/explain.c
+++ b/src/backend/commands/explain.c
@@ -181,28 +181,20 @@ static void ExplainYAMLLineStarting(ExplainState *es);
static void escape_yaml(StringInfo buf, const char *str);
static SerializeMetrics GetSerializationMetrics(DestReceiver *dest);
-
-
-/*
- * ExplainQuery -
- * execute an EXPLAIN command
- */
-void
-ExplainQuery(ParseState *pstate, ExplainStmt *stmt,
- ParamListInfo params, DestReceiver *dest)
+ExplainState *
+ParseExplainStmtOptions(ParseState *pstate, List *options)
{
- ExplainState *es = NewExplainState();
- TupOutputState *tstate;
- JumbleState *jstate = NULL;
- Query *query;
- List *rewritten;
ListCell *lc;
bool timing_set = false;
bool buffers_set = false;
bool summary_set = false;
+ ExplainState *es = NewExplainState();
+
+ if (!options)
+ return es;
/* Parse options list. */
- foreach(lc, stmt->options)
+ foreach(lc, options)
{
DefElem *opt = (DefElem *) lfirst(lc);
@@ -287,18 +279,37 @@ ExplainQuery(ParseState *pstate, ExplainStmt *stmt,
parser_errposition(pstate, opt->location)));
}
+ /* if the timing was not set explicitly, set default value */
+ es->timing = (timing_set) ? es->timing : es->analyze;
+
+ /* if the summary was not set explicitly, set default value */
+ es->summary = (summary_set) ? es->summary : es->analyze;
+
+ return es;
+}
+
+/*
+ * ExplainQuery -
+ * execute an EXPLAIN command
+ */
+void
+ExplainQuery(ParseState *pstate, ExplainStmt *stmt,
+ ParamListInfo params, DestReceiver *dest)
+{
+ ExplainState *es;
+ TupOutputState *tstate;
+ JumbleState *jstate = NULL;
+ Query *query;
+ List *rewritten;
+
+ es = ParseExplainStmtOptions(pstate, stmt->options);
+
/* check that WAL is used with EXPLAIN ANALYZE */
if (es->wal && !es->analyze)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("EXPLAIN option %s requires ANALYZE", "WAL")));
- /* if the timing was not set explicitly, set default value */
- es->timing = (timing_set) ? es->timing : es->analyze;
-
- /* if the buffers was not set explicitly, set default value */
- es->buffers = (buffers_set) ? es->buffers : es->analyze;
-
/* check that timing is used with EXPLAIN ANALYZE */
if (es->timing && !es->analyze)
ereport(ERROR,
@@ -317,9 +328,6 @@ ExplainQuery(ParseState *pstate, ExplainStmt *stmt,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("EXPLAIN options ANALYZE and GENERIC_PLAN cannot be used together")));
- /* if the summary was not set explicitly, set default value */
- es->summary = (summary_set) ? es->summary : es->analyze;
-
query = castNode(Query, stmt->query);
if (IsQueryIdEnabled())
jstate = JumbleQuery(query);
diff --git a/src/include/commands/explain.h b/src/include/commands/explain.h
index aa5872bc15..d1faac97e8 100644
--- a/src/include/commands/explain.h
+++ b/src/include/commands/explain.h
@@ -144,4 +144,6 @@ extern void ExplainCloseGroup(const char *objtype, const char *labelname,
extern DestReceiver *CreateExplainSerializeDestReceiver(ExplainState *es);
+extern ExplainState *ParseExplainStmtOptions(ParseState *pstate, List *options);
+
#endif /* EXPLAIN_H */
diff --git a/src/include/pg_config_ext.h b/src/include/pg_config_ext.h
new file mode 100644
index 0000000000..b4c07dd857
--- /dev/null
+++ b/src/include/pg_config_ext.h
@@ -0,0 +1,8 @@
+/* src/include/pg_config_ext.h. Generated from pg_config_ext.h.in by configure. */
+/*
+ * src/include/pg_config_ext.h.in. This is generated manually, not by
+ * autoheader, since we want to limit which symbols get defined here.
+ */
+
+/* Define to the name of a signed 64-bit integer type. */
+#define PG_INT64_TYPE long int
diff --git a/src/include/stamp-ext-h b/src/include/stamp-ext-h
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/src/include/stamp-ext-h
@@ -0,0 +1 @@
+
--
2.40.1
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2025-02-26 19:13 Sami Imseih <samimseih@gmail.com>
parent: dinesh salve <cooltodinesh@gmail.com>
3 siblings, 1 reply; 31+ messages in thread
From: Sami Imseih @ 2025-02-26 19:13 UTC (permalink / raw)
To: dinesh salve <cooltodinesh@gmail.com>; +Cc: pgsql-hackers
Hi,
Thanks for working on this patch!
I looked at the patch from and I have several comments. There are
some others, but wanted to start with the most important I found, in order
of importance.
1/ The use of NOTICE to propagate the explain plan.
I see the message content is checked, but this does not look robust
and could lead to
some strange results if another ExecutorRun hook emits a similar notice message.
+ // We might receive plans per batch of cursor, but we only need
to store one.
+ // do we really need to handle len==0. report warn if we still
recived. have test around this warn.
+ if (strstr(notice, "postgres_fdw_explain_plan") &&
explain_plans->len == 0) {
2/ The current patch requires that the remote side has postgres_fdw
enabled. This seems very much
against the philosophy of FDWs. Only the side which creates the
foreign tables should require
the extension to be installed.
Also, if auto_explain_plan is enabled on the foreign table side, it
seems the explain_ExecutorRun
is exercised. This code path should only be taken on the remote side. right?
3/ ExecutorRun is the wrong place to send the plans from, because
postgres_fdw performs
FETCHES from a SQL declared cursor, and each fetch will hit
ExecutorRun. If you return the
first plan from ExecutorRun and stop consuming the rest of the plans,
you will only get the
results from a single fetch only. The plan should be generated and
sent back at CLOSE cursor time.
4/ As far as presenting the remote plans, I think adding them inline
in the EXPLAIN output
will make the plans hard to read, especially fas the plans become more complex.
What about they get added to a new section called "remote plans" and
the remote plans will
be identified by the plan_node_id, which we can add.
Below is a sketch-up to make it clear what I am thinking.
"""
Sort (cost=1..10 rows=10 width=120) (actual time=1..10 rows=10 loops=1)
-> Foreign Scan on prices (cost=100.00..200.00 rows=10width=59)
(actual time=1..100 rows=10 loops=1) (node=1)
Planning Time: 10 ms
Execution Time: 100 ms
Remote Plans
---------------
node 1:
Seq Scan on prices (cost=100.00..4576146.22 rows=467980 width=59)
(actual time=8737.505..2258486.086 rows=31752 loops=1)
"""
Here is a thought about how to generate and consume the plans.
What if we do something like a new EXPLAIN option which returns all the rows
back to the client, and then writes out the plan to some local memory. We would
then be able to fetch the last plan through a sql function, i.e.
SELECT pg_last_explain().
This may have applications beyond postgre_fdw; but in the case of
postgres_fdw, it will
call the remote sql using this EXPLAIN option and at the end of
execution, it will be
responsible to fetch the plans from pg_last_explain. I Have not fully
formulated this idea,
but wanted to share it.
Regards,
Sami Imseih
Amazon Web Services (AWS)
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2025-03-05 19:00 Jeff Davis <pgsql@j-davis.com>
parent: Sami Imseih <samimseih@gmail.com>
0 siblings, 1 reply; 31+ messages in thread
From: Jeff Davis @ 2025-03-05 19:00 UTC (permalink / raw)
To: Sami Imseih <samimseih@gmail.com>; dinesh salve <cooltodinesh@gmail.com>; +Cc: pgsql-hackers
On Wed, 2025-02-26 at 13:13 -0600, Sami Imseih wrote:
> 1/ The use of NOTICE to propagate the explain plan.
> I see the message content is checked, but this does not look robust
> and could lead to
> some strange results if another ExecutorRun hook emits a similar
> notice message.
Fundamentally, EXPLAIN ANALYZE needs to return two result sets for this
patch to work: the ordinary result, and the EXPLAIN ANALYZE result. The
current patch hacks around that by returning the ordinary result set
from the foreign server, and then returning the EXPLAIN ANALYZE result
as a NOTICE.
Ideally, we'd have EXPLAIN ANALYZE return two result sets, kind of like
how a query with a semicolon returns two result sets. That changes the
expected message flow for EXPLAIN ANALYZE, though, so we'd need a new
option so we are sure the client is expecting it (is this a sane
idea?). I wonder if Robert's extensible EXPLAIN work[1] could be useful
here? We'd also need a DestReceiver capable of returning two result
sets. These problems sound solvable, but would require some more
discussion.
> What if we do something like a new EXPLAIN option which returns all
> the rows
> back to the client, and then writes out the plan to some local
> memory.
That's another idea, but I am starting to think returning two result
sets from EXPLAIN ANALYZE would be generally useful.
Regards,
Jeff Davis
[1]
https://www.postgresql.org/message-id/CA%2BTgmoYSzg58hPuBmei46o8D3SKX%2BSZoO4K_aGQGwiRzvRApLg%40mail...
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2025-03-05 19:12 Tom Lane <tgl@sss.pgh.pa.us>
parent: Jeff Davis <pgsql@j-davis.com>
0 siblings, 2 replies; 31+ messages in thread
From: Tom Lane @ 2025-03-05 19:12 UTC (permalink / raw)
To: Jeff Davis <pgsql@j-davis.com>; +Cc: Sami Imseih <samimseih@gmail.com>; dinesh salve <cooltodinesh@gmail.com>; pgsql-hackers
Jeff Davis <pgsql@j-davis.com> writes:
> Ideally, we'd have EXPLAIN ANALYZE return two result sets, kind of like
> how a query with a semicolon returns two result sets. That changes the
> expected message flow for EXPLAIN ANALYZE, though, so we'd need a new
> option so we are sure the client is expecting it (is this a sane
> idea?).
I'm afraid not. That pretty fundamentally breaks the wire protocol,
I think. Also (1) there could be more than two, no, if the query
touches more than one foreign table? How would the client know
how many to expect? (2) there would be no particularly compelling
ordering for the multiple resultsets.
> I wonder if Robert's extensible EXPLAIN work[1] could be useful
> here?
I'm wondering the same. You could certainly imagine cramming
all of the foreign EXPLAIN output into some new field attached
to the ForeignScan node. Readability and indentation would
require some thought, but the other approaches don't have any
mechanism for addressing that at all.
regards, tom lane
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2025-03-05 19:26 Sami Imseih <samimseih@gmail.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
1 sibling, 0 replies; 31+ messages in thread
From: Sami Imseih @ 2025-03-05 19:26 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Jeff Davis <pgsql@j-davis.com>; dinesh salve <cooltodinesh@gmail.com>; pgsql-hackers
>> What if we do something like a new EXPLAIN option which returns all
>> the rows
>> back to the client, and then writes out the plan to some local
>> memory.
> That's another idea, but I am starting to think returning two result
> sets from EXPLAIN ANALYZE would be generally useful.
I did not think that would be doable. Because a
ForeignScanNode for postgres_fdw is a DECLARE CURSOR
followed by a serious of FETCH statements and finally a CLOSE,
I suspect we can store the plan in memory when the cursor is closed
and then it's up to the fdw to call a remote sql to fetch the plan to the
other side to append it on top of the explain output.
I also thought about 2 options 1/ new EXPLAIN option to do this -or-
2/ put in core GUCs to allow storing the last plan in memory at
ExecutorEnd.
>> I wonder if Robert's extensible EXPLAIN work[1] could be useful
>> here?
> I'm wondering the same. You could certainly imagine cramming
> all of the foreign EXPLAIN output into some new field attached
> to the ForeignScan node. Readability and indentation would
> require some thought, but the other approaches don't have any
> mechanism for addressing that at al
FWIW, I had the same thought [0] and planned on doing the investigation.
[0] https://www.postgresql.org/message-id/CAA5RZ0tLrNOw-OgPkv49kbNmZS4nFn9vzpN5HXX_xvOaM9%3D5ww%40mail.g...
--
Sami Imseih
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2025-03-05 23:24 Jeff Davis <pgsql@j-davis.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
1 sibling, 1 reply; 31+ messages in thread
From: Jeff Davis @ 2025-03-05 23:24 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Sami Imseih <samimseih@gmail.com>; dinesh salve <cooltodinesh@gmail.com>; pgsql-hackers
On Wed, 2025-03-05 at 14:12 -0500, Tom Lane wrote:
> I'm afraid not. That pretty fundamentally breaks the wire protocol,
> I think.
The extended protocol docs say: "The possible responses to Execute are
the same as those described above for queries issued via simple query
protocol, except that Execute doesn't cause ReadyForQuery or
RowDescription to be issued."
Each result set needs a RowDescription, so I think you're right that it
breaks the extended protocol. I missed that the first time.
Regards,
Jeff Davis
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2025-11-18 03:25 dinesh salve <cooltodinesh@gmail.com>
parent: Jeff Davis <pgsql@j-davis.com>
0 siblings, 1 reply; 31+ messages in thread
From: dinesh salve @ 2025-11-18 03:25 UTC (permalink / raw)
To: Sami Imseih <samimseih@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
Hi Sami,
Thanks for the feedback. I have refactored the commit on the latest version
of PG and added a few more tests. To simplify the roll out of this feature,
I decided to work on analyze=false use case first. Please find the attached
patch for the same.
Regards,
Dinesh
On Thu, Mar 6, 2025 at 4:54 AM Jeff Davis <pgsql@j-davis.com> wrote:
> On Wed, 2025-03-05 at 14:12 -0500, Tom Lane wrote:
> > I'm afraid not. That pretty fundamentally breaks the wire protocol,
> > I think.
>
> The extended protocol docs say: "The possible responses to Execute are
> the same as those described above for queries issued via simple query
> protocol, except that Execute doesn't cause ReadyForQuery or
> RowDescription to be issued."
>
> Each result set needs a RowDescription, so I think you're right that it
> breaks the extended protocol. I missed that the first time.
>
> Regards,
> Jeff Davis
>
>
--
Regards,
Dinesh Salve
Cell:- 91 8125898845
Attachments:
0001-This-change-adds-capability-to-fetch-explain-plans-f.patch (application/octet-stream, 59.1K) download
From b5908a7ac4ea6f40493cb0d5638d6a254a4fb768 Mon Sep 17 00:00:00 2001
From: Dinesh Salve <salved@amazon.com>
Date: Wed, 5 Nov 2025 05:49:11 +0000
Subject: [PATCH 1/1] This change adds capability to fetch explain plans for
foreign tables. We have introduced new option "remote_plans" to achieve the
same. This option does not work with ANALYZE option yet.
---
.../postgres_fdw/expected/postgres_fdw.out | 581 ++++++++++++++++++
contrib/postgres_fdw/option.c | 71 +++
contrib/postgres_fdw/postgres_fdw.c | 256 +++++++-
contrib/postgres_fdw/postgres_fdw.h | 26 +
contrib/postgres_fdw/sql/postgres_fdw.sql | 39 ++
5 files changed, 964 insertions(+), 9 deletions(-)
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index cd28126049d..5496a6ddea5 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -441,6 +441,173 @@ SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
fixed |
(1 row)
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ - Plan: +
+ Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "ft1" +
+ Schema: "public" +
+ Alias: "t1" +
+ Disabled: false +
+ Output: +
+ - "c1" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Remote SQL: "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))"+
+ Plan Node ID: 0 +
+ Remote Plans: +
+ Plan Node ID 0: +
+ - Plan: +
+ Node Type: "Index Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Schema: "S 1" +
+ Alias: "T 1" +
+ Disabled: false +
+ Output: +
+ - "\"C 1\"" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Index Cond: "(\"T 1\".\"C 1\" = 101)"
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>ft1</Relation-Name> +
+ <Schema>public</Schema> +
+ <Alias>t1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>c1</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Remote-SQL>SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))</Remote-SQL>+
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-0> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Schema>S 1</Schema> +
+ <Alias>T 1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>"C 1"</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Index-Cond>("T 1"."C 1" = 101)</Index-Cond> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-0> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "ft1", +
+ "Schema": "public", +
+ "Alias": "t1", +
+ "Disabled": false, +
+ "Output": ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Remote SQL": "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))",+
+ "Plan Node ID": 0 +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 0": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Schema": "S 1", +
+ "Alias": "T 1", +
+ "Disabled": false, +
+ "Output": ["\"C 1\"", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Index Cond": "(\"T 1\".\"C 1\" = 101)" +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = 101)
+(10 rows)
+
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -5086,6 +5253,373 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
Remote SQL: SELECT r5."C 1", r6.c1 FROM ("S 1"."T 1" r5 INNER JOIN "S 1"."T 3" r6 ON (((r5."C 1" = r6.c1)))) ORDER BY r5."C 1" ASC NULLS LAST
(13 rows)
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ERROR: EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ Limit
+ Plan Node ID: 0
+ -> Merge Semi Join
+ Merge Cond: (ft1.c1 = ft2_1.c1)
+ Plan Node ID: 1
+ -> Foreign Scan
+ Relations: (ft1) INNER JOIN (ft2)
+ Plan Node ID: 2
+ -> Foreign Scan
+ Relations: (ft2 ft2_1) INNER JOIN (ft4)
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Only Scan using t1_pkey on "T 1" r2
+ Plan Node ID 3:
+ Merge Join
+ Merge Cond: (r5."C 1" = r6.c1)
+ -> Index Only Scan using t1_pkey on "T 1" r5
+ -> Sort
+ Sort Key: r6.c1
+ -> Seq Scan on "T 3" r6
+(22 rows)
+
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Limit</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Semi</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>false</Inner-Unique> +
+ <Merge-Cond>(ft1.c1 = ft2_1.c1)</Merge-Cond> +
+ <Plan-Node-ID>1</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft1) INNER JOIN (ft2)</Relations> +
+ <Plan-Node-ID>2</Plan-Node-ID> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft2 ft2_1) INNER JOIN (ft4)</Relations> +
+ <Plan-Node-ID>3</Plan-Node-ID> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-2> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r2</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-2> +
+ <Plan-Node-ID-3> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Inner</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>true</Inner-Unique> +
+ <Merge-Cond>(r5."C 1" = r6.c1)</Merge-Cond> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r5</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Sort</Node-Type> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Sort-Key> +
+ <Item>r6.c1</Item> +
+ </Sort-Key> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Seq Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship>+
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>T 3</Relation-Name> +
+ <Alias>r6</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-3> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Limit", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Plan Node ID": 0, +
+ "Plans": [ +
+ { +
+ "Node Type": "Merge Join", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Semi", +
+ "Disabled": false, +
+ "Inner Unique": false, +
+ "Merge Cond": "(ft1.c1 = ft2_1.c1)", +
+ "Plan Node ID": 1, +
+ "Plans": [ +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft1) INNER JOIN (ft2)", +
+ "Plan Node ID": 2 +
+ }, +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft2 ft2_1) INNER JOIN (ft4)",+
+ "Plan Node ID": 3 +
+ } +
+ ] +
+ } +
+ ] +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 2": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Only Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r2", +
+ "Disabled": false +
+ } +
+ } +
+ ] +
+ ], +
+ "Plan Node ID 3": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Merge Join", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Inner", +
+ "Disabled": false, +
+ "Inner Unique": true, +
+ "Merge Cond": "(r5.\"C 1\" = r6.c1)", +
+ "Plans": [ +
+ { +
+ "Node Type": "Index Only Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r5", +
+ "Disabled": false +
+ }, +
+ { +
+ "Node Type": "Sort", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Sort Key": ["r6.c1"], +
+ "Plans": [ +
+ { +
+ "Node Type": "Seq Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "T 3", +
+ "Alias": "r6", +
+ "Disabled": false +
+ } +
+ ] +
+ } +
+ ] +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ - Plan: +
+ Node Type: "Limit" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Plan Node ID: 0 +
+ Plans: +
+ - Node Type: "Merge Join" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Semi" +
+ Disabled: false +
+ Inner Unique: false +
+ Merge Cond: "(ft1.c1 = ft2_1.c1)" +
+ Plan Node ID: 1 +
+ Plans: +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft1) INNER JOIN (ft2)" +
+ Plan Node ID: 2 +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft2 ft2_1) INNER JOIN (ft4)"+
+ Plan Node ID: 3 +
+ Remote Plans: +
+ Plan Node ID 2: +
+ - Plan: +
+ Node Type: "Index Only Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r2" +
+ Disabled: false +
+ Plan Node ID 3: +
+ - Plan: +
+ Node Type: "Merge Join" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Inner" +
+ Disabled: false +
+ Inner Unique: true +
+ Merge Cond: "(r5.\"C 1\" = r6.c1)" +
+ Plans: +
+ - Node Type: "Index Only Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r5" +
+ Disabled: false +
+ - Node Type: "Sort" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Sort Key: +
+ - "r6.c1" +
+ Plans: +
+ - Node Type: "Seq Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "T 3" +
+ Alias: "r6" +
+ Disabled: false
+(1 row)
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -6303,6 +6837,25 @@ DELETE FROM ft2 WHERE c1 = 1200 RETURNING tableoid::regclass;
ft2
(1 row)
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
+ QUERY PLAN
+---------------------------------------------------------------------------------------
+ Update on public.ft2
+ Plan Node ID: 0
+ -> Foreign Update on public.ft2
+ Remote SQL: UPDATE "S 1"."T 1" SET c2 = (c2 + 300) WHERE ((("C 1" % 10) = 3))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Update on "S 1"."T 1"
+ -> Seq Scan on "S 1"."T 1"
+ Output: (c2 + 300), ctid
+ Filter: (("T 1"."C 1" % 10) = 3)
+(12 rows)
+
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id;
@@ -12260,6 +12813,34 @@ SELECT * FROM insert_tbl ORDER BY a;
2505 | 505 | bar
(2 rows)
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+ QUERY PLAN
+-------------------------------------------------------------------------
+ Insert on public.insert_tbl
+ Remote SQL: INSERT INTO public.base_tbl4(a, b, c) VALUES ($1, $2, $3)
+ Batch Size: 1
+ Plan Node ID: 0
+ -> Append
+ Plan Node ID: 1
+ -> Seq Scan on public.local_tbl
+ Output: local_tbl.a, local_tbl.b, local_tbl.c
+ Plan Node ID: 2
+ -> Async Foreign Scan on public.remote_tbl
+ Output: remote_tbl.a, remote_tbl.b, remote_tbl.c
+ Remote SQL: SELECT a, b, c FROM public.base_tbl3
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Insert on public.base_tbl4
+ -> Result
+ Output: $1, $2, $3
+ Plan Node ID 3:
+ Seq Scan on public.base_tbl3
+ Output: a, b, c
+(22 rows)
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 04788b7e8b3..a3b87d2bbaf 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -17,6 +17,8 @@
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#include "commands/defrem.h"
+#include "commands/explain.h"
+#include "commands/explain_state.h"
#include "commands/extension.h"
#include "libpq/libpq-be.h"
#include "postgres_fdw.h"
@@ -40,6 +42,13 @@ typedef struct PgFdwOption
*/
static PgFdwOption *postgres_fdw_options;
+/*
+ * EXPLAIN hooks
+ */
+static explain_per_node_hook_type prev_explain_per_node_hook;
+static explain_per_plan_hook_type prev_explain_per_plan_hook;
+static explain_validate_options_hook_type prev_explain_validate_options_hook;
+
/*
* GUC parameters
*/
@@ -561,6 +570,57 @@ process_pgfdw_appname(const char *appname)
return buf.data;
}
+/*
+ * Get the PgFdwExplainState structure from an ExplainState; if there is
+ * none, create one, attach it to the ExplainState, and return it.
+ */
+static PgFdwExplainState *
+pgfdw_ensure_options(ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"));
+
+ if (pgfdw_explain_state == NULL)
+ {
+ pgfdw_explain_state = palloc0(sizeof(PgFdwExplainState));
+ SetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"), pgfdw_explain_state);
+ pgfdw_explain_state->all_remote_plans = NIL;
+ }
+
+ return pgfdw_explain_state;
+}
+
+/*
+ * Parse handler for EXPLAIN (REMOTE_PLANS).
+ */
+static void
+pgfdw_remote_plans_apply(ExplainState *es, DefElem *opt, ParseState *pstate)
+{
+ PgFdwExplainState *options = pgfdw_ensure_options(es);
+
+ options->remote_plans = defGetBoolean(opt);
+}
+
+static void
+postgresExplainValidateOptions(ExplainState *es, List *options, ParseState *pstate)
+{
+ ListCell *lc;
+
+ foreach(lc, options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0)
+ {
+ if (defGetBoolean(opt) && es->analyze)
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together"));
+ }
+ }
+}
+
/*
* Module load callback
*/
@@ -587,4 +647,15 @@ _PG_init(void)
NULL);
MarkGUCPrefixReserved("postgres_fdw");
+
+ RegisterExtensionExplainOption("remote_plans", pgfdw_remote_plans_apply);
+
+ /* per node EXPLAIN hook */
+ prev_explain_per_node_hook = explain_per_node_hook;
+ explain_per_node_hook = postgresExplainPerNode;
+ prev_explain_per_plan_hook = explain_per_plan_hook;
+ explain_per_plan_hook = postgresExplainPerPlan;
+ prev_explain_validate_options_hook = explain_validate_options_hook;
+ explain_validate_options_hook = postgresExplainValidateOptions;
+
}
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 06b52c65300..9b99a2386b3 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -43,6 +43,7 @@
#include "utils/builtins.h"
#include "utils/float.h"
#include "utils/guc.h"
+#include "utils/json.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
@@ -133,6 +134,20 @@ enum FdwDirectModifyPrivateIndex
FdwDirectModifyPrivateSetProcessed,
};
+static const char *const explain_formats[] = {
+ [EXPLAIN_FORMAT_TEXT] = "TEXT",
+ [EXPLAIN_FORMAT_JSON] = "JSON",
+ [EXPLAIN_FORMAT_XML] = "XML",
+ [EXPLAIN_FORMAT_YAML] = "YAML",
+};
+
+/*
+ * Track the extension id in the backend.
+ */
+static int extension_id = -1;
+#define GET_EXTENSION_ID() ((extension_id == -1) ? \
+ GetExplainExtensionId("postgres_fdw"): extension_id)
+
/*
* Execution state of a foreign scan using postgres_fdw.
*/
@@ -2822,6 +2837,65 @@ postgresEndDirectModify(ForeignScanState *node)
/* MemoryContext will be deleted automatically. */
}
+static void
+postgresExplainStatement(int plan_node_id,
+ ExplainState *es,
+ PgFdwExplainState * pgfdw_explain_state,
+ PGconn *conn,
+ char *sql)
+{
+ PGresult *volatile res = NULL;
+ StringInfoData explain_sql;
+
+ PG_TRY();
+ {
+ int numrows,
+ i;
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) palloc(sizeof(PgFdwExplainRemotePlans));
+
+ initStringInfo(&explain_sql);
+ initStringInfo(&explain->explain_plan);
+
+ appendStringInfo(&explain_sql, "EXPLAIN (\
+ GENERIC_PLAN 1, \
+ FORMAT %s, \
+ VERBOSE %d, \
+ COSTS %d, \
+ SETTINGS %d) \
+ %s",
+ explain_formats[es->format],
+ (es->verbose) ? 1 : 0,
+ (es->costs) ? 1 : 0,
+ (es->settings) ? 1 : 0,
+ sql);
+
+ /* Run the query and collect the remote plan */
+ res = pgfdw_exec_query(conn, explain_sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, explain_sql.data);
+
+ numrows = PQntuples(res);
+
+ for (i = 0; i < numrows; i++)
+ appendStringInfo(&explain->explain_plan, "%s\n", pstrdup(PQgetvalue(res, i, 0)));
+
+ if (explain->explain_plan.len > 0 && explain->explain_plan.data[explain->explain_plan.len - 1] == '\n')
+ explain->explain_plan.data[--explain->explain_plan.len] = '\0';
+
+ explain->plan_node_id = plan_node_id;
+ pgfdw_explain_state->all_remote_plans = lappend(pgfdw_explain_state->all_remote_plans, explain);
+ }
+ PG_FINALLY();
+ {
+ if (res)
+ PQclear(res);
+
+ if (explain_sql.data)
+ pfree(explain_sql.data);
+ }
+ PG_END_TRY();
+}
+
/*
* postgresExplainForeignScan
* Produce extra output for EXPLAIN of a ForeignScan on a foreign table
@@ -2831,6 +2905,9 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
List *fdw_private = plan->fdw_private;
+ PgFdwExplainState *pgfdw_explain_state;
+ char *sql;
+ List *foreign_scan_table = NIL;
/*
* Identify foreign scans that are really joins or upper relations. The
@@ -2892,6 +2969,14 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
Assert(rte->rtekind == RTE_RELATION);
/* This logic should agree with explain.c's ExplainTargetRel */
relname = get_rel_name(rte->relid);
+
+ /*
+ * add one of the tables to foreign_scan_table to get the
+ * serverId for remote plans
+ */
+ if (list_length(foreign_scan_table) == 0)
+ foreign_scan_table = lappend_oid(foreign_scan_table, rte->relid);
+
if (es->verbose)
{
char *namespace;
@@ -2917,15 +3002,38 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
ExplainPropertyText("Relations", relations.data, es);
}
+ sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
+
/*
* Add remote query, when VERBOSE option is specified.
*/
if (es->verbose)
+ ExplainPropertyText("Remote SQL", sql, es);
+
+ pgfdw_explain_state = GetExplainExtensionState(es, GET_EXTENSION_ID());
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
{
- char *sql;
+ UserMapping *user = NULL;
+ PGconn *conn = NULL;
+ ForeignTable *table;
- sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
- ExplainPropertyText("Remote SQL", sql, es);
+ if (node && !node->ss.ss_currentRelation &&
+ foreign_scan_table == NIL)
+ return;
+
+ if (node && node->ss.ss_currentRelation)
+ table = GetForeignTable(RelationGetRelid(node->ss.ss_currentRelation));
+ else
+ table = GetForeignTable(list_nth_oid(foreign_scan_table, 0));
+
+ Assert(table);
+
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+
+ postgresExplainStatement(node->ss.ps.plan->plan_node_id, es, pgfdw_explain_state, conn, sql);
+ ReleaseConnection(conn);
}
}
@@ -2940,11 +3048,12 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
int subplan_index,
ExplainState *es)
{
+ char *sql = strVal(list_nth(fdw_private,
+ FdwModifyPrivateUpdateSql));
+ PgFdwExplainState *pgfdw_explain_state;
+
if (es->verbose)
{
- char *sql = strVal(list_nth(fdw_private,
- FdwModifyPrivateUpdateSql));
-
ExplainPropertyText("Remote SQL", sql, es);
/*
@@ -2954,6 +3063,24 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
if (rinfo->ri_BatchSize > 0)
ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
}
+
+ pgfdw_explain_state = GetExplainExtensionState(es, GET_EXTENSION_ID());
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ {
+ UserMapping *user = NULL;
+ PGconn *conn = NULL;
+ ForeignTable *table;
+
+ table = GetForeignTable(rinfo->ri_RelationDesc->rd_rel->oid);
+
+ Assert(table);
+
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+
+ postgresExplainStatement(mtstate->ps.plan->plan_node_id, es, pgfdw_explain_state, conn, sql);
+ ReleaseConnection(conn);
+ }
}
/*
@@ -2966,12 +3093,31 @@ postgresExplainDirectModify(ForeignScanState *node, ExplainState *es)
{
List *fdw_private;
char *sql;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
+ sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
if (es->verbose)
- {
- fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
- sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
ExplainPropertyText("Remote SQL", sql, es);
+
+ pgfdw_explain_state = GetExplainExtensionState(es, GET_EXTENSION_ID());
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ {
+ UserMapping *user = NULL;
+ PGconn *conn = NULL;
+ ForeignTable *table;
+
+ table = GetForeignTable(RelationGetRelid(node->ss.ss_currentRelation));
+
+ Assert(table);
+
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+
+ postgresExplainStatement(node->ss.ps.plan->plan_node_id, es, pgfdw_explain_state, conn, sql);
+ ReleaseConnection(conn);
}
}
@@ -7886,3 +8032,95 @@ get_batch_size_option(Relation rel)
return batch_size;
}
+
+void
+postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship, const char *plan_name,
+ ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, GET_EXTENSION_ID());
+
+ if (pgfdw_explain_state == NULL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ ExplainPropertyInteger("Plan Node ID", NULL, planstate->plan->plan_node_id, es);
+}
+
+static void
+pgfdwFormatRemotePlan(PgFdwExplainRemotePlans * explain,
+ ExplainState *es,
+ int plan_node_id)
+{
+ char *token;
+ StringInfoData remote_plan_name;
+
+ initStringInfo(&remote_plan_name);
+ appendStringInfo(&remote_plan_name, "Plan Node ID %d", plan_node_id);
+
+ ExplainOpenGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Plan Node ID %d:", plan_node_id);
+ appendStringInfoString(es->str, "\n");
+ }
+
+ while ((token = strsep(&explain->explain_plan.data, "\n")) != NULL)
+ {
+ if (es->format == EXPLAIN_FORMAT_JSON ||
+ es->format == EXPLAIN_FORMAT_YAML)
+ appendStringInfoString(es->str, "\n");
+
+ appendStringInfoSpaces(es->str, (es->indent == 0) ? 2 : es->indent * 2);
+ appendStringInfoString(es->str, token);
+
+ if (es->format == EXPLAIN_FORMAT_XML ||
+ es->format == EXPLAIN_FORMAT_TEXT)
+ appendStringInfoString(es->str, "\n");
+ }
+
+ ExplainCloseGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+ pfree(remote_plan_name.data);
+}
+
+void
+postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, GET_EXTENSION_ID());
+
+ if (pgfdw_explain_state == NULL ||
+ pgfdw_explain_state->all_remote_plans == NIL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ ExplainOpenGroup("Remote Plans", "Remote Plans", true, es);
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Remote Plans:\n");
+ appendStringInfo(es->str, "-------------\n");
+ }
+
+ /* Process every remote plan captured */
+ foreach(lc, pgfdw_explain_state->all_remote_plans)
+ {
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) lfirst(lc);
+
+ pgfdwFormatRemotePlan(explain,
+ es,
+ explain->plan_node_id);
+ }
+
+ ExplainCloseGroup("Remote Plans", "Remote Plans", true, es);
+}
diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h
index e69735298d7..b135664b933 100644
--- a/contrib/postgres_fdw/postgres_fdw.h
+++ b/contrib/postgres_fdw/postgres_fdw.h
@@ -13,6 +13,7 @@
#ifndef POSTGRES_FDW_H
#define POSTGRES_FDW_H
+#include "commands/explain_state.h"
#include "foreign/foreign.h"
#include "lib/stringinfo.h"
#include "libpq/libpq-be-fe.h"
@@ -151,6 +152,21 @@ typedef enum PgFdwSamplingMethod
ANALYZE_SAMPLE_BERNOULLI, /* TABLESAMPLE bernoulli */
} PgFdwSamplingMethod;
+typedef struct PgFdwExplainRemotePlans
+{
+ int plan_node_id;
+ StringInfoData explain_plan;
+
+} PgFdwExplainRemotePlans;
+
+typedef struct PgFdwExplainState
+{
+ List *all_remote_plans;
+
+ /* EXPLAIN options */
+ bool remote_plans;
+} PgFdwExplainState;
+
/* in postgres_fdw.c */
extern int set_transmission_modes(void);
extern void reset_transmission_modes(int nestlevel);
@@ -178,6 +194,16 @@ extern int ExtractConnectionOptions(List *defelems,
extern List *ExtractExtensionList(const char *extensionsString,
bool warnOnMissing);
extern char *process_pgfdw_appname(const char *appname);
+extern void postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship,
+ const char *plan_name,
+ ExplainState *es);
+extern void postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv);
extern char *pgfdw_application_name;
/* in deparse.c */
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 9a8f9e28135..25823a7ebe7 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -281,6 +281,11 @@ SELECT * FROM ft1 t1 WHERE t1.c3 = (SELECT MAX(c3) FROM ft2 t2) ORDER BY c1;
WITH t1 AS (SELECT * FROM ft1 WHERE c1 <= 10) SELECT t2.c1, t2.c2, t2.c3, t2.c4 FROM t1, ft2 t2 WHERE t1.c1 = t2.c1 ORDER BY t1.c1;
-- fixed values
SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -1489,6 +1494,33 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
ORDER BY ft1.c1 LIMIT 5;
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -1538,6 +1570,10 @@ EXPLAIN (verbose, costs off)
DELETE FROM ft2 WHERE c1 = 1200 RETURNING tableoid::regclass; -- can be pushed down
DELETE FROM ft2 WHERE c1 = 1200 RETURNING tableoid::regclass;
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
+
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id;
@@ -4138,6 +4174,9 @@ INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_t
SELECT * FROM insert_tbl ORDER BY a;
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
--
2.43.0
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2025-12-03 22:40 Sami Imseih <samimseih@gmail.com>
parent: dinesh salve <cooltodinesh@gmail.com>
0 siblings, 1 reply; 31+ messages in thread
From: Sami Imseih @ 2025-12-03 22:40 UTC (permalink / raw)
To: dinesh salve <cooltodinesh@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
> I have refactored the commit on the latest version of PG and added a few more tests.
Thanks for the update!
> To simplify the roll out of this feature, I decided to work on analyze=false use case first.
I did not go through the entire patch yet, but a few things stood out
from my first pass.
1/
RegisterExtensionExplainOption is called during _PG_init, which is fine, but I
also wonder if we can call this during postgresExplainForeignScan as well?
The reason being is for _PG_init to be invoked, the user must load postgres_fdw
(LOAD, session_preload_libraries, shared_preload_libraries), which from my
experience is not very common in postgres_fdw. Users ordinarily just
"CREATE EXTENSION..."
So this needs to be documented [0]
2/
Does this behave sanely with multiple fdw connections? Can we add
tests for this?
+
+ /*
+ * add one of the tables to
foreign_scan_table to get the
+ * serverId for remote plans
+ */
+ if (list_length(foreign_scan_table) == 0)
+ foreign_scan_table =
lappend_oid(foreign_scan_table, rte->relid);
+
[0] https://www.postgresql.org/docs/current/postgres-fdw.html
--
Sami Imseih
Amazon Web Services (AWS)
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2025-12-04 00:34 Sami Imseih <samimseih@gmail.com>
parent: Sami Imseih <samimseih@gmail.com>
0 siblings, 1 reply; 31+ messages in thread
From: Sami Imseih @ 2025-12-04 00:34 UTC (permalink / raw)
To: dinesh salve <cooltodinesh@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
I forgot to mention this point earlier.
I noticed GENERIC_PLAN is hard-coded to 1 (true).
Is that an oversight, or is it required?
```
+ GENERIC_PLAN 1, \
```
--
Sami Imseih
Amazon Web Services (AWS)
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2025-12-09 21:08 Sami Imseih <samimseih@gmail.com>
parent: Sami Imseih <samimseih@gmail.com>
0 siblings, 1 reply; 31+ messages in thread
From: Sami Imseih @ 2025-12-09 21:08 UTC (permalink / raw)
To: dinesh salve <cooltodinesh@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
Hi,
I spent more time reviewing this patch. Here are additional comments.
1/ Remove unnecessary includes
#include "commands/explain_state.h" from option.c.
#include "utils/json.h" from postgres_fdw.c.
2/ Add new EXPLAIN options
MEMORY and SUMMARY flags added to the remote EXPLAIN query formatting.
These do not require ANALYZE to be used.
A larger question is how would we want to ensure that new core EXPLAIN
options can be automatically set?
This is not quite common, but perhaps it is a good thing to add a comment
near ExplainState explaining that if a new option is added, make sure
that postgre_fdw remote_plans are updated.
```
typedef struct ExplainState
{
StringInfo str; /* output buffer */
/* options */
bool verbose; /* be verbose */
bool analyze; /* print actual times */
bool costs; /* print estimated co
```
3/ Removed unnecessary pstrdup() when appending remote plan rows to
explain_plan.
Removed unnecessary pstrdup() when appending remote plan rows to explain_plan.
```
+ appendStringInfo(&explain->explain_plan,
"%s\n", pstrdup(PQgetvalue(res, i, 0)));
```
4/ Simplify foreign table OID handling in postgresExplainForeignScan
I am not sure why we need a list that can only hold a single value.
Can we just use an Oid variable to store this?
5/ Encapsulates getting the connection, executing the remote EXPLAIN,
and releasing the connection.
Replaces repeated code in postgresExplainForeignScan,
postgresExplainForeignModify, and postgresExplainDirectModify.
For #4 and #5, attached is my attempt to simplify these routines. What
do you think?
6/ Updated typedefs.list
... to include PgFdwExplainRemotePlans and PgFdwExplainState.
7/ Tests
I quickly skimmed the tests, but I did not see a join push-down test.
We should add
that.
--
Sami Imseih
Amazon Web Services (AWS)
Attachments:
simplify_explain_routines.txt (text/plain, 6.1K) download
/*
* explain_remote_query
* Helper function to get connection and execute remote EXPLAIN
*/
static void
explain_remote_query(int plan_node_id, ExplainState *es,
PgFdwExplainState *pgfdw_explain_state,
Oid foreign_table_oid, char *sql)
{
UserMapping *user;
PGconn *conn;
ForeignTable *table;
table = GetForeignTable(foreign_table_oid);
user = GetUserMapping(GetUserId(), table->serverid);
conn = GetConnection(user, false, NULL);
postgresExplainStatement(plan_node_id, es, pgfdw_explain_state, conn, sql);
ReleaseConnection(conn);
}
/*
* postgresExplainForeignScan
* Produce extra output for EXPLAIN of a ForeignScan on a foreign table
*/
static void
postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
List *fdw_private = plan->fdw_private;
PgFdwExplainState *pgfdw_explain_state;
char *sql;
Oid foreign_table_oid = InvalidOid;
if (node->ss.ss_currentRelation)
foreign_table_oid = RelationGetRelid(node->ss.ss_currentRelation);
/*
* Identify foreign scans that are really joins or upper relations. The
* input looks something like "(1) LEFT JOIN (2)", and we must replace the
* digit string(s), which are RT indexes, with the correct relation names.
* 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)
{
StringInfoData relations;
char *rawrelations;
char *ptr;
int minrti,
rtoffset;
rawrelations = strVal(list_nth(fdw_private, FdwScanPrivateRelations));
/*
* A difficulty with using a string representation of RT indexes is
* that setrefs.c won't update the string when flattening the
* rangetable. To find out what rtoffset was applied, identify the
* minimum RT index appearing in the string and compare it to the
* minimum member of plan->fs_base_relids. (We expect all the relids
* in the join will have been offset by the same amount; the Asserts
* below should catch it if that ever changes.)
*/
minrti = INT_MAX;
ptr = rawrelations;
while (*ptr)
{
if (isdigit((unsigned char) *ptr))
{
int rti = strtol(ptr, &ptr, 10);
if (rti < minrti)
minrti = rti;
}
else
ptr++;
}
rtoffset = bms_next_member(plan->fs_base_relids, -1) - minrti;
/* Now we can translate the string */
initStringInfo(&relations);
ptr = rawrelations;
while (*ptr)
{
if (isdigit((unsigned char) *ptr))
{
int rti = strtol(ptr, &ptr, 10);
RangeTblEntry *rte;
char *relname;
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);
/*
* Save first table OID for getting server connection
*/
if (!OidIsValid(foreign_table_oid))
foreign_table_oid = 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)
appendStringInfo(&relations, " %s",
quote_identifier(refname));
}
else
appendStringInfoChar(&relations, *ptr++);
}
ExplainPropertyText("Relations", relations.data, es);
}
sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
/*
* Add remote query, when VERBOSE option is specified.
*/
if (es->verbose)
ExplainPropertyText("Remote SQL", sql, es);
pgfdw_explain_state = GetExplainExtensionState(es, GET_EXTENSION_ID());
/* If we don't have a foreign table oid by now, something went wrong */
Assert(foreign_table_oid);
if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
explain_remote_query(node->ss.ps.plan->plan_node_id,
es,
pgfdw_explain_state,
foreign_table_oid,
sql);
}
/*
* postgresExplainForeignModify
* Produce extra output for EXPLAIN of a ModifyTable on a foreign table
*/
static void
postgresExplainForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
ExplainState *es)
{
char *sql = strVal(list_nth(fdw_private,
FdwModifyPrivateUpdateSql));
PgFdwExplainState *pgfdw_explain_state;
if (es->verbose)
{
ExplainPropertyText("Remote SQL", sql, es);
/*
* For INSERT we should always have batch size >= 1, but UPDATE and
* DELETE don't support batching so don't show the property.
*/
if (rinfo->ri_BatchSize > 0)
ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
}
pgfdw_explain_state = GetExplainExtensionState(es, GET_EXTENSION_ID());
if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
explain_remote_query(mtstate->ps.plan->plan_node_id,
es,
pgfdw_explain_state,
rinfo->ri_RelationDesc->rd_rel->oid,
sql);
}
/*
* postgresExplainDirectModify
* Produce extra output for EXPLAIN of a ForeignScan that modifies a
* foreign table directly
*/
static void
postgresExplainDirectModify(ForeignScanState *node, ExplainState *es)
{
List *fdw_private;
char *sql;
PgFdwExplainState *pgfdw_explain_state;
fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
if (es->verbose)
ExplainPropertyText("Remote SQL", sql, es);
pgfdw_explain_state = GetExplainExtensionState(es, GET_EXTENSION_ID());
if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
explain_remote_query(node->ss.ps.plan->plan_node_id,
es,
pgfdw_explain_state,
RelationGetRelid(node->ss.ss_currentRelation),
sql);
}
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-01-07 10:00 dinesh salve <cooltodinesh@gmail.com>
parent: Sami Imseih <samimseih@gmail.com>
0 siblings, 1 reply; 31+ messages in thread
From: dinesh salve @ 2026-01-07 10:00 UTC (permalink / raw)
To: Sami Imseih <samimseih@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
Thanks Sami for feedback. Few points I wanted to call out and need your
inputs on -
Supporting remote_plans options for inserts:
Only "explain insert" are executed with bind variables (verified by logging
all sqls while running make check) and while executing that on remote is
erroring out with error "there is no parameter $1". We can either NOT
support remote plans for insert statements or always use generic_plan
option on remote sql. Using "generic_plan" on remote comes with an
additional check if remote supports this option or not in case remote shard
is older postgres.
I prefer not supporting remote_plans for inserts as there is nothing much
that goes in insert statement plans unless its "insert into..select". User
can always run explain on that select separately. Appreciate your inputs on
this.
About decision which explain options we should forward to remote shard:
This is because local and remote postgres could be different and we still
need to address what all options we send in remote sql as remote shard
might not even support them. We can forward only limited options to remote
which are widely supported (pg >= 9) i.e. verbose, costs, buffers, format
only.
If we need to support all possible options, we need to query the version of
remote postgres and then prepare remote sql. Thoughts?
Regard,
Dinesh (AWS)
On Wed, Dec 10, 2025 at 2:38 AM Sami Imseih <samimseih@gmail.com> wrote:
> Hi,
>
> I spent more time reviewing this patch. Here are additional comments.
>
> 1/ Remove unnecessary includes
>
> #include "commands/explain_state.h" from option.c.
> #include "utils/json.h" from postgres_fdw.c.
>
> 2/ Add new EXPLAIN options
>
> MEMORY and SUMMARY flags added to the remote EXPLAIN query formatting.
> These do not require ANALYZE to be used.
>
> A larger question is how would we want to ensure that new core EXPLAIN
> options can be automatically set?
>
> This is not quite common, but perhaps it is a good thing to add a comment
> near ExplainState explaining that if a new option is added, make sure
> that postgre_fdw remote_plans are updated.
>
> ```
> typedef struct ExplainState
> {
> StringInfo str; /* output buffer */
> /* options */
> bool verbose; /* be verbose */
> bool analyze; /* print actual times */
> bool costs; /* print estimated co
>
> ```
>
> 3/ Removed unnecessary pstrdup() when appending remote plan rows to
> explain_plan.
>
> Removed unnecessary pstrdup() when appending remote plan rows to
> explain_plan.
>
> ```
> + appendStringInfo(&explain->explain_plan,
> "%s\n", pstrdup(PQgetvalue(res, i, 0)));
> ```
>
>
> 4/ Simplify foreign table OID handling in postgresExplainForeignScan
>
> I am not sure why we need a list that can only hold a single value.
> Can we just use an Oid variable to store this?
>
>
> 5/ Encapsulates getting the connection, executing the remote EXPLAIN,
> and releasing the connection.
>
> Replaces repeated code in postgresExplainForeignScan,
> postgresExplainForeignModify, and postgresExplainDirectModify.
>
> For #4 and #5, attached is my attempt to simplify these routines. What
> do you think?
>
> 6/ Updated typedefs.list
>
> ... to include PgFdwExplainRemotePlans and PgFdwExplainState.
>
>
> 7/ Tests
>
> I quickly skimmed the tests, but I did not see a join push-down test.
> We should add
> that.
>
>
> --
> Sami Imseih
> Amazon Web Services (AWS)
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-01-10 00:16 Sami Imseih <samimseih@gmail.com>
parent: dinesh salve <cooltodinesh@gmail.com>
0 siblings, 1 reply; 31+ messages in thread
From: Sami Imseih @ 2026-01-10 00:16 UTC (permalink / raw)
To: dinesh salve <cooltodinesh@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
> Supporting remote_plans options for inserts:
> Only "explain insert" are executed with bind variables
> (verified by logging all sqls while running make check) and while executing
> that on remote is erroring out with error "there is no parameter $1". We can
> either NOT support remote plans for insert statements
> or always use generic_plan option on remote sql. Using "generic_plan" on
> remote comes with an additional check if remote supports
> this option or not in case remote shard is older postgres.
> I prefer not supporting remote_plans for inserts as there is nothing much that
> goes in insert statement plans unless its "insert into..select".
> User can always run explain on that select separately. Appreciate your
> inputs on this.
After looking at this a bit more, I don't think the INSERT case is the only one.
Here is an example:
```
-- Setup foreign server and table
CREATE EXTENSION postgres_fdw;
CREATE SERVER remote_server FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'localhost', port '5432', dbname 'postgres');
CREATE USER MAPPING FOR CURRENT_USER SERVER remote_server
OPTIONS (user 'postgres', password 'password');
CREATE TABLE local_table (id int, name text);
CREATE FOREIGN TABLE remote_table (
id int,
name text
) SERVER remote_server OPTIONS (table_name 'local_table');
postgres=# load 'postgres_fdw';
LOAD
postgres=# explain (remote_plans, verbose) select * from remote_table
where id = (select 1);
ERROR: there is no parameter $1
CONTEXT: remote SQL command: EXPLAIN (
FORMAT TEXT, VERBOSE
1, COSTS 1, SETTINGS
0) SELECT id, name FROM public.local_table WHERE ((id =
$1::integer))
postgres=#
postgres=# explain (verbose) select * from remote_table where id = (select 1);
QUERY PLAN
----------------------------------------------------------------------------------
Foreign Scan on public.remote_table (cost=100.01..128.54 rows=7 width=36)
Output: remote_table.id, remote_table.name
Remote SQL: SELECT id, name FROM public.local_table WHERE ((id =
$1::integer))
InitPlan expr_1
-> Result (cost=0.00..0.01 rows=1 width=4)
Output: 1
(6 rows)
````
The above is due to the value of the subquery is sent as a parameter; see
`printRemoteParam`in deparse.c.
Also see this comment in deparse.c:
```
* This is used when we're just trying to EXPLAIN the remote query.
* We don't have the actual value of the runtime parameter yet, and we don't
* want the remote planner to generate a plan that depends on such a value
* anyway. Thus, we can't do something simple like "$1::paramtype".
* Instead, we emit "((SELECT null::paramtype)::paramtype)".
```
The above comment is related to the EXPLAIN being sent remotely when
use_remote_estimate is enabled. But the point is, it will not be possible to
send the runtime parameters to the remote EXPLAIN.
So "generic_plan" as a mandatory option may be the best way to proceed,
and only make the remote_plans option available to remote versions that
support this option.
Maybe others have a better way?
> About decision which explain options we should forward to remote shard:
> This is because local and remote postgres could be different and we still
> need to address what all options we send in remote sql as remote shard
> might not even support them. We can forward only limited options to
> remote which are widely supported (pg >= 9) i.e. verbose, costs, buffers,
> format only. If we need to support all possible options, we need to query
> the version of remote postgres and then prepare remote sql. Thoughts?
I think if we try to forward an option that is on the source side but not on
the remote side, it's fair to just error out with "ERROR:
unrecognized EXPLAIN option..."
That should be acceptable, because the user will know better not to use that
option. right?
--
Sami Imseih
Amazon Web Services (AWS)
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-06-19 19:04 dinesh salve <cooltodinesh@gmail.com>
parent: Sami Imseih <samimseih@gmail.com>
0 siblings, 1 reply; 31+ messages in thread
From: dinesh salve @ 2026-06-19 19:04 UTC (permalink / raw)
To: Sami Imseih <samimseih@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
> So "generic_plan" as a mandatory option may be the best way to proceed,
> and only make the remote_plans option available to remote versions that
> support this option.
> Maybe others have a better way?
I agree, I found use of generic_plan convenient here. Attached patch 2
considers this. I have added an error message if the remote postgres server
is not compatible with options being sent. Also updated documentation with
limitations.
Thanks a lot for feedback, Sami. Please review the attached patch and share
feedback.
On Sat, Jan 10, 2026 at 5:46 AM Sami Imseih <samimseih@gmail.com> wrote:
> > Supporting remote_plans options for inserts:
> > Only "explain insert" are executed with bind variables
> > (verified by logging all sqls while running make check) and while
> executing
> > that on remote is erroring out with error "there is no parameter $1". We
> can
> > either NOT support remote plans for insert statements
> > or always use generic_plan option on remote sql. Using "generic_plan" on
> > remote comes with an additional check if remote supports
> > this option or not in case remote shard is older postgres.
> > I prefer not supporting remote_plans for inserts as there is nothing
> much that
> > goes in insert statement plans unless its "insert into..select".
> > User can always run explain on that select separately. Appreciate your
> > inputs on this.
>
> After looking at this a bit more, I don't think the INSERT case is the
> only one.
>
> Here is an example:
> ```
> -- Setup foreign server and table
> CREATE EXTENSION postgres_fdw;
> CREATE SERVER remote_server FOREIGN DATA WRAPPER postgres_fdw
> OPTIONS (host 'localhost', port '5432', dbname 'postgres');
> CREATE USER MAPPING FOR CURRENT_USER SERVER remote_server
> OPTIONS (user 'postgres', password 'password');
>
> CREATE TABLE local_table (id int, name text);
> CREATE FOREIGN TABLE remote_table (
> id int,
> name text
> ) SERVER remote_server OPTIONS (table_name 'local_table');
>
> postgres=# load 'postgres_fdw';
> LOAD
> postgres=# explain (remote_plans, verbose) select * from remote_table
> where id = (select 1);
> ERROR: there is no parameter $1
> CONTEXT: remote SQL command: EXPLAIN (
> FORMAT TEXT, VERBOSE
> 1, COSTS 1, SETTINGS
> 0) SELECT id, name FROM public.local_table WHERE ((id =
> $1::integer))
> postgres=#
>
> postgres=# explain (verbose) select * from remote_table where id = (select
> 1);
> QUERY PLAN
>
> ----------------------------------------------------------------------------------
> Foreign Scan on public.remote_table (cost=100.01..128.54 rows=7 width=36)
> Output: remote_table.id, remote_table.name
> Remote SQL: SELECT id, name FROM public.local_table WHERE ((id =
> $1::integer))
> InitPlan expr_1
> -> Result (cost=0.00..0.01 rows=1 width=4)
> Output: 1
> (6 rows)
>
> ````
>
> The above is due to the value of the subquery is sent as a parameter; see
> `printRemoteParam`in deparse.c.
>
> Also see this comment in deparse.c:
>
> ```
> * This is used when we're just trying to EXPLAIN the remote query.
> * We don't have the actual value of the runtime parameter yet, and we don't
> * want the remote planner to generate a plan that depends on such a value
> * anyway. Thus, we can't do something simple like "$1::paramtype".
> * Instead, we emit "((SELECT null::paramtype)::paramtype)".
> ```
>
> The above comment is related to the EXPLAIN being sent remotely when
> use_remote_estimate is enabled. But the point is, it will not be possible
> to
> send the runtime parameters to the remote EXPLAIN.
>
> So "generic_plan" as a mandatory option may be the best way to proceed,
> and only make the remote_plans option available to remote versions that
> support this option.
>
> Maybe others have a better way?
>
>
> > About decision which explain options we should forward to remote shard:
> > This is because local and remote postgres could be different and we still
> > need to address what all options we send in remote sql as remote shard
> > might not even support them. We can forward only limited options to
> > remote which are widely supported (pg >= 9) i.e. verbose, costs, buffers,
> > format only. If we need to support all possible options, we need to query
> > the version of remote postgres and then prepare remote sql. Thoughts?
>
> I think if we try to forward an option that is on the source side but not
> on
> the remote side, it's fair to just error out with "ERROR:
> unrecognized EXPLAIN option..."
>
> That should be acceptable, because the user will know better not to use
> that
> option. right?
>
> --
> Sami Imseih
> Amazon Web Services (AWS)
>
Attachments:
0002-postgres_fdw-show-remote-EXPLAIN-plans-via-REMOTE_PL.patch (application/octet-stream, 68.8K) download
From f46403f33189862933b545d4c4b1f9b0c68f2f78 Mon Sep 17 00:00:00 2001
From: Dinesh Salve <cooltodinesh@gmail.com>
Date: Sat, 20 Jun 2026 00:26:00 +0530
Subject: [PATCH] postgres_fdw: show remote EXPLAIN plans via REMOTE_PLANS
option
Add a REMOTE_PLANS option to EXPLAIN that, for every foreign scan or
foreign modification, runs EXPLAIN on the remote server for the
corresponding remote query and prints the result in a "Remote Plans"
section keyed by the local plan node id.
The remote query that postgres_fdw sends often contains $n parameter
placeholders (parameterized foreign scans and joins, subquery outputs,
and INSERT/UPDATE/DELETE), which a plain remote EXPLAIN cannot plan and
fails with "there is no parameter $1". REMOTE_PLANS therefore forces
GENERIC_PLAN on the remote EXPLAIN, which plans such statements without
bound values. GENERIC_PLAN is only available from PostgreSQL 16, so
REMOTE_PLANS errors out on older remote servers; the plans shown are
consequently generic.
REMOTE_PLANS cannot be combined with ANALYZE, so the ANALYZE-only EXPLAIN
options are not forwarded to the remote. The remaining plan-shaping
options the user requested are forwarded as-is; if the remote server does
not recognize one of them it errors out with "unrecognized EXPLAIN
option".
The option is registered when postgres_fdw is loaded.
---
.../postgres_fdw/expected/postgres_fdw.out | 626 ++++++++++++++++++
contrib/postgres_fdw/option.c | 71 ++
contrib/postgres_fdw/postgres_fdw.c | 279 +++++++-
contrib/postgres_fdw/postgres_fdw.h | 26 +
contrib/postgres_fdw/sql/postgres_fdw.sql | 50 ++
doc/src/sgml/postgres-fdw.sgml | 41 ++
src/include/commands/explain_state.h | 2 +-
src/tools/pgindent/typedefs.list | 2 +
8 files changed, 1084 insertions(+), 13 deletions(-)
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index e90289e..803ac6c 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -471,6 +471,173 @@ SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
fixed |
(1 row)
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ - Plan: +
+ Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "ft1" +
+ Schema: "public" +
+ Alias: "t1" +
+ Disabled: false +
+ Output: +
+ - "c1" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Remote SQL: "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))"+
+ Plan Node ID: 0 +
+ Remote Plans: +
+ Plan Node ID 0: +
+ - Plan: +
+ Node Type: "Index Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Schema: "S 1" +
+ Alias: "T 1" +
+ Disabled: false +
+ Output: +
+ - "\"C 1\"" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Index Cond: "(\"T 1\".\"C 1\" = 101)"
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>ft1</Relation-Name> +
+ <Schema>public</Schema> +
+ <Alias>t1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>c1</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Remote-SQL>SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))</Remote-SQL>+
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-0> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Schema>S 1</Schema> +
+ <Alias>T 1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>"C 1"</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Index-Cond>("T 1"."C 1" = 101)</Index-Cond> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-0> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "ft1", +
+ "Schema": "public", +
+ "Alias": "t1", +
+ "Disabled": false, +
+ "Output": ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Remote SQL": "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))",+
+ "Plan Node ID": 0 +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 0": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Schema": "S 1", +
+ "Alias": "T 1", +
+ "Disabled": false, +
+ "Output": ["\"C 1\"", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Index Cond": "(\"T 1\".\"C 1\" = 101)" +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = 101)
+(10 rows)
+
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -646,6 +813,25 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2
110 | 110 | 110
(10 rows)
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------------------------------------
+ Foreign Scan
+ Output: t1.c1, t2.c1
+ Relations: (public.ft1 t1) INNER JOIN (public.ft2 t2)
+ Remote SQL: SELECT r1."C 1", r2."C 1" FROM ("S 1"."T 1" r1 INNER JOIN "S 1"."T 1" r2 ON (((r2."C 1" = r1."C 1")) AND ((r1.c2 = 10))))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Seq Scan on "S 1"."T 1" r2
+ Output: r2."C 1", r2."C 1"
+ Filter: (r2.c2 = 10)
+(11 rows)
+
RESET enable_hashjoin;
RESET enable_nestloop;
-- Test executing assertion in estimate_path_cost_size() that makes sure that
@@ -790,6 +976,32 @@ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
47 | 7 | 00047 | Tue Feb 17 00:00:00 1970 PST | Tue Feb 17 00:00:00 1970 | 7 | 7 | foo | 7 | 7 | 00007 | Thu Jan 08 00:00:00 1970 PST | Thu Jan 08 00:00:00 1970 | 7 | 7 | foo
(1 row)
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+ QUERY PLAN
+-------------------------------------------------------------------------------------------------------------
+ Nested Loop
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8, b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Plan Node ID: 0
+ -> Index Scan using t1_pkey on "S 1"."T 1" a
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8
+ Index Cond: (a."C 1" = 47)
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft2 b
+ Output: b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = $1::integer))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = $1)
+(17 rows)
+
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM ft2 a, ft2 b
@@ -5116,6 +5328,373 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
Remote SQL: SELECT r5."C 1", r6.c1 FROM ("S 1"."T 1" r5 INNER JOIN "S 1"."T 3" r6 ON (((r5."C 1" = r6.c1)))) ORDER BY r5."C 1" ASC NULLS LAST
(13 rows)
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ERROR: EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ Limit
+ Plan Node ID: 0
+ -> Merge Semi Join
+ Merge Cond: (ft1.c1 = ft2_1.c1)
+ Plan Node ID: 1
+ -> Foreign Scan
+ Relations: (ft1) INNER JOIN (ft2)
+ Plan Node ID: 2
+ -> Foreign Scan
+ Relations: (ft2 ft2_1) INNER JOIN (ft4)
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Only Scan using t1_pkey on "T 1" r2
+ Plan Node ID 3:
+ Merge Join
+ Merge Cond: (r5."C 1" = r6.c1)
+ -> Index Only Scan using t1_pkey on "T 1" r5
+ -> Sort
+ Sort Key: r6.c1
+ -> Seq Scan on "T 3" r6
+(22 rows)
+
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Limit</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Semi</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>false</Inner-Unique> +
+ <Merge-Cond>(ft1.c1 = ft2_1.c1)</Merge-Cond> +
+ <Plan-Node-ID>1</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft1) INNER JOIN (ft2)</Relations> +
+ <Plan-Node-ID>2</Plan-Node-ID> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft2 ft2_1) INNER JOIN (ft4)</Relations> +
+ <Plan-Node-ID>3</Plan-Node-ID> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-2> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r2</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-2> +
+ <Plan-Node-ID-3> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Inner</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>true</Inner-Unique> +
+ <Merge-Cond>(r5."C 1" = r6.c1)</Merge-Cond> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r5</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Sort</Node-Type> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Sort-Key> +
+ <Item>r6.c1</Item> +
+ </Sort-Key> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Seq Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship>+
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>T 3</Relation-Name> +
+ <Alias>r6</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-3> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Limit", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Plan Node ID": 0, +
+ "Plans": [ +
+ { +
+ "Node Type": "Merge Join", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Semi", +
+ "Disabled": false, +
+ "Inner Unique": false, +
+ "Merge Cond": "(ft1.c1 = ft2_1.c1)", +
+ "Plan Node ID": 1, +
+ "Plans": [ +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft1) INNER JOIN (ft2)", +
+ "Plan Node ID": 2 +
+ }, +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft2 ft2_1) INNER JOIN (ft4)",+
+ "Plan Node ID": 3 +
+ } +
+ ] +
+ } +
+ ] +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 2": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Only Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r2", +
+ "Disabled": false +
+ } +
+ } +
+ ] +
+ ], +
+ "Plan Node ID 3": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Merge Join", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Inner", +
+ "Disabled": false, +
+ "Inner Unique": true, +
+ "Merge Cond": "(r5.\"C 1\" = r6.c1)", +
+ "Plans": [ +
+ { +
+ "Node Type": "Index Only Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r5", +
+ "Disabled": false +
+ }, +
+ { +
+ "Node Type": "Sort", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Sort Key": ["r6.c1"], +
+ "Plans": [ +
+ { +
+ "Node Type": "Seq Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "T 3", +
+ "Alias": "r6", +
+ "Disabled": false +
+ } +
+ ] +
+ } +
+ ] +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ - Plan: +
+ Node Type: "Limit" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Plan Node ID: 0 +
+ Plans: +
+ - Node Type: "Merge Join" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Semi" +
+ Disabled: false +
+ Inner Unique: false +
+ Merge Cond: "(ft1.c1 = ft2_1.c1)" +
+ Plan Node ID: 1 +
+ Plans: +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft1) INNER JOIN (ft2)" +
+ Plan Node ID: 2 +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft2 ft2_1) INNER JOIN (ft4)"+
+ Plan Node ID: 3 +
+ Remote Plans: +
+ Plan Node ID 2: +
+ - Plan: +
+ Node Type: "Index Only Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r2" +
+ Disabled: false +
+ Plan Node ID 3: +
+ - Plan: +
+ Node Type: "Merge Join" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Inner" +
+ Disabled: false +
+ Inner Unique: true +
+ Merge Cond: "(r5.\"C 1\" = r6.c1)" +
+ Plans: +
+ - Node Type: "Index Only Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r5" +
+ Disabled: false +
+ - Node Type: "Sort" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Sort Key: +
+ - "r6.c1" +
+ Plans: +
+ - Node Type: "Seq Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "T 3" +
+ Alias: "r6" +
+ Disabled: false
+(1 row)
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -6354,6 +6933,25 @@ SELECT * FROM ft8 WHERE c1 = '[2,3)' ORDER BY c1, c4;
[2,3) | 3 | AAA002 | [01-01-2000,01-01-2020)
(1 row)
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
+ QUERY PLAN
+---------------------------------------------------------------------------------------
+ Update on public.ft2
+ Plan Node ID: 0
+ -> Foreign Update on public.ft2
+ Remote SQL: UPDATE "S 1"."T 1" SET c2 = (c2 + 300) WHERE ((("C 1" % 10) = 3))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Update on "S 1"."T 1"
+ -> Seq Scan on "S 1"."T 1"
+ Output: (c2 + 300), ctid
+ Filter: (("T 1"."C 1" % 10) = 3)
+(12 rows)
+
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id;
@@ -12322,6 +12920,34 @@ SELECT * FROM insert_tbl ORDER BY a;
2505 | 505 | bar
(2 rows)
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+ QUERY PLAN
+-------------------------------------------------------------------------
+ Insert on public.insert_tbl
+ Remote SQL: INSERT INTO public.base_tbl4(a, b, c) VALUES ($1, $2, $3)
+ Batch Size: 1
+ Plan Node ID: 0
+ -> Append
+ Plan Node ID: 1
+ -> Seq Scan on public.local_tbl
+ Output: local_tbl.a, local_tbl.b, local_tbl.c
+ Plan Node ID: 2
+ -> Async Foreign Scan on public.remote_tbl
+ Output: remote_tbl.a, remote_tbl.b, remote_tbl.c
+ Remote SQL: SELECT a, b, c FROM public.base_tbl3
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Insert on public.base_tbl4
+ -> Result
+ Output: $1, $2, $3
+ Plan Node ID 3:
+ Seq Scan on public.base_tbl3
+ Output: a, b, c
+(22 rows)
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 79b16c3..c39a387 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -17,6 +17,7 @@
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#include "commands/defrem.h"
+#include "commands/explain.h"
#include "commands/extension.h"
#include "libpq/libpq-be.h"
#include "postgres_fdw.h"
@@ -40,6 +41,13 @@ typedef struct PgFdwOption
*/
static PgFdwOption *postgres_fdw_options;
+/*
+ * EXPLAIN hooks
+ */
+static explain_per_node_hook_type prev_explain_per_node_hook;
+static explain_per_plan_hook_type prev_explain_per_plan_hook;
+static explain_validate_options_hook_type prev_explain_validate_options_hook;
+
/*
* GUC parameters
*/
@@ -566,6 +574,57 @@ process_pgfdw_appname(const char *appname)
return buf.data;
}
+/*
+ * Get the PgFdwExplainState structure from an ExplainState; if there is
+ * none, create one, attach it to the ExplainState, and return it.
+ */
+static PgFdwExplainState *
+pgfdw_ensure_options(ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"));
+
+ if (pgfdw_explain_state == NULL)
+ {
+ pgfdw_explain_state = palloc0(sizeof(PgFdwExplainState));
+ SetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"), pgfdw_explain_state);
+ pgfdw_explain_state->all_remote_plans = NIL;
+ }
+
+ return pgfdw_explain_state;
+}
+
+/*
+ * Parse handler for EXPLAIN (REMOTE_PLANS).
+ */
+static void
+pgfdw_remote_plans_apply(ExplainState *es, DefElem *opt, ParseState *pstate)
+{
+ PgFdwExplainState *options = pgfdw_ensure_options(es);
+
+ options->remote_plans = defGetBoolean(opt);
+}
+
+static void
+postgresExplainValidateOptions(ExplainState *es, List *options, ParseState *pstate)
+{
+ ListCell *lc;
+
+ foreach(lc, options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0)
+ {
+ if (defGetBoolean(opt) && es->analyze)
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together"));
+ }
+ }
+}
+
/*
* Module load callback
*/
@@ -592,4 +651,16 @@ _PG_init(void)
NULL);
MarkGUCPrefixReserved("postgres_fdw");
+
+ RegisterExtensionExplainOption("remote_plans", pgfdw_remote_plans_apply,
+ GUCCheckBooleanExplainOption);
+
+ /* per node EXPLAIN hook */
+ prev_explain_per_node_hook = explain_per_node_hook;
+ explain_per_node_hook = postgresExplainPerNode;
+ prev_explain_per_plan_hook = explain_per_plan_hook;
+ explain_per_plan_hook = postgresExplainPerPlan;
+ prev_explain_validate_options_hook = explain_validate_options_hook;
+ explain_validate_options_hook = postgresExplainValidateOptions;
+
}
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 6dbae58..8eeb1e6 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -137,6 +137,26 @@ enum FdwDirectModifyPrivateIndex
FdwDirectModifyPrivateSetProcessed,
};
+static const char *const explain_formats[] = {
+ [EXPLAIN_FORMAT_TEXT] = "TEXT",
+ [EXPLAIN_FORMAT_JSON] = "JSON",
+ [EXPLAIN_FORMAT_XML] = "XML",
+ [EXPLAIN_FORMAT_YAML] = "YAML",
+};
+
+/*
+ * Track the extension id in the backend.
+ */
+static int extension_id = -1;
+
+static int
+get_extension_id(void)
+{
+ if (extension_id == -1)
+ extension_id = GetExplainExtensionId("postgres_fdw");
+ return extension_id;
+}
+
/*
* Execution state of a foreign scan using postgres_fdw.
*/
@@ -3038,6 +3058,109 @@ postgresEndDirectModify(ForeignScanState *node)
/* MemoryContext will be deleted automatically. */
}
+static void
+postgresExplainStatement(int plan_node_id,
+ ExplainState *es,
+ PgFdwExplainState * pgfdw_explain_state,
+ PGconn *conn,
+ char *sql)
+{
+ PGresult *volatile res = NULL;
+ StringInfoData explain_sql;
+ int remote_version = PQserverVersion(conn);
+
+ /*
+ * REMOTE_PLANS relies on GENERIC_PLAN to explain the statements that
+ * postgres_fdw sends to the remote server: the deparsed SQL embeds $n
+ * parameter placeholders (for parameterized scans, and for INSERT/UPDATE/
+ * DELETE), and a plain remote EXPLAIN would fail with "there is no
+ * parameter $1". GENERIC_PLAN plans such statements without bound values.
+ * It is only available on remote servers running v16 or later, so refuse
+ * to proceed against anything older rather than emit a confusing error.
+ */
+ if (remote_version < 160000)
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("EXPLAIN option REMOTE_PLANS requires a remote server version of 16 or later"),
+ errdetail("The remote server version is %d.", remote_version));
+
+ PG_TRY();
+ {
+ int numrows,
+ i;
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) palloc(sizeof(PgFdwExplainRemotePlans));
+
+ initStringInfo(&explain_sql);
+ initStringInfo(&explain->explain_plan);
+
+ /*
+ * Build the remote EXPLAIN. GENERIC_PLAN is always forced on (see
+ * above). Of the remaining options we forward only the ones that
+ * describe the plan and that the user actually requested; the
+ * ANALYZE-only options (WAL, TIMING, SERIALIZE, IO, SUMMARY) are
+ * intentionally omitted because REMOTE_PLANS cannot be combined with
+ * ANALYZE. If the user requests an option that the remote server does
+ * not recognize, the remote EXPLAIN simply errors out with
+ * "unrecognized EXPLAIN option", which is a clear enough signal.
+ */
+ appendStringInfoString(&explain_sql, "EXPLAIN (GENERIC_PLAN TRUE");
+ appendStringInfo(&explain_sql, ", VERBOSE %s", es->verbose ? "TRUE" : "FALSE");
+ appendStringInfo(&explain_sql, ", COSTS %s", es->costs ? "TRUE" : "FALSE");
+ appendStringInfo(&explain_sql, ", SETTINGS %s", es->settings ? "TRUE" : "FALSE");
+ appendStringInfo(&explain_sql, ", BUFFERS %s", es->buffers ? "TRUE" : "FALSE");
+ appendStringInfo(&explain_sql, ", MEMORY %s", es->memory ? "TRUE" : "FALSE");
+
+ appendStringInfo(&explain_sql, ", FORMAT %s) %s",
+ explain_formats[es->format], sql);
+
+ /* Run the query and collect the remote plan */
+ res = pgfdw_exec_query(conn, explain_sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, explain_sql.data);
+
+ numrows = PQntuples(res);
+
+ for (i = 0; i < numrows; i++)
+ appendStringInfo(&explain->explain_plan, "%s\n", PQgetvalue(res, i, 0));
+
+ if (explain->explain_plan.len > 0 && explain->explain_plan.data[explain->explain_plan.len - 1] == '\n')
+ explain->explain_plan.data[--explain->explain_plan.len] = '\0';
+
+ explain->plan_node_id = plan_node_id;
+ pgfdw_explain_state->all_remote_plans = lappend(pgfdw_explain_state->all_remote_plans, explain);
+ }
+ PG_FINALLY();
+ {
+ if (res)
+ PQclear(res);
+
+ if (explain_sql.data)
+ pfree(explain_sql.data);
+ }
+ PG_END_TRY();
+}
+
+/*
+ * explain_remote_query
+ * Helper function to get connection and execute remote EXPLAIN
+ */
+static void
+explain_remote_query(int plan_node_id, ExplainState *es,
+ PgFdwExplainState *pgfdw_explain_state,
+ Oid foreign_table_oid, char *sql)
+{
+ UserMapping *user;
+ PGconn *conn;
+ ForeignTable *table;
+
+ table = GetForeignTable(foreign_table_oid);
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+
+ postgresExplainStatement(plan_node_id, es, pgfdw_explain_state, conn, sql);
+ ReleaseConnection(conn);
+}
+
/*
* postgresExplainForeignScan
* Produce extra output for EXPLAIN of a ForeignScan on a foreign table
@@ -3047,6 +3170,12 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
List *fdw_private = plan->fdw_private;
+ PgFdwExplainState *pgfdw_explain_state;
+ char *sql;
+ Oid foreign_table_oid = InvalidOid;
+
+ if (node->ss.ss_currentRelation)
+ foreign_table_oid = RelationGetRelid(node->ss.ss_currentRelation);
/*
* Identify foreign scans that are really joins or upper relations. The
@@ -3108,6 +3237,13 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
Assert(rte->rtekind == RTE_RELATION);
/* This logic should agree with explain.c's ExplainTargetRel */
relname = get_rel_name(rte->relid);
+
+ /*
+ * Save first table OID for getting server connection
+ */
+ if (!OidIsValid(foreign_table_oid))
+ foreign_table_oid = rte->relid;
+
if (es->verbose)
{
char *namespace;
@@ -3133,16 +3269,25 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
ExplainPropertyText("Relations", relations.data, es);
}
+ sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
+
/*
* Add remote query, when VERBOSE option is specified.
*/
if (es->verbose)
- {
- char *sql;
-
- sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ /* If we don't have a foreign table oid by now, something went wrong */
+ Assert(foreign_table_oid);
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ es,
+ pgfdw_explain_state,
+ foreign_table_oid,
+ sql);
}
/*
@@ -3156,11 +3301,12 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
int subplan_index,
ExplainState *es)
{
+ char *sql = strVal(list_nth(fdw_private,
+ FdwModifyPrivateUpdateSql));
+ PgFdwExplainState *pgfdw_explain_state;
+
if (es->verbose)
{
- char *sql = strVal(list_nth(fdw_private,
- FdwModifyPrivateUpdateSql));
-
ExplainPropertyText("Remote SQL", sql, es);
/*
@@ -3170,6 +3316,14 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
if (rinfo->ri_BatchSize > 0)
ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
}
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(mtstate->ps.plan->plan_node_id,
+ es,
+ pgfdw_explain_state,
+ rinfo->ri_RelationDesc->rd_rel->oid,
+ sql);
}
/*
@@ -3182,13 +3336,22 @@ postgresExplainDirectModify(ForeignScanState *node, ExplainState *es)
{
List *fdw_private;
char *sql;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
+ sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
if (es->verbose)
- {
- fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
- sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ es,
+ pgfdw_explain_state,
+ RelationGetRelid(node->ss.ss_currentRelation),
+ sql);
}
/*
@@ -8835,3 +8998,95 @@ get_batch_size_option(Relation rel)
return batch_size;
}
+
+void
+postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship, const char *plan_name,
+ ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state == NULL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ ExplainPropertyInteger("Plan Node ID", NULL, planstate->plan->plan_node_id, es);
+}
+
+static void
+pgfdwFormatRemotePlan(PgFdwExplainRemotePlans * explain,
+ ExplainState *es,
+ int plan_node_id)
+{
+ char *token;
+ StringInfoData remote_plan_name;
+
+ initStringInfo(&remote_plan_name);
+ appendStringInfo(&remote_plan_name, "Plan Node ID %d", plan_node_id);
+
+ ExplainOpenGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Plan Node ID %d:", plan_node_id);
+ appendStringInfoString(es->str, "\n");
+ }
+
+ while ((token = strsep(&explain->explain_plan.data, "\n")) != NULL)
+ {
+ if (es->format == EXPLAIN_FORMAT_JSON ||
+ es->format == EXPLAIN_FORMAT_YAML)
+ appendStringInfoString(es->str, "\n");
+
+ appendStringInfoSpaces(es->str, (es->indent == 0) ? 2 : es->indent * 2);
+ appendStringInfoString(es->str, token);
+
+ if (es->format == EXPLAIN_FORMAT_XML ||
+ es->format == EXPLAIN_FORMAT_TEXT)
+ appendStringInfoString(es->str, "\n");
+ }
+
+ ExplainCloseGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+ pfree(remote_plan_name.data);
+}
+
+void
+postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state == NULL ||
+ pgfdw_explain_state->all_remote_plans == NIL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ ExplainOpenGroup("Remote Plans", "Remote Plans", true, es);
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Remote Plans:\n");
+ appendStringInfo(es->str, "-------------\n");
+ }
+
+ /* Process every remote plan captured */
+ foreach(lc, pgfdw_explain_state->all_remote_plans)
+ {
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) lfirst(lc);
+
+ pgfdwFormatRemotePlan(explain,
+ es,
+ explain->plan_node_id);
+ }
+
+ ExplainCloseGroup("Remote Plans", "Remote Plans", true, es);
+}
diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h
index a2bb1ff..cf74dba 100644
--- a/contrib/postgres_fdw/postgres_fdw.h
+++ b/contrib/postgres_fdw/postgres_fdw.h
@@ -13,6 +13,7 @@
#ifndef POSTGRES_FDW_H
#define POSTGRES_FDW_H
+#include "commands/explain_state.h"
#include "foreign/foreign.h"
#include "lib/stringinfo.h"
#include "libpq/libpq-be-fe.h"
@@ -151,6 +152,21 @@ typedef enum PgFdwSamplingMethod
ANALYZE_SAMPLE_BERNOULLI, /* TABLESAMPLE bernoulli */
} PgFdwSamplingMethod;
+typedef struct PgFdwExplainRemotePlans
+{
+ int plan_node_id;
+ StringInfoData explain_plan;
+
+} PgFdwExplainRemotePlans;
+
+typedef struct PgFdwExplainState
+{
+ List *all_remote_plans;
+
+ /* EXPLAIN options */
+ bool remote_plans;
+} PgFdwExplainState;
+
/* in postgres_fdw.c */
extern int set_transmission_modes(void);
extern void reset_transmission_modes(int nestlevel);
@@ -178,6 +194,16 @@ extern int ExtractConnectionOptions(List *defelems,
extern List *ExtractExtensionList(const char *extensionsString,
bool warnOnMissing);
extern char *process_pgfdw_appname(const char *appname);
+extern void postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship,
+ const char *plan_name,
+ ExplainState *es);
+extern void postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv);
extern char *pgfdw_application_name;
/* in deparse.c */
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index dfc58be..26a3f4f 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -311,6 +311,11 @@ SELECT * FROM ft1 t1 WHERE t1.c3 = (SELECT MAX(c3) FROM ft2 t2) ORDER BY c1;
WITH t1 AS (SELECT * FROM ft1 WHERE c1 <= 10) SELECT t2.c1, t2.c2, t2.c3, t2.c4 FROM t1, ft2 t2 WHERE t1.c1 = t2.c1 ORDER BY t1.c1;
-- fixed values
SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -338,6 +343,12 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 left join ft1 t2 full join ft2
EXPLAIN (VERBOSE, COSTS OFF)
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
+
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+
RESET enable_hashjoin;
RESET enable_nestloop;
@@ -379,6 +390,11 @@ EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c8 = 'foo'; -- can't be
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
@@ -1527,6 +1543,33 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
ORDER BY ft1.c1 LIMIT 5;
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -1587,6 +1630,10 @@ DELETE FROM ft8 FOR PORTION OF c4 FROM '2005-01-01' TO '2006-01-01'
WHERE c1 = '[2,3)';
SELECT * FROM ft8 WHERE c1 = '[2,3)' ORDER BY c1, c4;
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
+
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id;
@@ -4194,6 +4241,9 @@ INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_t
SELECT * FROM insert_tbl ORDER BY a;
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index b9e1b04..d36a9f9 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -1197,6 +1197,47 @@ CREATE SUBSCRIPTION my_subscription SERVER subscription_server PUBLICATION testp
The query that is actually sent to the remote server for execution can
be examined using <command>EXPLAIN VERBOSE</command>.
</para>
+
+ <para>
+ In addition to the remote query itself, the plan that the remote server
+ chooses for that query can be examined with the
+ <literal>REMOTE_PLANS</literal> option of <command>EXPLAIN</command>, for
+ example <literal>EXPLAIN (VERBOSE, REMOTE_PLANS) SELECT ...</literal>. For
+ every foreign scan or foreign modification in the local plan,
+ <filename>postgres_fdw</filename> runs <command>EXPLAIN</command> on the
+ remote server for the corresponding remote query and prints the result in a
+ <literal>Remote Plans</literal> section, keyed by the plan node id of the
+ local node.
+ </para>
+
+ <para>
+ The <literal>REMOTE_PLANS</literal> option is registered when
+ <filename>postgres_fdw</filename> is loaded, so the module must be loaded
+ (for example with <command>CREATE EXTENSION postgres_fdw</command>) before
+ the option can be used. The following restrictions apply:
+ <itemizedlist>
+ <listitem>
+ <para>
+ It cannot be combined with <literal>ANALYZE</literal>; doing so raises an
+ error. The remote query is only planned, never executed, so the foreign
+ server is not affected and no remote rows are fetched.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ The remote server must be running <productname>PostgreSQL</productname>
+ 16 or later. The remote query that <filename>postgres_fdw</filename>
+ sends may contain parameter placeholders (for parameterized foreign
+ scans, and for <command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command>),
+ so the option relies on the <literal>GENERIC_PLAN</literal> option of
+ <command>EXPLAIN</command>, which was introduced in that release. As a
+ consequence, the remote plans shown are generic plans that treat those
+ placeholders as unknown values rather than plans for specific parameter
+ values.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
</sect2>
<sect2 id="postgres-fdw-remote-query-execution-environment">
diff --git a/src/include/commands/explain_state.h b/src/include/commands/explain_state.h
index 97bc7ed..ba09c1d 100644
--- a/src/include/commands/explain_state.h
+++ b/src/include/commands/explain_state.h
@@ -45,7 +45,7 @@ typedef struct ExplainWorkersState
typedef struct ExplainState
{
StringInfo str; /* output buffer */
- /* options */
+ /* options. considering updating logic to create explain_sql in postgres_fdw extension if adding new option here.*/
bool verbose; /* be verbose */
bool analyze; /* print actual times */
bool costs; /* print estimated costs */
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f9eb23e..c7b1140 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2304,6 +2304,8 @@ PgChecksumMode
PgFdwAnalyzeState
PgFdwConnState
PgFdwDirectModifyState
+PgFdwExplainRemotePlans
+PgFdwExplainState
PgFdwModifyState
PgFdwOption
PgFdwPathExtraData
base-commit: 2963ddeef2be6d6e064cb9d382f67dcbf2c049a8
--
2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-07-03 18:35 Sami Imseih <samimseih@gmail.com>
parent: dinesh salve <cooltodinesh@gmail.com>
0 siblings, 1 reply; 31+ messages in thread
From: Sami Imseih @ 2026-07-03 18:35 UTC (permalink / raw)
To: dinesh salve <cooltodinesh@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
Hi Dinesh,
Thanks for the patch. v2 needed rebasing, but I also went ahead and applied
my comments to v3.
1/ Forward all user options instead of hardcoding ExplainState booleans
The current approach reads individual ExplainState fields to construct the
remote EXPLAIN:
```
appendStringInfo(&explain_sql, ", VERBOSE %s", es->verbose ? "TRUE" : "FALSE");
...
.....
```
After thinking about this a bit, this creates a maintenance problem.
Any new non-ANALYZE EXPLAIN option added to core requires someone to
remember to update postgres_fdw. I previously suggested a comment
in explain_state.h to remind developers, but I think we should do
something better.
The explain_validate_options_hook already receives the user's
original option list. We save it in PgFdwExplainState and use
to construct the remote EXPLAIN SQL, skipping only remote_plans
and generic_plan.
New core EXPLAIN options will automatically be forwarded to the
remote when the user specifies them, with no postgres_fdw code
change needed. If the remote doesn't recognize an option, it errors
clearly rather than silently ignoring it.
I tested this against a PG 16 remote. EXPLAIN (REMOTE_PLANS, MEMORY)
correctly errors with "unrecognized EXPLAIN option 'memory'" since
PG 16 does not have MEMORY. This seems better than silent omission.
2/ I also made some comment improvements. Some were just too verbose.
3/ Documentation improvements
The generic plan limitation only matters when the remote SQL contains
parameter placeholders. For queries with only literals (e.g.,
WHERE id = 42), the generic plan is identical to a custom plan. The docs
should clarify this rather than making it seem like a general limitation.
I also added some concrete examples showing both cases where a literal
is used vs a parameter.
Attached is my attempt at the above. What do you think?
--
Sami Imseih
Amazon Web Services (AWS)
Attachments:
v3-0001-postgres_fdw-show-remote-EXPLAIN-plans-via-REMOTE.patch (application/octet-stream, 69.3K) download
From 487844c90bed811dcc93b44dcf9c9e399ff1b246 Mon Sep 17 00:00:00 2001
From: Dinesh Salve <cooltodinesh@gmail.com>
Date: Sat, 20 Jun 2026 00:26:00 +0530
Subject: [PATCH v3] postgres_fdw: show remote EXPLAIN plans via REMOTE_PLANS
option
Add a REMOTE_PLANS option to EXPLAIN that, for every foreign scan or
foreign modification, runs EXPLAIN on the remote server for the
corresponding remote query and prints the result in a "Remote Plans"
section keyed by the local plan node id.
The remote query that postgres_fdw sends often contains $n parameter
placeholders (parameterized foreign scans and joins, subquery outputs,
and INSERT/UPDATE/DELETE), which a plain remote EXPLAIN cannot plan and
fails with "there is no parameter $1". REMOTE_PLANS therefore forces
GENERIC_PLAN on the remote EXPLAIN, which plans such statements without
bound values. GENERIC_PLAN is only available from PostgreSQL 16, so
REMOTE_PLANS errors out on older remote servers.
REMOTE_PLANS cannot be combined with ANALYZE. All user-specified EXPLAIN
options (other than REMOTE_PLANS and GENERIC_PLAN) are forwarded to the
remote server as-is. If the remote server does not recognize a forwarded
option, it reports an error.
The option is registered when postgres_fdw is loaded.
---
.../postgres_fdw/expected/postgres_fdw.out | 626 ++++++++++++++++++
contrib/postgres_fdw/option.c | 75 +++
contrib/postgres_fdw/postgres_fdw.c | 268 +++++++-
contrib/postgres_fdw/postgres_fdw.h | 27 +
contrib/postgres_fdw/sql/postgres_fdw.sql | 49 ++
doc/src/sgml/postgres-fdw.sgml | 87 +++
src/include/commands/explain_state.h | 1 +
src/tools/pgindent/typedefs.list | 2 +
8 files changed, 1123 insertions(+), 12 deletions(-)
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 0805c56cb1b..f4326714381 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -471,6 +471,173 @@ SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
fixed |
(1 row)
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ - Plan: +
+ Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "ft1" +
+ Schema: "public" +
+ Alias: "t1" +
+ Disabled: false +
+ Output: +
+ - "c1" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Remote SQL: "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))"+
+ Plan Node ID: 0 +
+ Remote Plans: +
+ Plan Node ID 0: +
+ - Plan: +
+ Node Type: "Index Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Schema: "S 1" +
+ Alias: "T 1" +
+ Disabled: false +
+ Output: +
+ - "\"C 1\"" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Index Cond: "(\"T 1\".\"C 1\" = 101)"
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>ft1</Relation-Name> +
+ <Schema>public</Schema> +
+ <Alias>t1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>c1</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Remote-SQL>SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))</Remote-SQL>+
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-0> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Schema>S 1</Schema> +
+ <Alias>T 1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>"C 1"</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Index-Cond>("T 1"."C 1" = 101)</Index-Cond> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-0> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "ft1", +
+ "Schema": "public", +
+ "Alias": "t1", +
+ "Disabled": false, +
+ "Output": ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Remote SQL": "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))",+
+ "Plan Node ID": 0 +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 0": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Schema": "S 1", +
+ "Alias": "T 1", +
+ "Disabled": false, +
+ "Output": ["\"C 1\"", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Index Cond": "(\"T 1\".\"C 1\" = 101)" +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = 101)
+(10 rows)
+
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -646,6 +813,25 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2
110 | 110 | 110
(10 rows)
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------------------------------------
+ Foreign Scan
+ Output: t1.c1, t2.c1
+ Relations: (public.ft1 t1) INNER JOIN (public.ft2 t2)
+ Remote SQL: SELECT r1."C 1", r2."C 1" FROM ("S 1"."T 1" r1 INNER JOIN "S 1"."T 1" r2 ON (((r2."C 1" = r1."C 1")) AND ((r1.c2 = 10))))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Seq Scan on "S 1"."T 1" r2
+ Output: r2."C 1", r2."C 1"
+ Filter: (r2.c2 = 10)
+(11 rows)
+
RESET enable_hashjoin;
RESET enable_nestloop;
-- Test executing assertion in estimate_path_cost_size() that makes sure that
@@ -790,6 +976,32 @@ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
47 | 7 | 00047 | Tue Feb 17 00:00:00 1970 PST | Tue Feb 17 00:00:00 1970 | 7 | 7 | foo | 7 | 7 | 00007 | Thu Jan 08 00:00:00 1970 PST | Thu Jan 08 00:00:00 1970 | 7 | 7 | foo
(1 row)
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+ QUERY PLAN
+-------------------------------------------------------------------------------------------------------------
+ Nested Loop
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8, b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Plan Node ID: 0
+ -> Index Scan using t1_pkey on "S 1"."T 1" a
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8
+ Index Cond: (a."C 1" = 47)
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft2 b
+ Output: b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = $1::integer))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = $1)
+(17 rows)
+
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM ft2 a, ft2 b
@@ -5116,6 +5328,373 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
Remote SQL: SELECT r5."C 1", r6.c1 FROM ("S 1"."T 1" r5 INNER JOIN "S 1"."T 3" r6 ON (((r5."C 1" = r6.c1)))) ORDER BY r5."C 1" ASC NULLS LAST
(13 rows)
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ERROR: EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ Limit
+ Plan Node ID: 0
+ -> Merge Semi Join
+ Merge Cond: (ft1.c1 = ft2_1.c1)
+ Plan Node ID: 1
+ -> Foreign Scan
+ Relations: (ft1) INNER JOIN (ft2)
+ Plan Node ID: 2
+ -> Foreign Scan
+ Relations: (ft2 ft2_1) INNER JOIN (ft4)
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Only Scan using t1_pkey on "T 1" r2
+ Plan Node ID 3:
+ Merge Join
+ Merge Cond: (r5."C 1" = r6.c1)
+ -> Index Only Scan using t1_pkey on "T 1" r5
+ -> Sort
+ Sort Key: r6.c1
+ -> Seq Scan on "T 3" r6
+(22 rows)
+
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Limit</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Semi</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>false</Inner-Unique> +
+ <Merge-Cond>(ft1.c1 = ft2_1.c1)</Merge-Cond> +
+ <Plan-Node-ID>1</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft1) INNER JOIN (ft2)</Relations> +
+ <Plan-Node-ID>2</Plan-Node-ID> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft2 ft2_1) INNER JOIN (ft4)</Relations> +
+ <Plan-Node-ID>3</Plan-Node-ID> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-2> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r2</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-2> +
+ <Plan-Node-ID-3> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Inner</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>true</Inner-Unique> +
+ <Merge-Cond>(r5."C 1" = r6.c1)</Merge-Cond> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r5</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Sort</Node-Type> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Sort-Key> +
+ <Item>r6.c1</Item> +
+ </Sort-Key> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Seq Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship>+
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>T 3</Relation-Name> +
+ <Alias>r6</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-3> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Limit", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Plan Node ID": 0, +
+ "Plans": [ +
+ { +
+ "Node Type": "Merge Join", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Semi", +
+ "Disabled": false, +
+ "Inner Unique": false, +
+ "Merge Cond": "(ft1.c1 = ft2_1.c1)", +
+ "Plan Node ID": 1, +
+ "Plans": [ +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft1) INNER JOIN (ft2)", +
+ "Plan Node ID": 2 +
+ }, +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft2 ft2_1) INNER JOIN (ft4)",+
+ "Plan Node ID": 3 +
+ } +
+ ] +
+ } +
+ ] +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 2": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Only Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r2", +
+ "Disabled": false +
+ } +
+ } +
+ ] +
+ ], +
+ "Plan Node ID 3": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Merge Join", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Inner", +
+ "Disabled": false, +
+ "Inner Unique": true, +
+ "Merge Cond": "(r5.\"C 1\" = r6.c1)", +
+ "Plans": [ +
+ { +
+ "Node Type": "Index Only Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r5", +
+ "Disabled": false +
+ }, +
+ { +
+ "Node Type": "Sort", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Sort Key": ["r6.c1"], +
+ "Plans": [ +
+ { +
+ "Node Type": "Seq Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "T 3", +
+ "Alias": "r6", +
+ "Disabled": false +
+ } +
+ ] +
+ } +
+ ] +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ - Plan: +
+ Node Type: "Limit" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Plan Node ID: 0 +
+ Plans: +
+ - Node Type: "Merge Join" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Semi" +
+ Disabled: false +
+ Inner Unique: false +
+ Merge Cond: "(ft1.c1 = ft2_1.c1)" +
+ Plan Node ID: 1 +
+ Plans: +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft1) INNER JOIN (ft2)" +
+ Plan Node ID: 2 +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft2 ft2_1) INNER JOIN (ft4)"+
+ Plan Node ID: 3 +
+ Remote Plans: +
+ Plan Node ID 2: +
+ - Plan: +
+ Node Type: "Index Only Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r2" +
+ Disabled: false +
+ Plan Node ID 3: +
+ - Plan: +
+ Node Type: "Merge Join" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Inner" +
+ Disabled: false +
+ Inner Unique: true +
+ Merge Cond: "(r5.\"C 1\" = r6.c1)" +
+ Plans: +
+ - Node Type: "Index Only Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r5" +
+ Disabled: false +
+ - Node Type: "Sort" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Sort Key: +
+ - "r6.c1" +
+ Plans: +
+ - Node Type: "Seq Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "T 3" +
+ Alias: "r6" +
+ Disabled: false
+(1 row)
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -6390,6 +6969,25 @@ SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
(3 rows)
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
+ QUERY PLAN
+---------------------------------------------------------------------------------------
+ Update on public.ft2
+ Plan Node ID: 0
+ -> Foreign Update on public.ft2
+ Remote SQL: UPDATE "S 1"."T 1" SET c2 = (c2 + 300) WHERE ((("C 1" % 10) = 3))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Update on "S 1"."T 1"
+ -> Seq Scan on "S 1"."T 1"
+ Output: (c2 + 300), ctid
+ Filter: (("T 1"."C 1" % 10) = 3)
+(12 rows)
+
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id;
@@ -12422,6 +13020,34 @@ SELECT * FROM insert_tbl ORDER BY a;
2505 | 505 | bar
(2 rows)
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+ QUERY PLAN
+-------------------------------------------------------------------------
+ Insert on public.insert_tbl
+ Remote SQL: INSERT INTO public.base_tbl4(a, b, c) VALUES ($1, $2, $3)
+ Batch Size: 1
+ Plan Node ID: 0
+ -> Append
+ Plan Node ID: 1
+ -> Seq Scan on public.local_tbl
+ Output: local_tbl.a, local_tbl.b, local_tbl.c
+ Plan Node ID: 2
+ -> Async Foreign Scan on public.remote_tbl
+ Output: remote_tbl.a, remote_tbl.b, remote_tbl.c
+ Remote SQL: SELECT a, b, c FROM public.base_tbl3
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Insert on public.base_tbl4
+ -> Result
+ Output: $1, $2, $3
+ Plan Node ID 3:
+ Seq Scan on public.base_tbl3
+ Output: a, b, c
+(22 rows)
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 79b16c3f318..43cf0196bbb 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -17,6 +17,7 @@
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#include "commands/defrem.h"
+#include "commands/explain.h"
#include "commands/extension.h"
#include "libpq/libpq-be.h"
#include "postgres_fdw.h"
@@ -40,6 +41,13 @@ typedef struct PgFdwOption
*/
static PgFdwOption *postgres_fdw_options;
+/*
+ * EXPLAIN hooks
+ */
+static explain_per_node_hook_type prev_explain_per_node_hook;
+static explain_per_plan_hook_type prev_explain_per_plan_hook;
+static explain_validate_options_hook_type prev_explain_validate_options_hook;
+
/*
* GUC parameters
*/
@@ -566,6 +574,61 @@ process_pgfdw_appname(const char *appname)
return buf.data;
}
+/*
+ * Get the PgFdwExplainState structure from an ExplainState; if there is
+ * none, create one, attach it to the ExplainState, and return it.
+ */
+static PgFdwExplainState *
+pgfdw_ensure_options(ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"));
+
+ if (pgfdw_explain_state == NULL)
+ {
+ pgfdw_explain_state = palloc0(sizeof(PgFdwExplainState));
+ SetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"), pgfdw_explain_state);
+ pgfdw_explain_state->all_remote_plans = NIL;
+ }
+
+ return pgfdw_explain_state;
+}
+
+/*
+ * Parse handler for EXPLAIN (REMOTE_PLANS).
+ */
+static void
+pgfdw_remote_plans_apply(ExplainState *es, DefElem *opt, ParseState *pstate)
+{
+ PgFdwExplainState *options = pgfdw_ensure_options(es);
+
+ options->remote_plans = defGetBoolean(opt);
+}
+
+static void
+postgresExplainValidateOptions(ExplainState *es, List *options, ParseState *pstate)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state = NULL;
+
+ foreach(lc, options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0)
+ {
+ if (defGetBoolean(opt) && es->analyze)
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together"));
+
+ pgfdw_explain_state = pgfdw_ensure_options(es);
+ pgfdw_explain_state->options = options;
+ }
+ }
+}
+
/*
* Module load callback
*/
@@ -592,4 +655,16 @@ _PG_init(void)
NULL);
MarkGUCPrefixReserved("postgres_fdw");
+
+ RegisterExtensionExplainOption("remote_plans", pgfdw_remote_plans_apply,
+ GUCCheckBooleanExplainOption);
+
+ /* per node EXPLAIN hook */
+ prev_explain_per_node_hook = explain_per_node_hook;
+ explain_per_node_hook = postgresExplainPerNode;
+ prev_explain_per_plan_hook = explain_per_plan_hook;
+ explain_per_plan_hook = postgresExplainPerPlan;
+ prev_explain_validate_options_hook = explain_validate_options_hook;
+ explain_validate_options_hook = postgresExplainValidateOptions;
+
}
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 6fa45773c30..af30222e60a 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -137,6 +137,19 @@ enum FdwDirectModifyPrivateIndex
FdwDirectModifyPrivateSetProcessed,
};
+/*
+ * Track the extension id in the backend.
+ */
+static int extension_id = -1;
+
+static int
+get_extension_id(void)
+{
+ if (extension_id == -1)
+ extension_id = GetExplainExtensionId("postgres_fdw");
+ return extension_id;
+}
+
/*
* Execution state of a foreign scan using postgres_fdw.
*/
@@ -3038,6 +3051,105 @@ postgresEndDirectModify(ForeignScanState *node)
/* MemoryContext will be deleted automatically. */
}
+static void
+postgresExplainStatement(int plan_node_id,
+ ExplainState *es,
+ PgFdwExplainState *pgfdw_explain_state,
+ PGconn *conn,
+ char *sql)
+{
+ PGresult *volatile res = NULL;
+ StringInfoData explain_sql;
+ int remote_version = PQserverVersion(conn);
+
+ /*
+ * GENERIC_PLAN required because deparsed SQL may contain $n placeholders;
+ * only available from PG 16.
+ */
+ if (remote_version < 160000)
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("EXPLAIN option REMOTE_PLANS requires a remote server version of 16 or later"),
+ errdetail("The remote server version is %d.", remote_version));
+
+ PG_TRY();
+ {
+ int numrows,
+ i;
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) palloc(sizeof(PgFdwExplainRemotePlans));
+ ListCell *lc;
+
+ initStringInfo(&explain_sql);
+ initStringInfo(&explain->explain_plan);
+
+ /* Forward user-specified options as-is; force GENERIC_PLAN on. */
+ appendStringInfoString(&explain_sql, "EXPLAIN (GENERIC_PLAN TRUE");
+
+ foreach(lc, pgfdw_explain_state->options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0 ||
+ strcmp(opt->defname, "generic_plan") == 0)
+ continue;
+
+ if (opt->arg == NULL)
+ appendStringInfo(&explain_sql, ", %s", opt->defname);
+ else
+ appendStringInfo(&explain_sql, ", %s %s", opt->defname,
+ defGetString(opt));
+ }
+
+ appendStringInfo(&explain_sql, ") %s", sql);
+
+ /* Run the query and collect the remote plan */
+ res = pgfdw_exec_query(conn, explain_sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, explain_sql.data);
+
+ numrows = PQntuples(res);
+
+ for (i = 0; i < numrows; i++)
+ appendStringInfo(&explain->explain_plan, "%s\n", PQgetvalue(res, i, 0));
+
+ if (explain->explain_plan.len > 0 && explain->explain_plan.data[explain->explain_plan.len - 1] == '\n')
+ explain->explain_plan.data[--explain->explain_plan.len] = '\0';
+
+ explain->plan_node_id = plan_node_id;
+ pgfdw_explain_state->all_remote_plans = lappend(pgfdw_explain_state->all_remote_plans, explain);
+ }
+ PG_FINALLY();
+ {
+ if (res)
+ PQclear(res);
+
+ if (explain_sql.data)
+ pfree(explain_sql.data);
+ }
+ PG_END_TRY();
+}
+
+/*
+ * explain_remote_query
+ * Helper function to get connection and execute remote EXPLAIN
+ */
+static void
+explain_remote_query(int plan_node_id, ExplainState *es,
+ PgFdwExplainState *pgfdw_explain_state,
+ Oid foreign_table_oid, char *sql)
+{
+ UserMapping *user;
+ PGconn *conn;
+ ForeignTable *table;
+
+ table = GetForeignTable(foreign_table_oid);
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+
+ postgresExplainStatement(plan_node_id, es, pgfdw_explain_state, conn, sql);
+ ReleaseConnection(conn);
+}
+
/*
* postgresExplainForeignScan
* Produce extra output for EXPLAIN of a ForeignScan on a foreign table
@@ -3047,6 +3159,12 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
List *fdw_private = plan->fdw_private;
+ PgFdwExplainState *pgfdw_explain_state;
+ char *sql;
+ Oid foreign_table_oid = InvalidOid;
+
+ if (node->ss.ss_currentRelation)
+ foreign_table_oid = RelationGetRelid(node->ss.ss_currentRelation);
/*
* Identify foreign scans that are really joins or upper relations. The
@@ -3108,6 +3226,13 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
Assert(rte->rtekind == RTE_RELATION);
/* This logic should agree with explain.c's ExplainTargetRel */
relname = get_rel_name(rte->relid);
+
+ /*
+ * Save first table OID for getting server connection
+ */
+ if (!OidIsValid(foreign_table_oid))
+ foreign_table_oid = rte->relid;
+
if (es->verbose)
{
char *namespace;
@@ -3133,16 +3258,25 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
ExplainPropertyText("Relations", relations.data, es);
}
+ sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
+
/*
* Add remote query, when VERBOSE option is specified.
*/
if (es->verbose)
- {
- char *sql;
-
- sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ /* If we don't have a foreign table oid by now, something went wrong */
+ Assert(foreign_table_oid);
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ es,
+ pgfdw_explain_state,
+ foreign_table_oid,
+ sql);
}
/*
@@ -3156,11 +3290,12 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
int subplan_index,
ExplainState *es)
{
+ char *sql = strVal(list_nth(fdw_private,
+ FdwModifyPrivateUpdateSql));
+ PgFdwExplainState *pgfdw_explain_state;
+
if (es->verbose)
{
- char *sql = strVal(list_nth(fdw_private,
- FdwModifyPrivateUpdateSql));
-
ExplainPropertyText("Remote SQL", sql, es);
/*
@@ -3170,6 +3305,14 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
if (rinfo->ri_BatchSize > 0)
ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
}
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(mtstate->ps.plan->plan_node_id,
+ es,
+ pgfdw_explain_state,
+ rinfo->ri_RelationDesc->rd_rel->oid,
+ sql);
}
/*
@@ -3182,13 +3325,22 @@ postgresExplainDirectModify(ForeignScanState *node, ExplainState *es)
{
List *fdw_private;
char *sql;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
+ sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
if (es->verbose)
- {
- fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
- sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ es,
+ pgfdw_explain_state,
+ RelationGetRelid(node->ss.ss_currentRelation),
+ sql);
}
/*
@@ -8835,3 +8987,95 @@ get_batch_size_option(Relation rel)
return batch_size;
}
+
+void
+postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship, const char *plan_name,
+ ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state == NULL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ ExplainPropertyInteger("Plan Node ID", NULL, planstate->plan->plan_node_id, es);
+}
+
+static void
+pgfdwFormatRemotePlan(PgFdwExplainRemotePlans *explain,
+ ExplainState *es,
+ int plan_node_id)
+{
+ char *token;
+ StringInfoData remote_plan_name;
+
+ initStringInfo(&remote_plan_name);
+ appendStringInfo(&remote_plan_name, "Plan Node ID %d", plan_node_id);
+
+ ExplainOpenGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Plan Node ID %d:", plan_node_id);
+ appendStringInfoString(es->str, "\n");
+ }
+
+ while ((token = strsep(&explain->explain_plan.data, "\n")) != NULL)
+ {
+ if (es->format == EXPLAIN_FORMAT_JSON ||
+ es->format == EXPLAIN_FORMAT_YAML)
+ appendStringInfoString(es->str, "\n");
+
+ appendStringInfoSpaces(es->str, (es->indent == 0) ? 2 : es->indent * 2);
+ appendStringInfoString(es->str, token);
+
+ if (es->format == EXPLAIN_FORMAT_XML ||
+ es->format == EXPLAIN_FORMAT_TEXT)
+ appendStringInfoString(es->str, "\n");
+ }
+
+ ExplainCloseGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+ pfree(remote_plan_name.data);
+}
+
+void
+postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state == NULL ||
+ pgfdw_explain_state->all_remote_plans == NIL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ ExplainOpenGroup("Remote Plans", "Remote Plans", true, es);
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Remote Plans:\n");
+ appendStringInfo(es->str, "-------------\n");
+ }
+
+ /* Process every remote plan captured */
+ foreach(lc, pgfdw_explain_state->all_remote_plans)
+ {
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) lfirst(lc);
+
+ pgfdwFormatRemotePlan(explain,
+ es,
+ explain->plan_node_id);
+ }
+
+ ExplainCloseGroup("Remote Plans", "Remote Plans", true, es);
+}
diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h
index a2bb1ff352c..6ede7a4e41f 100644
--- a/contrib/postgres_fdw/postgres_fdw.h
+++ b/contrib/postgres_fdw/postgres_fdw.h
@@ -13,6 +13,7 @@
#ifndef POSTGRES_FDW_H
#define POSTGRES_FDW_H
+#include "commands/explain_state.h"
#include "foreign/foreign.h"
#include "lib/stringinfo.h"
#include "libpq/libpq-be-fe.h"
@@ -151,6 +152,22 @@ typedef enum PgFdwSamplingMethod
ANALYZE_SAMPLE_BERNOULLI, /* TABLESAMPLE bernoulli */
} PgFdwSamplingMethod;
+typedef struct PgFdwExplainRemotePlans
+{
+ int plan_node_id;
+ StringInfoData explain_plan;
+
+} PgFdwExplainRemotePlans;
+
+typedef struct PgFdwExplainState
+{
+ List *all_remote_plans;
+
+ /* EXPLAIN options */
+ bool remote_plans;
+ List *options; /* raw user DefElem list, for forwarding */
+} PgFdwExplainState;
+
/* in postgres_fdw.c */
extern int set_transmission_modes(void);
extern void reset_transmission_modes(int nestlevel);
@@ -178,6 +195,16 @@ extern int ExtractConnectionOptions(List *defelems,
extern List *ExtractExtensionList(const char *extensionsString,
bool warnOnMissing);
extern char *process_pgfdw_appname(const char *appname);
+extern void postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship,
+ const char *plan_name,
+ ExplainState *es);
+extern void postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv);
extern char *pgfdw_application_name;
/* in deparse.c */
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 8162c5496bf..9e36697ade1 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -311,6 +311,11 @@ SELECT * FROM ft1 t1 WHERE t1.c3 = (SELECT MAX(c3) FROM ft2 t2) ORDER BY c1;
WITH t1 AS (SELECT * FROM ft1 WHERE c1 <= 10) SELECT t2.c1, t2.c2, t2.c3, t2.c4 FROM t1, ft2 t2 WHERE t1.c1 = t2.c1 ORDER BY t1.c1;
-- fixed values
SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -338,6 +343,12 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 left join ft1 t2 full join ft2
EXPLAIN (VERBOSE, COSTS OFF)
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
+
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+
RESET enable_hashjoin;
RESET enable_nestloop;
@@ -379,6 +390,11 @@ EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c8 = 'foo'; -- can't be
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
@@ -1527,6 +1543,33 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
ORDER BY ft1.c1 LIMIT 5;
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -1610,6 +1653,9 @@ DELETE FROM fpo_part_parent
FOR PORTION OF c4 FROM '2024-06-01' TO '2024-06-15' WHERE c2 = 1; -- okay
SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
@@ -4252,6 +4298,9 @@ INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_t
SELECT * FROM insert_tbl ORDER BY a;
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index b9e1b04463e..b457611db04 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -1197,6 +1197,93 @@ CREATE SUBSCRIPTION my_subscription SERVER subscription_server PUBLICATION testp
The query that is actually sent to the remote server for execution can
be examined using <command>EXPLAIN VERBOSE</command>.
</para>
+
+ <para>
+ In addition to the remote query itself, the plan that the remote server
+ chooses for that query can be examined with the
+ <literal>REMOTE_PLANS</literal> option of <command>EXPLAIN</command>.
+ For every foreign scan or foreign modification in the local plan,
+ <filename>postgres_fdw</filename> runs <command>EXPLAIN</command> on the
+ remote server for the corresponding remote query and prints the result in a
+ <literal>Remote Plans</literal> section, keyed by the plan node id of the
+ local node. For example:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS) SELECT * FROM foreign_tbl WHERE id = 42;
+ QUERY PLAN
+-----------------------------------------------------------
+ Foreign Scan on public.foreign_tbl
+ Output: id, val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = 42))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = 42)
+</programlisting>
+ When the local plan uses a parameterized foreign scan (for example, as
+ the inner side of a nested loop join), the remote SQL contains parameter
+ placeholders. The remote plan is a generic plan in this case:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS, COSTS OFF)
+ SELECT * FROM local_tbl a, foreign_tbl b WHERE a.id = 1 AND b.id = a.val;
+ QUERY PLAN
+-----------------------------------------------------------
+ Nested Loop
+ Output: a.id, a.val, b.id, b.val
+ -> Seq Scan on public.local_tbl a
+ Output: a.id, a.val
+ Filter: (a.id = 1)
+ -> Foreign Scan on public.foreign_tbl b
+ Output: b.id, b.val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = $1::integer))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = $1)
+</programlisting>
+ </para>
+
+ <para>
+ The <literal>REMOTE_PLANS</literal> option is registered when
+ <filename>postgres_fdw</filename> is loaded, so the module must be loaded
+ (for example with <command>CREATE EXTENSION postgres_fdw</command>) before
+ the option can be used. The following restrictions apply:
+ <itemizedlist>
+ <listitem>
+ <para>
+ It cannot be combined with <literal>ANALYZE</literal>; doing so raises an
+ error. The remote query is only planned, never executed, so the foreign
+ server is not affected and no remote rows are fetched.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ The remote server must be running <productname>PostgreSQL</productname>
+ 16 or later, because <literal>REMOTE_PLANS</literal> relies on the
+ <literal>GENERIC_PLAN</literal> option of <command>EXPLAIN</command>,
+ which was introduced in that release. As shown in the parameterized
+ example above, the plan shown by <literal>REMOTE_PLANS</literal> is
+ always a generic plan, which may differ from the plan the remote
+ server actually uses at execution time when specific parameter values
+ are available.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ All <command>EXPLAIN</command> options specified by the user (other than
+ <literal>REMOTE_PLANS</literal> itself and
+ <literal>GENERIC_PLAN</literal>) are forwarded to the remote server.
+ If the remote server is running an older version that does not recognize
+ a forwarded option, it will report an error.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
</sect2>
<sect2 id="postgres-fdw-remote-query-execution-environment">
diff --git a/src/include/commands/explain_state.h b/src/include/commands/explain_state.h
index 97bc7ed49f6..7e4dc6bca9c 100644
--- a/src/include/commands/explain_state.h
+++ b/src/include/commands/explain_state.h
@@ -45,6 +45,7 @@ typedef struct ExplainWorkersState
typedef struct ExplainState
{
StringInfo str; /* output buffer */
+
/* options */
bool verbose; /* be verbose */
bool analyze; /* print actual times */
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..9f5ee7c8bfb 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2305,6 +2305,8 @@ PgChecksumMode
PgFdwAnalyzeState
PgFdwConnState
PgFdwDirectModifyState
+PgFdwExplainRemotePlans
+PgFdwExplainState
PgFdwModifyState
PgFdwOption
PgFdwPathExtraData
--
2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-07-04 17:07 dinesh salve <cooltodinesh@gmail.com>
parent: Sami Imseih <samimseih@gmail.com>
0 siblings, 1 reply; 31+ messages in thread
From: dinesh salve @ 2026-07-04 17:07 UTC (permalink / raw)
To: Sami Imseih <samimseih@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
Just took a look and it looks great, thanks Sami for trimming down the
documentation and avoiding maintenance of version and their options. I have
moved the patch to the current commitfest PG20-2.
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-07-08 18:12 dinesh salve <cooltodinesh@gmail.com>
parent: dinesh salve <cooltodinesh@gmail.com>
0 siblings, 1 reply; 31+ messages in thread
From: dinesh salve @ 2026-07-08 18:12 UTC (permalink / raw)
To: Sami Imseih <samimseih@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
As discussed offline, also added a regression test that joins two foreign
tables living on different foreign servers (loopback and loopback2), which
exercises REMOTE_PLANS over multiple fdw connections.
>
Attachments:
v4-0001-postgres_fdw-show-remote-EXPLAIN-plans-via-REMOTE.patch (application/octet-stream, 70.9K) download
From ff4c2b1a4e5828c9dd89f7b7a6413fdafc530b8e Mon Sep 17 00:00:00 2001
From: Dinesh Salve <cooltodinesh@gmail.com>
Date: Wed, 8 Jul 2026 23:02:34 +0530
Subject: [PATCH v4] postgres_fdw: show remote EXPLAIN plans via REMOTE_PLANS
option
Add a REMOTE_PLANS option to EXPLAIN that, for every foreign scan or
foreign modification, runs EXPLAIN on the remote server for the
corresponding remote query and prints the result in a "Remote Plans"
section keyed by the local plan node id.
The remote query that postgres_fdw sends often contains $n parameter
placeholders (parameterized foreign scans and joins, subquery outputs,
and INSERT/UPDATE/DELETE), which a plain remote EXPLAIN cannot plan and
fails with "there is no parameter $1". REMOTE_PLANS therefore forces
GENERIC_PLAN on the remote EXPLAIN, which plans such statements without
bound values. GENERIC_PLAN is only available from PostgreSQL 16, so
REMOTE_PLANS errors out on older remote servers.
REMOTE_PLANS cannot be combined with ANALYZE. All user-specified EXPLAIN
options (other than REMOTE_PLANS and GENERIC_PLAN) are forwarded to the
remote server as-is. If the remote server does not recognize a forwarded
option, it reports an error.
The option is registered when postgres_fdw is loaded.
---
.../postgres_fdw/expected/postgres_fdw.out | 658 ++++++++++++++++++
contrib/postgres_fdw/option.c | 75 ++
contrib/postgres_fdw/postgres_fdw.c | 268 ++++++-
contrib/postgres_fdw/postgres_fdw.h | 27 +
contrib/postgres_fdw/sql/postgres_fdw.sql | 56 ++
doc/src/sgml/postgres-fdw.sgml | 87 +++
src/include/commands/explain_state.h | 1 +
src/tools/pgindent/typedefs.list | 2 +
8 files changed, 1162 insertions(+), 12 deletions(-)
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 5ebae1c..37709e9 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -471,6 +471,173 @@ SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
fixed |
(1 row)
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ - Plan: +
+ Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "ft1" +
+ Schema: "public" +
+ Alias: "t1" +
+ Disabled: false +
+ Output: +
+ - "c1" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Remote SQL: "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))"+
+ Plan Node ID: 0 +
+ Remote Plans: +
+ Plan Node ID 0: +
+ - Plan: +
+ Node Type: "Index Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Schema: "S 1" +
+ Alias: "T 1" +
+ Disabled: false +
+ Output: +
+ - "\"C 1\"" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Index Cond: "(\"T 1\".\"C 1\" = 101)"
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>ft1</Relation-Name> +
+ <Schema>public</Schema> +
+ <Alias>t1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>c1</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Remote-SQL>SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))</Remote-SQL>+
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-0> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Schema>S 1</Schema> +
+ <Alias>T 1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>"C 1"</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Index-Cond>("T 1"."C 1" = 101)</Index-Cond> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-0> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "ft1", +
+ "Schema": "public", +
+ "Alias": "t1", +
+ "Disabled": false, +
+ "Output": ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Remote SQL": "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))",+
+ "Plan Node ID": 0 +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 0": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Schema": "S 1", +
+ "Alias": "T 1", +
+ "Disabled": false, +
+ "Output": ["\"C 1\"", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Index Cond": "(\"T 1\".\"C 1\" = 101)" +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = 101)
+(10 rows)
+
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -646,6 +813,57 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2
110 | 110 | 110
(10 rows)
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------------------------------------
+ Foreign Scan
+ Output: t1.c1, t2.c1
+ Relations: (public.ft1 t1) INNER JOIN (public.ft2 t2)
+ Remote SQL: SELECT r1."C 1", r2."C 1" FROM ("S 1"."T 1" r1 INNER JOIN "S 1"."T 1" r2 ON (((r2."C 1" = r1."C 1")) AND ((r1.c2 = 10))))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Seq Scan on "S 1"."T 1" r2
+ Output: r2."C 1", r2."C 1"
+ Filter: (r2.c2 = 10)
+(11 rows)
+
+-- Tables on multiple foreign connections: ft5 lives on server loopback and
+-- ft6 on server loopback2, so the join cannot be pushed down as a single
+-- foreign join. Each side is scanned over its own connection, so REMOTE_PLANS
+-- must collect and print one remote plan per connection.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) WHERE t1.c1 = 10;
+ QUERY PLAN
+------------------------------------------------------------------
+ Nested Loop
+ Disabled: true
+ Output: t1.c1, t2.c1
+ Plan Node ID: 0
+ -> Foreign Scan on public.ft5 t1
+ Output: t1.c1, t1.c2, t1.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 4" WHERE ((c1 = 10))
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft6 t2
+ Output: t2.c1, t2.c2, t2.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 4" WHERE ((c1 = 10))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Seq Scan on "S 1"."T 4"
+ Output: c1
+ Filter: ("T 4".c1 = 10)
+ Plan Node ID 2:
+ Seq Scan on "S 1"."T 4"
+ Output: c1
+ Filter: ("T 4".c1 = 10)
+(22 rows)
+
RESET enable_hashjoin;
RESET enable_nestloop;
-- Test executing assertion in estimate_path_cost_size() that makes sure that
@@ -790,6 +1008,32 @@ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
47 | 7 | 00047 | Tue Feb 17 00:00:00 1970 PST | Tue Feb 17 00:00:00 1970 | 7 | 7 | foo | 7 | 7 | 00007 | Thu Jan 08 00:00:00 1970 PST | Thu Jan 08 00:00:00 1970 | 7 | 7 | foo
(1 row)
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+ QUERY PLAN
+-------------------------------------------------------------------------------------------------------------
+ Nested Loop
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8, b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Plan Node ID: 0
+ -> Index Scan using t1_pkey on "S 1"."T 1" a
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8
+ Index Cond: (a."C 1" = 47)
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft2 b
+ Output: b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = $1::integer))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = $1)
+(17 rows)
+
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM ft2 a, ft2 b
@@ -5116,6 +5360,373 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
Remote SQL: SELECT r5."C 1", r6.c1 FROM ("S 1"."T 1" r5 INNER JOIN "S 1"."T 3" r6 ON (((r5."C 1" = r6.c1)))) ORDER BY r5."C 1" ASC NULLS LAST
(13 rows)
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ERROR: EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ Limit
+ Plan Node ID: 0
+ -> Merge Semi Join
+ Merge Cond: (ft1.c1 = ft2_1.c1)
+ Plan Node ID: 1
+ -> Foreign Scan
+ Relations: (ft1) INNER JOIN (ft2)
+ Plan Node ID: 2
+ -> Foreign Scan
+ Relations: (ft2 ft2_1) INNER JOIN (ft4)
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Only Scan using t1_pkey on "T 1" r2
+ Plan Node ID 3:
+ Merge Join
+ Merge Cond: (r5."C 1" = r6.c1)
+ -> Index Only Scan using t1_pkey on "T 1" r5
+ -> Sort
+ Sort Key: r6.c1
+ -> Seq Scan on "T 3" r6
+(22 rows)
+
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Limit</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Semi</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>false</Inner-Unique> +
+ <Merge-Cond>(ft1.c1 = ft2_1.c1)</Merge-Cond> +
+ <Plan-Node-ID>1</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft1) INNER JOIN (ft2)</Relations> +
+ <Plan-Node-ID>2</Plan-Node-ID> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft2 ft2_1) INNER JOIN (ft4)</Relations> +
+ <Plan-Node-ID>3</Plan-Node-ID> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-2> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r2</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-2> +
+ <Plan-Node-ID-3> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Inner</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>true</Inner-Unique> +
+ <Merge-Cond>(r5."C 1" = r6.c1)</Merge-Cond> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r5</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Sort</Node-Type> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Sort-Key> +
+ <Item>r6.c1</Item> +
+ </Sort-Key> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Seq Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship>+
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>T 3</Relation-Name> +
+ <Alias>r6</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-3> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Limit", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Plan Node ID": 0, +
+ "Plans": [ +
+ { +
+ "Node Type": "Merge Join", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Semi", +
+ "Disabled": false, +
+ "Inner Unique": false, +
+ "Merge Cond": "(ft1.c1 = ft2_1.c1)", +
+ "Plan Node ID": 1, +
+ "Plans": [ +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft1) INNER JOIN (ft2)", +
+ "Plan Node ID": 2 +
+ }, +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft2 ft2_1) INNER JOIN (ft4)",+
+ "Plan Node ID": 3 +
+ } +
+ ] +
+ } +
+ ] +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 2": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Only Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r2", +
+ "Disabled": false +
+ } +
+ } +
+ ] +
+ ], +
+ "Plan Node ID 3": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Merge Join", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Inner", +
+ "Disabled": false, +
+ "Inner Unique": true, +
+ "Merge Cond": "(r5.\"C 1\" = r6.c1)", +
+ "Plans": [ +
+ { +
+ "Node Type": "Index Only Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r5", +
+ "Disabled": false +
+ }, +
+ { +
+ "Node Type": "Sort", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Sort Key": ["r6.c1"], +
+ "Plans": [ +
+ { +
+ "Node Type": "Seq Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "T 3", +
+ "Alias": "r6", +
+ "Disabled": false +
+ } +
+ ] +
+ } +
+ ] +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ - Plan: +
+ Node Type: "Limit" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Plan Node ID: 0 +
+ Plans: +
+ - Node Type: "Merge Join" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Semi" +
+ Disabled: false +
+ Inner Unique: false +
+ Merge Cond: "(ft1.c1 = ft2_1.c1)" +
+ Plan Node ID: 1 +
+ Plans: +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft1) INNER JOIN (ft2)" +
+ Plan Node ID: 2 +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft2 ft2_1) INNER JOIN (ft4)"+
+ Plan Node ID: 3 +
+ Remote Plans: +
+ Plan Node ID 2: +
+ - Plan: +
+ Node Type: "Index Only Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r2" +
+ Disabled: false +
+ Plan Node ID 3: +
+ - Plan: +
+ Node Type: "Merge Join" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Inner" +
+ Disabled: false +
+ Inner Unique: true +
+ Merge Cond: "(r5.\"C 1\" = r6.c1)" +
+ Plans: +
+ - Node Type: "Index Only Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r5" +
+ Disabled: false +
+ - Node Type: "Sort" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Sort Key: +
+ - "r6.c1" +
+ Plans: +
+ - Node Type: "Seq Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "T 3" +
+ Alias: "r6" +
+ Disabled: false
+(1 row)
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -6390,6 +7001,25 @@ SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
(3 rows)
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
+ QUERY PLAN
+---------------------------------------------------------------------------------------
+ Update on public.ft2
+ Plan Node ID: 0
+ -> Foreign Update on public.ft2
+ Remote SQL: UPDATE "S 1"."T 1" SET c2 = (c2 + 300) WHERE ((("C 1" % 10) = 3))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Update on "S 1"."T 1"
+ -> Seq Scan on "S 1"."T 1"
+ Output: (c2 + 300), ctid
+ Filter: (("T 1"."C 1" % 10) = 3)
+(12 rows)
+
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id;
@@ -12422,6 +13052,34 @@ SELECT * FROM insert_tbl ORDER BY a;
2505 | 505 | bar
(2 rows)
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+ QUERY PLAN
+-------------------------------------------------------------------------
+ Insert on public.insert_tbl
+ Remote SQL: INSERT INTO public.base_tbl4(a, b, c) VALUES ($1, $2, $3)
+ Batch Size: 1
+ Plan Node ID: 0
+ -> Append
+ Plan Node ID: 1
+ -> Seq Scan on public.local_tbl
+ Output: local_tbl.a, local_tbl.b, local_tbl.c
+ Plan Node ID: 2
+ -> Async Foreign Scan on public.remote_tbl
+ Output: remote_tbl.a, remote_tbl.b, remote_tbl.c
+ Remote SQL: SELECT a, b, c FROM public.base_tbl3
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Insert on public.base_tbl4
+ -> Result
+ Output: $1, $2, $3
+ Plan Node ID 3:
+ Seq Scan on public.base_tbl3
+ Output: a, b, c
+(22 rows)
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 79b16c3..43cf019 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -17,6 +17,7 @@
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#include "commands/defrem.h"
+#include "commands/explain.h"
#include "commands/extension.h"
#include "libpq/libpq-be.h"
#include "postgres_fdw.h"
@@ -40,6 +41,13 @@ typedef struct PgFdwOption
*/
static PgFdwOption *postgres_fdw_options;
+/*
+ * EXPLAIN hooks
+ */
+static explain_per_node_hook_type prev_explain_per_node_hook;
+static explain_per_plan_hook_type prev_explain_per_plan_hook;
+static explain_validate_options_hook_type prev_explain_validate_options_hook;
+
/*
* GUC parameters
*/
@@ -566,6 +574,61 @@ process_pgfdw_appname(const char *appname)
return buf.data;
}
+/*
+ * Get the PgFdwExplainState structure from an ExplainState; if there is
+ * none, create one, attach it to the ExplainState, and return it.
+ */
+static PgFdwExplainState *
+pgfdw_ensure_options(ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"));
+
+ if (pgfdw_explain_state == NULL)
+ {
+ pgfdw_explain_state = palloc0(sizeof(PgFdwExplainState));
+ SetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"), pgfdw_explain_state);
+ pgfdw_explain_state->all_remote_plans = NIL;
+ }
+
+ return pgfdw_explain_state;
+}
+
+/*
+ * Parse handler for EXPLAIN (REMOTE_PLANS).
+ */
+static void
+pgfdw_remote_plans_apply(ExplainState *es, DefElem *opt, ParseState *pstate)
+{
+ PgFdwExplainState *options = pgfdw_ensure_options(es);
+
+ options->remote_plans = defGetBoolean(opt);
+}
+
+static void
+postgresExplainValidateOptions(ExplainState *es, List *options, ParseState *pstate)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state = NULL;
+
+ foreach(lc, options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0)
+ {
+ if (defGetBoolean(opt) && es->analyze)
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together"));
+
+ pgfdw_explain_state = pgfdw_ensure_options(es);
+ pgfdw_explain_state->options = options;
+ }
+ }
+}
+
/*
* Module load callback
*/
@@ -592,4 +655,16 @@ _PG_init(void)
NULL);
MarkGUCPrefixReserved("postgres_fdw");
+
+ RegisterExtensionExplainOption("remote_plans", pgfdw_remote_plans_apply,
+ GUCCheckBooleanExplainOption);
+
+ /* per node EXPLAIN hook */
+ prev_explain_per_node_hook = explain_per_node_hook;
+ explain_per_node_hook = postgresExplainPerNode;
+ prev_explain_per_plan_hook = explain_per_plan_hook;
+ explain_per_plan_hook = postgresExplainPerPlan;
+ prev_explain_validate_options_hook = explain_validate_options_hook;
+ explain_validate_options_hook = postgresExplainValidateOptions;
+
}
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 0ea72a6..ff8c76e 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -139,6 +139,19 @@ enum FdwDirectModifyPrivateIndex
FdwDirectModifyPrivateSetProcessed,
};
+/*
+ * Track the extension id in the backend.
+ */
+static int extension_id = -1;
+
+static int
+get_extension_id(void)
+{
+ if (extension_id == -1)
+ extension_id = GetExplainExtensionId("postgres_fdw");
+ return extension_id;
+}
+
/*
* Execution state of a foreign scan using postgres_fdw.
*/
@@ -3042,6 +3055,105 @@ postgresEndDirectModify(ForeignScanState *node)
/* MemoryContext will be deleted automatically. */
}
+static void
+postgresExplainStatement(int plan_node_id,
+ ExplainState *es,
+ PgFdwExplainState *pgfdw_explain_state,
+ PGconn *conn,
+ char *sql)
+{
+ PGresult *volatile res = NULL;
+ StringInfoData explain_sql;
+ int remote_version = PQserverVersion(conn);
+
+ /*
+ * GENERIC_PLAN required because deparsed SQL may contain $n placeholders;
+ * only available from PG 16.
+ */
+ if (remote_version < 160000)
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("EXPLAIN option REMOTE_PLANS requires a remote server version of 16 or later"),
+ errdetail("The remote server version is %d.", remote_version));
+
+ PG_TRY();
+ {
+ int numrows,
+ i;
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) palloc(sizeof(PgFdwExplainRemotePlans));
+ ListCell *lc;
+
+ initStringInfo(&explain_sql);
+ initStringInfo(&explain->explain_plan);
+
+ /* Forward user-specified options as-is; force GENERIC_PLAN on. */
+ appendStringInfoString(&explain_sql, "EXPLAIN (GENERIC_PLAN TRUE");
+
+ foreach(lc, pgfdw_explain_state->options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0 ||
+ strcmp(opt->defname, "generic_plan") == 0)
+ continue;
+
+ if (opt->arg == NULL)
+ appendStringInfo(&explain_sql, ", %s", opt->defname);
+ else
+ appendStringInfo(&explain_sql, ", %s %s", opt->defname,
+ defGetString(opt));
+ }
+
+ appendStringInfo(&explain_sql, ") %s", sql);
+
+ /* Run the query and collect the remote plan */
+ res = pgfdw_exec_query(conn, explain_sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, explain_sql.data);
+
+ numrows = PQntuples(res);
+
+ for (i = 0; i < numrows; i++)
+ appendStringInfo(&explain->explain_plan, "%s\n", PQgetvalue(res, i, 0));
+
+ if (explain->explain_plan.len > 0 && explain->explain_plan.data[explain->explain_plan.len - 1] == '\n')
+ explain->explain_plan.data[--explain->explain_plan.len] = '\0';
+
+ explain->plan_node_id = plan_node_id;
+ pgfdw_explain_state->all_remote_plans = lappend(pgfdw_explain_state->all_remote_plans, explain);
+ }
+ PG_FINALLY();
+ {
+ if (res)
+ PQclear(res);
+
+ if (explain_sql.data)
+ pfree(explain_sql.data);
+ }
+ PG_END_TRY();
+}
+
+/*
+ * explain_remote_query
+ * Helper function to get connection and execute remote EXPLAIN
+ */
+static void
+explain_remote_query(int plan_node_id, ExplainState *es,
+ PgFdwExplainState *pgfdw_explain_state,
+ Oid foreign_table_oid, char *sql)
+{
+ UserMapping *user;
+ PGconn *conn;
+ ForeignTable *table;
+
+ table = GetForeignTable(foreign_table_oid);
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+
+ postgresExplainStatement(plan_node_id, es, pgfdw_explain_state, conn, sql);
+ ReleaseConnection(conn);
+}
+
/*
* postgresExplainForeignScan
* Produce extra output for EXPLAIN of a ForeignScan on a foreign table
@@ -3051,6 +3163,12 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
List *fdw_private = plan->fdw_private;
+ PgFdwExplainState *pgfdw_explain_state;
+ char *sql;
+ Oid foreign_table_oid = InvalidOid;
+
+ if (node->ss.ss_currentRelation)
+ foreign_table_oid = RelationGetRelid(node->ss.ss_currentRelation);
/*
* Identify foreign scans that are really joins or upper relations. The
@@ -3112,6 +3230,13 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
Assert(rte->rtekind == RTE_RELATION);
/* This logic should agree with explain.c's ExplainTargetRel */
relname = get_rel_name(rte->relid);
+
+ /*
+ * Save first table OID for getting server connection
+ */
+ if (!OidIsValid(foreign_table_oid))
+ foreign_table_oid = rte->relid;
+
if (es->verbose)
{
char *namespace;
@@ -3137,16 +3262,25 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
ExplainPropertyText("Relations", relations.data, es);
}
+ sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
+
/*
* Add remote query, when VERBOSE option is specified.
*/
if (es->verbose)
- {
- char *sql;
-
- sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ /* If we don't have a foreign table oid by now, something went wrong */
+ Assert(foreign_table_oid);
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ es,
+ pgfdw_explain_state,
+ foreign_table_oid,
+ sql);
}
/*
@@ -3160,11 +3294,12 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
int subplan_index,
ExplainState *es)
{
+ char *sql = strVal(list_nth(fdw_private,
+ FdwModifyPrivateUpdateSql));
+ PgFdwExplainState *pgfdw_explain_state;
+
if (es->verbose)
{
- char *sql = strVal(list_nth(fdw_private,
- FdwModifyPrivateUpdateSql));
-
ExplainPropertyText("Remote SQL", sql, es);
/*
@@ -3174,6 +3309,14 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
if (rinfo->ri_BatchSize > 0)
ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
}
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(mtstate->ps.plan->plan_node_id,
+ es,
+ pgfdw_explain_state,
+ rinfo->ri_RelationDesc->rd_rel->oid,
+ sql);
}
/*
@@ -3186,13 +3329,22 @@ postgresExplainDirectModify(ForeignScanState *node, ExplainState *es)
{
List *fdw_private;
char *sql;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
+ sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
if (es->verbose)
- {
- fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
- sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ es,
+ pgfdw_explain_state,
+ RelationGetRelid(node->ss.ss_currentRelation),
+ sql);
}
/*
@@ -8851,3 +9003,95 @@ get_batch_size_option(Relation rel)
return batch_size;
}
+
+void
+postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship, const char *plan_name,
+ ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state == NULL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ ExplainPropertyInteger("Plan Node ID", NULL, planstate->plan->plan_node_id, es);
+}
+
+static void
+pgfdwFormatRemotePlan(PgFdwExplainRemotePlans *explain,
+ ExplainState *es,
+ int plan_node_id)
+{
+ char *token;
+ StringInfoData remote_plan_name;
+
+ initStringInfo(&remote_plan_name);
+ appendStringInfo(&remote_plan_name, "Plan Node ID %d", plan_node_id);
+
+ ExplainOpenGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Plan Node ID %d:", plan_node_id);
+ appendStringInfoString(es->str, "\n");
+ }
+
+ while ((token = strsep(&explain->explain_plan.data, "\n")) != NULL)
+ {
+ if (es->format == EXPLAIN_FORMAT_JSON ||
+ es->format == EXPLAIN_FORMAT_YAML)
+ appendStringInfoString(es->str, "\n");
+
+ appendStringInfoSpaces(es->str, (es->indent == 0) ? 2 : es->indent * 2);
+ appendStringInfoString(es->str, token);
+
+ if (es->format == EXPLAIN_FORMAT_XML ||
+ es->format == EXPLAIN_FORMAT_TEXT)
+ appendStringInfoString(es->str, "\n");
+ }
+
+ ExplainCloseGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+ pfree(remote_plan_name.data);
+}
+
+void
+postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state == NULL ||
+ pgfdw_explain_state->all_remote_plans == NIL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ ExplainOpenGroup("Remote Plans", "Remote Plans", true, es);
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Remote Plans:\n");
+ appendStringInfo(es->str, "-------------\n");
+ }
+
+ /* Process every remote plan captured */
+ foreach(lc, pgfdw_explain_state->all_remote_plans)
+ {
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) lfirst(lc);
+
+ pgfdwFormatRemotePlan(explain,
+ es,
+ explain->plan_node_id);
+ }
+
+ ExplainCloseGroup("Remote Plans", "Remote Plans", true, es);
+}
diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h
index a2bb1ff..6ede7a4 100644
--- a/contrib/postgres_fdw/postgres_fdw.h
+++ b/contrib/postgres_fdw/postgres_fdw.h
@@ -13,6 +13,7 @@
#ifndef POSTGRES_FDW_H
#define POSTGRES_FDW_H
+#include "commands/explain_state.h"
#include "foreign/foreign.h"
#include "lib/stringinfo.h"
#include "libpq/libpq-be-fe.h"
@@ -151,6 +152,22 @@ typedef enum PgFdwSamplingMethod
ANALYZE_SAMPLE_BERNOULLI, /* TABLESAMPLE bernoulli */
} PgFdwSamplingMethod;
+typedef struct PgFdwExplainRemotePlans
+{
+ int plan_node_id;
+ StringInfoData explain_plan;
+
+} PgFdwExplainRemotePlans;
+
+typedef struct PgFdwExplainState
+{
+ List *all_remote_plans;
+
+ /* EXPLAIN options */
+ bool remote_plans;
+ List *options; /* raw user DefElem list, for forwarding */
+} PgFdwExplainState;
+
/* in postgres_fdw.c */
extern int set_transmission_modes(void);
extern void reset_transmission_modes(int nestlevel);
@@ -178,6 +195,16 @@ extern int ExtractConnectionOptions(List *defelems,
extern List *ExtractExtensionList(const char *extensionsString,
bool warnOnMissing);
extern char *process_pgfdw_appname(const char *appname);
+extern void postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship,
+ const char *plan_name,
+ ExplainState *es);
+extern void postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv);
extern char *pgfdw_application_name;
/* in deparse.c */
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index e868da0..198b894 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -311,6 +311,11 @@ SELECT * FROM ft1 t1 WHERE t1.c3 = (SELECT MAX(c3) FROM ft2 t2) ORDER BY c1;
WITH t1 AS (SELECT * FROM ft1 WHERE c1 <= 10) SELECT t2.c1, t2.c2, t2.c3, t2.c4 FROM t1, ft2 t2 WHERE t1.c1 = t2.c1 ORDER BY t1.c1;
-- fixed values
SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -338,6 +343,19 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 left join ft1 t2 full join ft2
EXPLAIN (VERBOSE, COSTS OFF)
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
+
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+
+-- Tables on multiple foreign connections: ft5 lives on server loopback and
+-- ft6 on server loopback2, so the join cannot be pushed down as a single
+-- foreign join. Each side is scanned over its own connection, so REMOTE_PLANS
+-- must collect and print one remote plan per connection.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) WHERE t1.c1 = 10;
+
RESET enable_hashjoin;
RESET enable_nestloop;
@@ -379,6 +397,11 @@ EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c8 = 'foo'; -- can't be
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
@@ -1527,6 +1550,33 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
ORDER BY ft1.c1 LIMIT 5;
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -1610,6 +1660,9 @@ DELETE FROM fpo_part_parent
FOR PORTION OF c4 FROM '2024-06-01' TO '2024-06-15' WHERE c2 = 1; -- okay
SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
@@ -4252,6 +4305,9 @@ INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_t
SELECT * FROM insert_tbl ORDER BY a;
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index b9e1b04..b457611 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -1197,6 +1197,93 @@ CREATE SUBSCRIPTION my_subscription SERVER subscription_server PUBLICATION testp
The query that is actually sent to the remote server for execution can
be examined using <command>EXPLAIN VERBOSE</command>.
</para>
+
+ <para>
+ In addition to the remote query itself, the plan that the remote server
+ chooses for that query can be examined with the
+ <literal>REMOTE_PLANS</literal> option of <command>EXPLAIN</command>.
+ For every foreign scan or foreign modification in the local plan,
+ <filename>postgres_fdw</filename> runs <command>EXPLAIN</command> on the
+ remote server for the corresponding remote query and prints the result in a
+ <literal>Remote Plans</literal> section, keyed by the plan node id of the
+ local node. For example:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS) SELECT * FROM foreign_tbl WHERE id = 42;
+ QUERY PLAN
+-----------------------------------------------------------
+ Foreign Scan on public.foreign_tbl
+ Output: id, val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = 42))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = 42)
+</programlisting>
+ When the local plan uses a parameterized foreign scan (for example, as
+ the inner side of a nested loop join), the remote SQL contains parameter
+ placeholders. The remote plan is a generic plan in this case:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS, COSTS OFF)
+ SELECT * FROM local_tbl a, foreign_tbl b WHERE a.id = 1 AND b.id = a.val;
+ QUERY PLAN
+-----------------------------------------------------------
+ Nested Loop
+ Output: a.id, a.val, b.id, b.val
+ -> Seq Scan on public.local_tbl a
+ Output: a.id, a.val
+ Filter: (a.id = 1)
+ -> Foreign Scan on public.foreign_tbl b
+ Output: b.id, b.val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = $1::integer))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = $1)
+</programlisting>
+ </para>
+
+ <para>
+ The <literal>REMOTE_PLANS</literal> option is registered when
+ <filename>postgres_fdw</filename> is loaded, so the module must be loaded
+ (for example with <command>CREATE EXTENSION postgres_fdw</command>) before
+ the option can be used. The following restrictions apply:
+ <itemizedlist>
+ <listitem>
+ <para>
+ It cannot be combined with <literal>ANALYZE</literal>; doing so raises an
+ error. The remote query is only planned, never executed, so the foreign
+ server is not affected and no remote rows are fetched.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ The remote server must be running <productname>PostgreSQL</productname>
+ 16 or later, because <literal>REMOTE_PLANS</literal> relies on the
+ <literal>GENERIC_PLAN</literal> option of <command>EXPLAIN</command>,
+ which was introduced in that release. As shown in the parameterized
+ example above, the plan shown by <literal>REMOTE_PLANS</literal> is
+ always a generic plan, which may differ from the plan the remote
+ server actually uses at execution time when specific parameter values
+ are available.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ All <command>EXPLAIN</command> options specified by the user (other than
+ <literal>REMOTE_PLANS</literal> itself and
+ <literal>GENERIC_PLAN</literal>) are forwarded to the remote server.
+ If the remote server is running an older version that does not recognize
+ a forwarded option, it will report an error.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
</sect2>
<sect2 id="postgres-fdw-remote-query-execution-environment">
diff --git a/src/include/commands/explain_state.h b/src/include/commands/explain_state.h
index 97bc7ed..7e4dc6b 100644
--- a/src/include/commands/explain_state.h
+++ b/src/include/commands/explain_state.h
@@ -45,6 +45,7 @@ typedef struct ExplainWorkersState
typedef struct ExplainState
{
StringInfo str; /* output buffer */
+
/* options */
bool verbose; /* be verbose */
bool analyze; /* print actual times */
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index ffb413a..6f77701 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2305,6 +2305,8 @@ PgChecksumMode
PgFdwAnalyzeState
PgFdwConnState
PgFdwDirectModifyState
+PgFdwExplainRemotePlans
+PgFdwExplainState
PgFdwModifyState
PgFdwOption
PgFdwPathExtraData
base-commit: ad7877b00a4232d71bb4cb63c22f9d748e65e3f7
--
2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-07-24 03:05 Yilin Zhang <jiezhilove@126.com>
parent: dinesh salve <cooltodinesh@gmail.com>
0 siblings, 2 replies; 31+ messages in thread
From: Yilin Zhang @ 2026-07-24 03:05 UTC (permalink / raw)
To: dinesh salve <cooltodinesh@gmail.com>; +Cc: Sami Imseih <samimseih@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, "Jeff Davis" <pgsql@j-davis.com>
At 2026-07-09 02:12:36, "dinesh salve" <cooltodinesh@gmail.com> wrote:
> As discussed offline, also added a regression test that joins two foreign
> tables living on different foreign servers (loopback and loopback2), which
> exercises REMOTE_PLANS over multiple fdw connections.
Hi,
Few comments for v4-0001.
1.
inline patch 1: src/include/commands/explain_state.h (+1/-0 lines) download inline-1.patch
--- a/src/include/commands/explain_state.h
+++ b/src/include/commands/explain_state.h
@@ -45,6 +45,7 @@ typedef struct ExplainWorkersState
typedef struct ExplainState
{
StringInfo str; /* output buffer */
+
/* options */
bool verbose; /* be verbose */
bool analyze; /* print actual times */
Is this blank line in explain_state.h necessary?
2.
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 0ea72a6..ff8c76e 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
......
+static void
+postgresExplainStatement(int plan_node_id,
+ ExplainState *es,
+ PgFdwExplainState *pgfdw_explain_state,
+ PGconn *conn,
+ char *sql)
+{
+ PGresult *volatile res = NULL;
+ StringInfoData explain_sql;
+ int remote_version = PQserverVersion(conn);
+
+ /*
+ * GENERIC_PLAN required because deparsed SQL may contain $n placeholders;
+ * only available from PG 16.
+ */
+ if (remote_version < 160000)
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("EXPLAIN option REMOTE_PLANS requires a remote server version of 16 or later"),
+ errdetail("The remote server version is %d.", remote_version));
+
+ PG_TRY();
+ {
+ int numrows,
+ i;
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) palloc(sizeof(PgFdwExplainRemotePlans));
+ ListCell *lc;
+
+ initStringInfo(&explain_sql);
+ initStringInfo(&explain->explain_plan);
The StringInfoData explain_sql; declared here is uninitialized. While the risk is low, it could lead to subtle problems.
This pattern also does not align with existing usage of StringInfoData throughout the codebase.
I recommend initializing it before entering the PG_TRY block.
Best regards,
--
Yilin Zhang
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-07-27 16:04 Dinesh Salve <cooltodinesh@gmail.com>
parent: Yilin Zhang <jiezhilove@126.com>
1 sibling, 1 reply; 31+ messages in thread
From: Dinesh Salve @ 2026-07-27 16:04 UTC (permalink / raw)
To: Yilin Zhang <jiezhilove@126.com>; +Cc: Sami Imseih <samimseih@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
Thanks for feedback Yilin. I have removed that blank line, initializing
explain_sql before PG_TRY now and removed unused variables at a few places.
Attaching updated patch v5.
Regards,
Dinesh Salve
>
Attachments:
v5-0001-postgres_fdw-show-remote-EXPLAIN-plans-via-REMOTE.patch (application/octet-stream, 70.7K) download
From 64ffd6ce423dff3dd30042b40e4cc8e86ec7fccc Mon Sep 17 00:00:00 2001
From: Dinesh Salve <cooltodinesh@gmail.com>
Date: Mon, 27 Jul 2026 21:22:24 +0530
Subject: [PATCH v5] postgres_fdw: show remote EXPLAIN plans via REMOTE_PLANS
option
Add a REMOTE_PLANS option to EXPLAIN that, for every foreign scan or
foreign modification, runs EXPLAIN on the remote server for the
corresponding remote query and prints the result in a "Remote Plans"
section keyed by the local plan node id.
The remote query that postgres_fdw sends often contains $n parameter
placeholders (parameterized foreign scans and joins, subquery outputs,
and INSERT/UPDATE/DELETE), which a plain remote EXPLAIN cannot plan and
fails with "there is no parameter $1". REMOTE_PLANS therefore forces
GENERIC_PLAN on the remote EXPLAIN, which plans such statements without
bound values. GENERIC_PLAN is only available from PostgreSQL 16, so
REMOTE_PLANS errors out on older remote servers.
REMOTE_PLANS cannot be combined with ANALYZE. All user-specified EXPLAIN
options (other than REMOTE_PLANS and GENERIC_PLAN) are forwarded to the
remote server as-is. If the remote server does not recognize a forwarded
option, it reports an error.
The option is registered when postgres_fdw is loaded.
---
.../postgres_fdw/expected/postgres_fdw.out | 658 ++++++++++++++++++
contrib/postgres_fdw/option.c | 75 ++
contrib/postgres_fdw/postgres_fdw.c | 266 ++++++-
contrib/postgres_fdw/postgres_fdw.h | 27 +
contrib/postgres_fdw/sql/postgres_fdw.sql | 56 ++
doc/src/sgml/postgres-fdw.sgml | 87 +++
src/include/commands/explain_state.h | 1 +
src/tools/pgindent/typedefs.list | 2 +
8 files changed, 1160 insertions(+), 12 deletions(-)
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index d19121b..0109ed2 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -471,6 +471,173 @@ SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
fixed |
(1 row)
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ - Plan: +
+ Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "ft1" +
+ Schema: "public" +
+ Alias: "t1" +
+ Disabled: false +
+ Output: +
+ - "c1" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Remote SQL: "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))"+
+ Plan Node ID: 0 +
+ Remote Plans: +
+ Plan Node ID 0: +
+ - Plan: +
+ Node Type: "Index Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Schema: "S 1" +
+ Alias: "T 1" +
+ Disabled: false +
+ Output: +
+ - "\"C 1\"" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Index Cond: "(\"T 1\".\"C 1\" = 101)"
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>ft1</Relation-Name> +
+ <Schema>public</Schema> +
+ <Alias>t1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>c1</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Remote-SQL>SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))</Remote-SQL>+
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-0> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Schema>S 1</Schema> +
+ <Alias>T 1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>"C 1"</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Index-Cond>("T 1"."C 1" = 101)</Index-Cond> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-0> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "ft1", +
+ "Schema": "public", +
+ "Alias": "t1", +
+ "Disabled": false, +
+ "Output": ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Remote SQL": "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))",+
+ "Plan Node ID": 0 +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 0": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Schema": "S 1", +
+ "Alias": "T 1", +
+ "Disabled": false, +
+ "Output": ["\"C 1\"", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Index Cond": "(\"T 1\".\"C 1\" = 101)" +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = 101)
+(10 rows)
+
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -646,6 +813,57 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2
110 | 110 | 110
(10 rows)
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------------------------------------
+ Foreign Scan
+ Output: t1.c1, t2.c1
+ Relations: (public.ft1 t1) INNER JOIN (public.ft2 t2)
+ Remote SQL: SELECT r1."C 1", r2."C 1" FROM ("S 1"."T 1" r1 INNER JOIN "S 1"."T 1" r2 ON (((r2."C 1" = r1."C 1")) AND ((r1.c2 = 10))))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Seq Scan on "S 1"."T 1" r2
+ Output: r2."C 1", r2."C 1"
+ Filter: (r2.c2 = 10)
+(11 rows)
+
+-- Tables on multiple foreign connections: ft5 lives on server loopback and
+-- ft6 on server loopback2, so the join cannot be pushed down as a single
+-- foreign join. Each side is scanned over its own connection, so REMOTE_PLANS
+-- must collect and print one remote plan per connection.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) WHERE t1.c1 = 10;
+ QUERY PLAN
+------------------------------------------------------------------
+ Nested Loop
+ Disabled: true
+ Output: t1.c1, t2.c1
+ Plan Node ID: 0
+ -> Foreign Scan on public.ft5 t1
+ Output: t1.c1, t1.c2, t1.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 4" WHERE ((c1 = 10))
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft6 t2
+ Output: t2.c1, t2.c2, t2.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 4" WHERE ((c1 = 10))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Seq Scan on "S 1"."T 4"
+ Output: c1
+ Filter: ("T 4".c1 = 10)
+ Plan Node ID 2:
+ Seq Scan on "S 1"."T 4"
+ Output: c1
+ Filter: ("T 4".c1 = 10)
+(22 rows)
+
RESET enable_hashjoin;
RESET enable_nestloop;
-- Test executing assertion in estimate_path_cost_size() that makes sure that
@@ -790,6 +1008,32 @@ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
47 | 7 | 00047 | Tue Feb 17 00:00:00 1970 PST | Tue Feb 17 00:00:00 1970 | 7 | 7 | foo | 7 | 7 | 00007 | Thu Jan 08 00:00:00 1970 PST | Thu Jan 08 00:00:00 1970 | 7 | 7 | foo
(1 row)
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+ QUERY PLAN
+-------------------------------------------------------------------------------------------------------------
+ Nested Loop
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8, b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Plan Node ID: 0
+ -> Index Scan using t1_pkey on "S 1"."T 1" a
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8
+ Index Cond: (a."C 1" = 47)
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft2 b
+ Output: b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = $1::integer))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = $1)
+(17 rows)
+
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM ft2 a, ft2 b
@@ -5191,6 +5435,373 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
Remote SQL: SELECT r5."C 1", r6.c1 FROM ("S 1"."T 1" r5 INNER JOIN "S 1"."T 3" r6 ON (((r5."C 1" = r6.c1)))) ORDER BY r5."C 1" ASC NULLS LAST
(13 rows)
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ERROR: EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ Limit
+ Plan Node ID: 0
+ -> Merge Semi Join
+ Merge Cond: (ft1.c1 = ft2_1.c1)
+ Plan Node ID: 1
+ -> Foreign Scan
+ Relations: (ft1) INNER JOIN (ft2)
+ Plan Node ID: 2
+ -> Foreign Scan
+ Relations: (ft2 ft2_1) INNER JOIN (ft4)
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Only Scan using t1_pkey on "T 1" r2
+ Plan Node ID 3:
+ Merge Join
+ Merge Cond: (r5."C 1" = r6.c1)
+ -> Index Only Scan using t1_pkey on "T 1" r5
+ -> Sort
+ Sort Key: r6.c1
+ -> Seq Scan on "T 3" r6
+(22 rows)
+
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Limit</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Semi</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>false</Inner-Unique> +
+ <Merge-Cond>(ft1.c1 = ft2_1.c1)</Merge-Cond> +
+ <Plan-Node-ID>1</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft1) INNER JOIN (ft2)</Relations> +
+ <Plan-Node-ID>2</Plan-Node-ID> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft2 ft2_1) INNER JOIN (ft4)</Relations> +
+ <Plan-Node-ID>3</Plan-Node-ID> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-2> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r2</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-2> +
+ <Plan-Node-ID-3> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Inner</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>true</Inner-Unique> +
+ <Merge-Cond>(r5."C 1" = r6.c1)</Merge-Cond> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r5</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Sort</Node-Type> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Sort-Key> +
+ <Item>r6.c1</Item> +
+ </Sort-Key> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Seq Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship>+
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>T 3</Relation-Name> +
+ <Alias>r6</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-3> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Limit", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Plan Node ID": 0, +
+ "Plans": [ +
+ { +
+ "Node Type": "Merge Join", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Semi", +
+ "Disabled": false, +
+ "Inner Unique": false, +
+ "Merge Cond": "(ft1.c1 = ft2_1.c1)", +
+ "Plan Node ID": 1, +
+ "Plans": [ +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft1) INNER JOIN (ft2)", +
+ "Plan Node ID": 2 +
+ }, +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft2 ft2_1) INNER JOIN (ft4)",+
+ "Plan Node ID": 3 +
+ } +
+ ] +
+ } +
+ ] +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 2": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Only Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r2", +
+ "Disabled": false +
+ } +
+ } +
+ ] +
+ ], +
+ "Plan Node ID 3": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Merge Join", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Inner", +
+ "Disabled": false, +
+ "Inner Unique": true, +
+ "Merge Cond": "(r5.\"C 1\" = r6.c1)", +
+ "Plans": [ +
+ { +
+ "Node Type": "Index Only Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r5", +
+ "Disabled": false +
+ }, +
+ { +
+ "Node Type": "Sort", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Sort Key": ["r6.c1"], +
+ "Plans": [ +
+ { +
+ "Node Type": "Seq Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "T 3", +
+ "Alias": "r6", +
+ "Disabled": false +
+ } +
+ ] +
+ } +
+ ] +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ - Plan: +
+ Node Type: "Limit" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Plan Node ID: 0 +
+ Plans: +
+ - Node Type: "Merge Join" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Semi" +
+ Disabled: false +
+ Inner Unique: false +
+ Merge Cond: "(ft1.c1 = ft2_1.c1)" +
+ Plan Node ID: 1 +
+ Plans: +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft1) INNER JOIN (ft2)" +
+ Plan Node ID: 2 +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft2 ft2_1) INNER JOIN (ft4)"+
+ Plan Node ID: 3 +
+ Remote Plans: +
+ Plan Node ID 2: +
+ - Plan: +
+ Node Type: "Index Only Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r2" +
+ Disabled: false +
+ Plan Node ID 3: +
+ - Plan: +
+ Node Type: "Merge Join" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Inner" +
+ Disabled: false +
+ Inner Unique: true +
+ Merge Cond: "(r5.\"C 1\" = r6.c1)" +
+ Plans: +
+ - Node Type: "Index Only Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r5" +
+ Disabled: false +
+ - Node Type: "Sort" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Sort Key: +
+ - "r6.c1" +
+ Plans: +
+ - Node Type: "Seq Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "T 3" +
+ Alias: "r6" +
+ Disabled: false
+(1 row)
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -6465,6 +7076,25 @@ SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
(3 rows)
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
+ QUERY PLAN
+---------------------------------------------------------------------------------------
+ Update on public.ft2
+ Plan Node ID: 0
+ -> Foreign Update on public.ft2
+ Remote SQL: UPDATE "S 1"."T 1" SET c2 = (c2 + 300) WHERE ((("C 1" % 10) = 3))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Update on "S 1"."T 1"
+ -> Seq Scan on "S 1"."T 1"
+ Output: (c2 + 300), ctid
+ Filter: (("T 1"."C 1" % 10) = 3)
+(12 rows)
+
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id;
@@ -12497,6 +13127,34 @@ SELECT * FROM insert_tbl ORDER BY a;
2505 | 505 | bar
(2 rows)
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+ QUERY PLAN
+-------------------------------------------------------------------------
+ Insert on public.insert_tbl
+ Remote SQL: INSERT INTO public.base_tbl4(a, b, c) VALUES ($1, $2, $3)
+ Batch Size: 1
+ Plan Node ID: 0
+ -> Append
+ Plan Node ID: 1
+ -> Seq Scan on public.local_tbl
+ Output: local_tbl.a, local_tbl.b, local_tbl.c
+ Plan Node ID: 2
+ -> Async Foreign Scan on public.remote_tbl
+ Output: remote_tbl.a, remote_tbl.b, remote_tbl.c
+ Remote SQL: SELECT a, b, c FROM public.base_tbl3
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Insert on public.base_tbl4
+ -> Result
+ Output: $1, $2, $3
+ Plan Node ID 3:
+ Seq Scan on public.base_tbl3
+ Output: a, b, c
+(22 rows)
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 79b16c3..43cf019 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -17,6 +17,7 @@
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#include "commands/defrem.h"
+#include "commands/explain.h"
#include "commands/extension.h"
#include "libpq/libpq-be.h"
#include "postgres_fdw.h"
@@ -40,6 +41,13 @@ typedef struct PgFdwOption
*/
static PgFdwOption *postgres_fdw_options;
+/*
+ * EXPLAIN hooks
+ */
+static explain_per_node_hook_type prev_explain_per_node_hook;
+static explain_per_plan_hook_type prev_explain_per_plan_hook;
+static explain_validate_options_hook_type prev_explain_validate_options_hook;
+
/*
* GUC parameters
*/
@@ -566,6 +574,61 @@ process_pgfdw_appname(const char *appname)
return buf.data;
}
+/*
+ * Get the PgFdwExplainState structure from an ExplainState; if there is
+ * none, create one, attach it to the ExplainState, and return it.
+ */
+static PgFdwExplainState *
+pgfdw_ensure_options(ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"));
+
+ if (pgfdw_explain_state == NULL)
+ {
+ pgfdw_explain_state = palloc0(sizeof(PgFdwExplainState));
+ SetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"), pgfdw_explain_state);
+ pgfdw_explain_state->all_remote_plans = NIL;
+ }
+
+ return pgfdw_explain_state;
+}
+
+/*
+ * Parse handler for EXPLAIN (REMOTE_PLANS).
+ */
+static void
+pgfdw_remote_plans_apply(ExplainState *es, DefElem *opt, ParseState *pstate)
+{
+ PgFdwExplainState *options = pgfdw_ensure_options(es);
+
+ options->remote_plans = defGetBoolean(opt);
+}
+
+static void
+postgresExplainValidateOptions(ExplainState *es, List *options, ParseState *pstate)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state = NULL;
+
+ foreach(lc, options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0)
+ {
+ if (defGetBoolean(opt) && es->analyze)
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together"));
+
+ pgfdw_explain_state = pgfdw_ensure_options(es);
+ pgfdw_explain_state->options = options;
+ }
+ }
+}
+
/*
* Module load callback
*/
@@ -592,4 +655,16 @@ _PG_init(void)
NULL);
MarkGUCPrefixReserved("postgres_fdw");
+
+ RegisterExtensionExplainOption("remote_plans", pgfdw_remote_plans_apply,
+ GUCCheckBooleanExplainOption);
+
+ /* per node EXPLAIN hook */
+ prev_explain_per_node_hook = explain_per_node_hook;
+ explain_per_node_hook = postgresExplainPerNode;
+ prev_explain_per_plan_hook = explain_per_plan_hook;
+ explain_per_plan_hook = postgresExplainPerPlan;
+ prev_explain_validate_options_hook = explain_validate_options_hook;
+ explain_validate_options_hook = postgresExplainValidateOptions;
+
}
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 8b660a6..4cc955d 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -139,6 +139,19 @@ enum FdwDirectModifyPrivateIndex
FdwDirectModifyPrivateSetProcessed,
};
+/*
+ * Track the extension id in the backend.
+ */
+static int extension_id = -1;
+
+static int
+get_extension_id(void)
+{
+ if (extension_id == -1)
+ extension_id = GetExplainExtensionId("postgres_fdw");
+ return extension_id;
+}
+
/*
* Execution state of a foreign scan using postgres_fdw.
*/
@@ -2916,6 +2929,106 @@ postgresEndDirectModify(ForeignScanState *node)
/* MemoryContext will be deleted automatically. */
}
+static void
+postgresExplainStatement(int plan_node_id,
+ PgFdwExplainState *pgfdw_explain_state,
+ PGconn *conn,
+ char *sql)
+{
+ PGresult *volatile res = NULL;
+ StringInfoData explain_sql;
+ int remote_version = PQserverVersion(conn);
+ ListCell *lc;
+
+ /*
+ * GENERIC_PLAN required because deparsed SQL may contain $n placeholders;
+ * only available from PG 16.
+ */
+ if (remote_version < 160000)
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("EXPLAIN option REMOTE_PLANS requires a remote server version of 16 or later"),
+ errdetail("The remote server version is %d.", remote_version));
+
+ /*
+ * Forward user-specified options as-is; force GENERIC_PLAN on.
+ */
+ initStringInfo(&explain_sql);
+ appendStringInfoString(&explain_sql, "EXPLAIN (GENERIC_PLAN TRUE");
+
+ foreach(lc, pgfdw_explain_state->options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0 ||
+ strcmp(opt->defname, "generic_plan") == 0)
+ continue;
+
+ if (opt->arg == NULL)
+ appendStringInfo(&explain_sql, ", %s", opt->defname);
+ else
+ appendStringInfo(&explain_sql, ", %s %s", opt->defname,
+ defGetString(opt));
+ }
+
+ appendStringInfo(&explain_sql, ") %s", sql);
+
+ PG_TRY();
+ {
+ int numrows,
+ i;
+ PgFdwExplainRemotePlans *explain;
+
+ /* Run the query and collect the remote plan */
+ res = pgfdw_exec_query(conn, explain_sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, explain_sql.data);
+
+ explain = (PgFdwExplainRemotePlans *) palloc(sizeof(PgFdwExplainRemotePlans));
+ initStringInfo(&explain->explain_plan);
+
+ numrows = PQntuples(res);
+
+ for (i = 0; i < numrows; i++)
+ appendStringInfo(&explain->explain_plan, "%s\n", PQgetvalue(res, i, 0));
+
+ if (explain->explain_plan.len > 0 && explain->explain_plan.data[explain->explain_plan.len - 1] == '\n')
+ explain->explain_plan.data[--explain->explain_plan.len] = '\0';
+
+ explain->plan_node_id = plan_node_id;
+ pgfdw_explain_state->all_remote_plans = lappend(pgfdw_explain_state->all_remote_plans, explain);
+ }
+ PG_FINALLY();
+ {
+ if (res)
+ PQclear(res);
+ }
+ PG_END_TRY();
+
+ pfree(explain_sql.data);
+}
+
+/*
+ * explain_remote_query
+ * Helper function to get connection and execute remote EXPLAIN
+ */
+static void
+explain_remote_query(int plan_node_id,
+ PgFdwExplainState *pgfdw_explain_state,
+ Oid foreign_table_oid, char *sql)
+{
+ UserMapping *user;
+ PGconn *conn;
+ ForeignTable *table;
+
+ table = GetForeignTable(foreign_table_oid);
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+
+ postgresExplainStatement(plan_node_id, pgfdw_explain_state, conn, sql);
+ ReleaseConnection(conn);
+}
+
/*
* postgresExplainForeignScan
* Produce extra output for EXPLAIN of a ForeignScan on a foreign table
@@ -2925,6 +3038,12 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
List *fdw_private = plan->fdw_private;
+ PgFdwExplainState *pgfdw_explain_state;
+ char *sql;
+ Oid foreign_table_oid = InvalidOid;
+
+ if (node->ss.ss_currentRelation)
+ foreign_table_oid = RelationGetRelid(node->ss.ss_currentRelation);
/*
* Identify foreign scans that are really joins or upper relations. The
@@ -2986,6 +3105,13 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
Assert(rte->rtekind == RTE_RELATION);
/* This logic should agree with explain.c's ExplainTargetRel */
relname = get_rel_name(rte->relid);
+
+ /*
+ * Save first table OID for getting server connection
+ */
+ if (!OidIsValid(foreign_table_oid))
+ foreign_table_oid = rte->relid;
+
if (es->verbose)
{
char *namespace;
@@ -3011,16 +3137,24 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
ExplainPropertyText("Relations", relations.data, es);
}
+ sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
+
/*
* Add remote query, when VERBOSE option is specified.
*/
if (es->verbose)
- {
- char *sql;
-
- sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ /* If we don't have a foreign table oid by now, something went wrong */
+ Assert(foreign_table_oid);
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ foreign_table_oid,
+ sql);
}
/*
@@ -3034,11 +3168,12 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
int subplan_index,
ExplainState *es)
{
+ char *sql = strVal(list_nth(fdw_private,
+ FdwModifyPrivateUpdateSql));
+ PgFdwExplainState *pgfdw_explain_state;
+
if (es->verbose)
{
- char *sql = strVal(list_nth(fdw_private,
- FdwModifyPrivateUpdateSql));
-
ExplainPropertyText("Remote SQL", sql, es);
/*
@@ -3048,6 +3183,13 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
if (rinfo->ri_BatchSize > 0)
ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
}
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(mtstate->ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ rinfo->ri_RelationDesc->rd_rel->oid,
+ sql);
}
/*
@@ -3060,13 +3202,21 @@ postgresExplainDirectModify(ForeignScanState *node, ExplainState *es)
{
List *fdw_private;
char *sql;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
+ sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
if (es->verbose)
- {
- fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
- sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ RelationGetRelid(node->ss.ss_currentRelation),
+ sql);
}
/*
@@ -8766,3 +8916,95 @@ get_batch_size_option(Relation rel)
return batch_size;
}
+
+void
+postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship, const char *plan_name,
+ ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state == NULL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ ExplainPropertyInteger("Plan Node ID", NULL, planstate->plan->plan_node_id, es);
+}
+
+static void
+pgfdwFormatRemotePlan(PgFdwExplainRemotePlans *explain,
+ ExplainState *es,
+ int plan_node_id)
+{
+ char *token;
+ StringInfoData remote_plan_name;
+
+ initStringInfo(&remote_plan_name);
+ appendStringInfo(&remote_plan_name, "Plan Node ID %d", plan_node_id);
+
+ ExplainOpenGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Plan Node ID %d:", plan_node_id);
+ appendStringInfoString(es->str, "\n");
+ }
+
+ while ((token = strsep(&explain->explain_plan.data, "\n")) != NULL)
+ {
+ if (es->format == EXPLAIN_FORMAT_JSON ||
+ es->format == EXPLAIN_FORMAT_YAML)
+ appendStringInfoString(es->str, "\n");
+
+ appendStringInfoSpaces(es->str, (es->indent == 0) ? 2 : es->indent * 2);
+ appendStringInfoString(es->str, token);
+
+ if (es->format == EXPLAIN_FORMAT_XML ||
+ es->format == EXPLAIN_FORMAT_TEXT)
+ appendStringInfoString(es->str, "\n");
+ }
+
+ ExplainCloseGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+ pfree(remote_plan_name.data);
+}
+
+void
+postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state == NULL ||
+ pgfdw_explain_state->all_remote_plans == NIL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ ExplainOpenGroup("Remote Plans", "Remote Plans", true, es);
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Remote Plans:\n");
+ appendStringInfo(es->str, "-------------\n");
+ }
+
+ /* Process every remote plan captured */
+ foreach(lc, pgfdw_explain_state->all_remote_plans)
+ {
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) lfirst(lc);
+
+ pgfdwFormatRemotePlan(explain,
+ es,
+ explain->plan_node_id);
+ }
+
+ ExplainCloseGroup("Remote Plans", "Remote Plans", true, es);
+}
diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h
index a2bb1ff..6ede7a4 100644
--- a/contrib/postgres_fdw/postgres_fdw.h
+++ b/contrib/postgres_fdw/postgres_fdw.h
@@ -13,6 +13,7 @@
#ifndef POSTGRES_FDW_H
#define POSTGRES_FDW_H
+#include "commands/explain_state.h"
#include "foreign/foreign.h"
#include "lib/stringinfo.h"
#include "libpq/libpq-be-fe.h"
@@ -151,6 +152,22 @@ typedef enum PgFdwSamplingMethod
ANALYZE_SAMPLE_BERNOULLI, /* TABLESAMPLE bernoulli */
} PgFdwSamplingMethod;
+typedef struct PgFdwExplainRemotePlans
+{
+ int plan_node_id;
+ StringInfoData explain_plan;
+
+} PgFdwExplainRemotePlans;
+
+typedef struct PgFdwExplainState
+{
+ List *all_remote_plans;
+
+ /* EXPLAIN options */
+ bool remote_plans;
+ List *options; /* raw user DefElem list, for forwarding */
+} PgFdwExplainState;
+
/* in postgres_fdw.c */
extern int set_transmission_modes(void);
extern void reset_transmission_modes(int nestlevel);
@@ -178,6 +195,16 @@ extern int ExtractConnectionOptions(List *defelems,
extern List *ExtractExtensionList(const char *extensionsString,
bool warnOnMissing);
extern char *process_pgfdw_appname(const char *appname);
+extern void postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship,
+ const char *plan_name,
+ ExplainState *es);
+extern void postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv);
extern char *pgfdw_application_name;
/* in deparse.c */
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index e701995..1e68708 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -311,6 +311,11 @@ SELECT * FROM ft1 t1 WHERE t1.c3 = (SELECT MAX(c3) FROM ft2 t2) ORDER BY c1;
WITH t1 AS (SELECT * FROM ft1 WHERE c1 <= 10) SELECT t2.c1, t2.c2, t2.c3, t2.c4 FROM t1, ft2 t2 WHERE t1.c1 = t2.c1 ORDER BY t1.c1;
-- fixed values
SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -338,6 +343,19 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 left join ft1 t2 full join ft2
EXPLAIN (VERBOSE, COSTS OFF)
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
+
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+
+-- Tables on multiple foreign connections: ft5 lives on server loopback and
+-- ft6 on server loopback2, so the join cannot be pushed down as a single
+-- foreign join. Each side is scanned over its own connection, so REMOTE_PLANS
+-- must collect and print one remote plan per connection.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) WHERE t1.c1 = 10;
+
RESET enable_hashjoin;
RESET enable_nestloop;
@@ -379,6 +397,11 @@ EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c8 = 'foo'; -- can't be
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
@@ -1562,6 +1585,33 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
ORDER BY ft1.c1 LIMIT 5;
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -1645,6 +1695,9 @@ DELETE FROM fpo_part_parent
FOR PORTION OF c4 FROM '2024-06-01' TO '2024-06-15' WHERE c2 = 1; -- okay
SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
@@ -4287,6 +4340,9 @@ INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_t
SELECT * FROM insert_tbl ORDER BY a;
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index b9e1b04..b457611 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -1197,6 +1197,93 @@ CREATE SUBSCRIPTION my_subscription SERVER subscription_server PUBLICATION testp
The query that is actually sent to the remote server for execution can
be examined using <command>EXPLAIN VERBOSE</command>.
</para>
+
+ <para>
+ In addition to the remote query itself, the plan that the remote server
+ chooses for that query can be examined with the
+ <literal>REMOTE_PLANS</literal> option of <command>EXPLAIN</command>.
+ For every foreign scan or foreign modification in the local plan,
+ <filename>postgres_fdw</filename> runs <command>EXPLAIN</command> on the
+ remote server for the corresponding remote query and prints the result in a
+ <literal>Remote Plans</literal> section, keyed by the plan node id of the
+ local node. For example:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS) SELECT * FROM foreign_tbl WHERE id = 42;
+ QUERY PLAN
+-----------------------------------------------------------
+ Foreign Scan on public.foreign_tbl
+ Output: id, val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = 42))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = 42)
+</programlisting>
+ When the local plan uses a parameterized foreign scan (for example, as
+ the inner side of a nested loop join), the remote SQL contains parameter
+ placeholders. The remote plan is a generic plan in this case:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS, COSTS OFF)
+ SELECT * FROM local_tbl a, foreign_tbl b WHERE a.id = 1 AND b.id = a.val;
+ QUERY PLAN
+-----------------------------------------------------------
+ Nested Loop
+ Output: a.id, a.val, b.id, b.val
+ -> Seq Scan on public.local_tbl a
+ Output: a.id, a.val
+ Filter: (a.id = 1)
+ -> Foreign Scan on public.foreign_tbl b
+ Output: b.id, b.val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = $1::integer))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = $1)
+</programlisting>
+ </para>
+
+ <para>
+ The <literal>REMOTE_PLANS</literal> option is registered when
+ <filename>postgres_fdw</filename> is loaded, so the module must be loaded
+ (for example with <command>CREATE EXTENSION postgres_fdw</command>) before
+ the option can be used. The following restrictions apply:
+ <itemizedlist>
+ <listitem>
+ <para>
+ It cannot be combined with <literal>ANALYZE</literal>; doing so raises an
+ error. The remote query is only planned, never executed, so the foreign
+ server is not affected and no remote rows are fetched.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ The remote server must be running <productname>PostgreSQL</productname>
+ 16 or later, because <literal>REMOTE_PLANS</literal> relies on the
+ <literal>GENERIC_PLAN</literal> option of <command>EXPLAIN</command>,
+ which was introduced in that release. As shown in the parameterized
+ example above, the plan shown by <literal>REMOTE_PLANS</literal> is
+ always a generic plan, which may differ from the plan the remote
+ server actually uses at execution time when specific parameter values
+ are available.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ All <command>EXPLAIN</command> options specified by the user (other than
+ <literal>REMOTE_PLANS</literal> itself and
+ <literal>GENERIC_PLAN</literal>) are forwarded to the remote server.
+ If the remote server is running an older version that does not recognize
+ a forwarded option, it will report an error.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
</sect2>
<sect2 id="postgres-fdw-remote-query-execution-environment">
diff --git a/src/include/commands/explain_state.h b/src/include/commands/explain_state.h
index 97bc7ed..7e4dc6b 100644
--- a/src/include/commands/explain_state.h
+++ b/src/include/commands/explain_state.h
@@ -45,6 +45,7 @@ typedef struct ExplainWorkersState
typedef struct ExplainState
{
StringInfo str; /* output buffer */
+
/* options */
bool verbose; /* be verbose */
bool analyze; /* print actual times */
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 56c1f99..be16b39 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2308,6 +2308,8 @@ PgChecksumMode
PgFdwAnalyzeState
PgFdwConnState
PgFdwDirectModifyState
+PgFdwExplainRemotePlans
+PgFdwExplainState
PgFdwModifyState
PgFdwOption
PgFdwPathExtraData
--
2.47.3
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-07-28 06:26 Dinesh Salve <cooltodinesh@gmail.com>
parent: Dinesh Salve <cooltodinesh@gmail.com>
0 siblings, 1 reply; 31+ messages in thread
From: Dinesh Salve @ 2026-07-28 06:26 UTC (permalink / raw)
To: Yilin Zhang <jiezhilove@126.com>; +Cc: Sami Imseih <samimseih@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
A minor update in patch after observing cfbot failures.
Root cause was - _PG_init saved the previous explain* hooks but never
called them, so when postgres_fdw.so was lazily loaded during planning it
clobbered pg_plan_advice's per-plan hook and its "Generated Plan Advice"
output vanished — breaking contrib/pg_plan_advice/t/001_foreign_scan.pl on
every platform.
Regards,
Dinesh Salve
>
Attachments:
v6-0001-postgres_fdw-show-remote-EXPLAIN-plans-via-REMOTE.patch (application/octet-stream, 71.7K) download
From 7986f908844348a4b3e1514c630a449cf088a5f2 Mon Sep 17 00:00:00 2001
From: Dinesh Salve <cooltodinesh@gmail.com>
Date: Mon, 27 Jul 2026 21:22:24 +0530
Subject: [PATCH v6] postgres_fdw: show remote EXPLAIN plans via REMOTE_PLANS
option
Add a REMOTE_PLANS option to EXPLAIN that, for every foreign scan or
foreign modification, runs EXPLAIN on the remote server for the
corresponding remote query and prints the result in a "Remote Plans"
section keyed by the local plan node id.
The remote query that postgres_fdw sends often contains $n parameter
placeholders (parameterized foreign scans and joins, subquery outputs,
and INSERT/UPDATE/DELETE), which a plain remote EXPLAIN cannot plan and
fails with "there is no parameter $1". REMOTE_PLANS therefore forces
GENERIC_PLAN on the remote EXPLAIN, which plans such statements without
bound values. GENERIC_PLAN is only available from PostgreSQL 16, so
REMOTE_PLANS errors out on older remote servers.
REMOTE_PLANS cannot be combined with ANALYZE. All user-specified EXPLAIN
options (other than REMOTE_PLANS and GENERIC_PLAN) are forwarded to the
remote server as-is. If the remote server does not recognize a forwarded
option, it reports an error.
The option is registered, and the EXPLAIN hooks it needs are installed,
when postgres_fdw is loaded. The work is split across three hooks:
explain_validate_options_hook rejects REMOTE_PLANS together with ANALYZE
and records the user's option list for forwarding, explain_per_node_hook
labels each node with its plan node id, and explain_per_plan_hook prints
the remote plans collected while the plan was walked. Each of these
chains to the hook it replaced, so other modules using the same hooks
keep working regardless of the order in which the modules are loaded.
---
.../postgres_fdw/expected/postgres_fdw.out | 658 ++++++++++++++++++
contrib/postgres_fdw/option.c | 79 +++
contrib/postgres_fdw/postgres_fdw.c | 273 +++++++-
contrib/postgres_fdw/postgres_fdw.h | 35 +
contrib/postgres_fdw/sql/postgres_fdw.sql | 56 ++
doc/src/sgml/postgres-fdw.sgml | 87 +++
src/tools/pgindent/typedefs.list | 2 +
7 files changed, 1178 insertions(+), 12 deletions(-)
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index d19121b..0109ed2 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -471,6 +471,173 @@ SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
fixed |
(1 row)
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ - Plan: +
+ Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "ft1" +
+ Schema: "public" +
+ Alias: "t1" +
+ Disabled: false +
+ Output: +
+ - "c1" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Remote SQL: "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))"+
+ Plan Node ID: 0 +
+ Remote Plans: +
+ Plan Node ID 0: +
+ - Plan: +
+ Node Type: "Index Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Schema: "S 1" +
+ Alias: "T 1" +
+ Disabled: false +
+ Output: +
+ - "\"C 1\"" +
+ - "c2" +
+ - "c3" +
+ - "c4" +
+ - "c5" +
+ - "c6" +
+ - "c7" +
+ - "c8" +
+ Index Cond: "(\"T 1\".\"C 1\" = 101)"
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>ft1</Relation-Name> +
+ <Schema>public</Schema> +
+ <Alias>t1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>c1</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Remote-SQL>SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))</Remote-SQL>+
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-0> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Schema>S 1</Schema> +
+ <Alias>T 1</Alias> +
+ <Disabled>false</Disabled> +
+ <Output> +
+ <Item>"C 1"</Item> +
+ <Item>c2</Item> +
+ <Item>c3</Item> +
+ <Item>c4</Item> +
+ <Item>c5</Item> +
+ <Item>c6</Item> +
+ <Item>c7</Item> +
+ <Item>c8</Item> +
+ </Output> +
+ <Index-Cond>("T 1"."C 1" = 101)</Index-Cond> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-0> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "ft1", +
+ "Schema": "public", +
+ "Alias": "t1", +
+ "Disabled": false, +
+ "Output": ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Remote SQL": "SELECT \"C 1\", c2, c3, c4, c5, c6, c7, c8 FROM \"S 1\".\"T 1\" WHERE ((\"C 1\" = 101))",+
+ "Plan Node ID": 0 +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 0": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Schema": "S 1", +
+ "Alias": "T 1", +
+ "Disabled": false, +
+ "Output": ["\"C 1\"", "c2", "c3", "c4", "c5", "c6", "c7", "c8"], +
+ "Index Cond": "(\"T 1\".\"C 1\" = 101)" +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = 101)
+(10 rows)
+
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -646,6 +813,57 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2
110 | 110 | 110
(10 rows)
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------------------------------------
+ Foreign Scan
+ Output: t1.c1, t2.c1
+ Relations: (public.ft1 t1) INNER JOIN (public.ft2 t2)
+ Remote SQL: SELECT r1."C 1", r2."C 1" FROM ("S 1"."T 1" r1 INNER JOIN "S 1"."T 1" r2 ON (((r2."C 1" = r1."C 1")) AND ((r1.c2 = 10))))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Seq Scan on "S 1"."T 1" r2
+ Output: r2."C 1", r2."C 1"
+ Filter: (r2.c2 = 10)
+(11 rows)
+
+-- Tables on multiple foreign connections: ft5 lives on server loopback and
+-- ft6 on server loopback2, so the join cannot be pushed down as a single
+-- foreign join. Each side is scanned over its own connection, so REMOTE_PLANS
+-- must collect and print one remote plan per connection.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) WHERE t1.c1 = 10;
+ QUERY PLAN
+------------------------------------------------------------------
+ Nested Loop
+ Disabled: true
+ Output: t1.c1, t2.c1
+ Plan Node ID: 0
+ -> Foreign Scan on public.ft5 t1
+ Output: t1.c1, t1.c2, t1.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 4" WHERE ((c1 = 10))
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft6 t2
+ Output: t2.c1, t2.c2, t2.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 4" WHERE ((c1 = 10))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Seq Scan on "S 1"."T 4"
+ Output: c1
+ Filter: ("T 4".c1 = 10)
+ Plan Node ID 2:
+ Seq Scan on "S 1"."T 4"
+ Output: c1
+ Filter: ("T 4".c1 = 10)
+(22 rows)
+
RESET enable_hashjoin;
RESET enable_nestloop;
-- Test executing assertion in estimate_path_cost_size() that makes sure that
@@ -790,6 +1008,32 @@ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
47 | 7 | 00047 | Tue Feb 17 00:00:00 1970 PST | Tue Feb 17 00:00:00 1970 | 7 | 7 | foo | 7 | 7 | 00007 | Thu Jan 08 00:00:00 1970 PST | Thu Jan 08 00:00:00 1970 | 7 | 7 | foo
(1 row)
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+ QUERY PLAN
+-------------------------------------------------------------------------------------------------------------
+ Nested Loop
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8, b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Plan Node ID: 0
+ -> Index Scan using t1_pkey on "S 1"."T 1" a
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8
+ Index Cond: (a."C 1" = 47)
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft2 b
+ Output: b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = $1::integer))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = $1)
+(17 rows)
+
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM ft2 a, ft2 b
@@ -5191,6 +5435,373 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
Remote SQL: SELECT r5."C 1", r6.c1 FROM ("S 1"."T 1" r5 INNER JOIN "S 1"."T 3" r6 ON (((r5."C 1" = r6.c1)))) ORDER BY r5."C 1" ASC NULLS LAST
(13 rows)
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ERROR: EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ Limit
+ Plan Node ID: 0
+ -> Merge Semi Join
+ Merge Cond: (ft1.c1 = ft2_1.c1)
+ Plan Node ID: 1
+ -> Foreign Scan
+ Relations: (ft1) INNER JOIN (ft2)
+ Plan Node ID: 2
+ -> Foreign Scan
+ Relations: (ft2 ft2_1) INNER JOIN (ft4)
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Only Scan using t1_pkey on "T 1" r2
+ Plan Node ID 3:
+ Merge Join
+ Merge Cond: (r5."C 1" = r6.c1)
+ -> Index Only Scan using t1_pkey on "T 1" r5
+ -> Sort
+ Sort Key: r6.c1
+ -> Seq Scan on "T 3" r6
+(22 rows)
+
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Limit</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Semi</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>false</Inner-Unique> +
+ <Merge-Cond>(ft1.c1 = ft2_1.c1)</Merge-Cond> +
+ <Plan-Node-ID>1</Plan-Node-ID> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft1) INNER JOIN (ft2)</Relations> +
+ <Plan-Node-ID>2</Plan-Node-ID> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Relations>(ft2 ft2_1) INNER JOIN (ft4)</Relations> +
+ <Plan-Node-ID>3</Plan-Node-ID> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-2> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r2</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-2> +
+ <Plan-Node-ID-3> +
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Merge Join</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Join-Type>Inner</Join-Type> +
+ <Disabled>false</Disabled> +
+ <Inner-Unique>true</Inner-Unique> +
+ <Merge-Cond>(r5."C 1" = r6.c1)</Merge-Cond> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>r5</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ <Plan> +
+ <Node-Type>Sort</Node-Type> +
+ <Parent-Relationship>Inner</Parent-Relationship> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Disabled>false</Disabled> +
+ <Sort-Key> +
+ <Item>r6.c1</Item> +
+ </Sort-Key> +
+ <Plans> +
+ <Plan> +
+ <Node-Type>Seq Scan</Node-Type> +
+ <Parent-Relationship>Outer</Parent-Relationship>+
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>T 3</Relation-Name> +
+ <Alias>r6</Alias> +
+ <Disabled>false</Disabled> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Plans> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-3> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+------------------------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Limit", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Plan Node ID": 0, +
+ "Plans": [ +
+ { +
+ "Node Type": "Merge Join", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Semi", +
+ "Disabled": false, +
+ "Inner Unique": false, +
+ "Merge Cond": "(ft1.c1 = ft2_1.c1)", +
+ "Plan Node ID": 1, +
+ "Plans": [ +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft1) INNER JOIN (ft2)", +
+ "Plan Node ID": 2 +
+ }, +
+ { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Relations": "(ft2 ft2_1) INNER JOIN (ft4)",+
+ "Plan Node ID": 3 +
+ } +
+ ] +
+ } +
+ ] +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 2": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Only Scan", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r2", +
+ "Disabled": false +
+ } +
+ } +
+ ] +
+ ], +
+ "Plan Node ID 3": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Merge Join", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Join Type": "Inner", +
+ "Disabled": false, +
+ "Inner Unique": true, +
+ "Merge Cond": "(r5.\"C 1\" = r6.c1)", +
+ "Plans": [ +
+ { +
+ "Node Type": "Index Only Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "r5", +
+ "Disabled": false +
+ }, +
+ { +
+ "Node Type": "Sort", +
+ "Parent Relationship": "Inner", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Disabled": false, +
+ "Sort Key": ["r6.c1"], +
+ "Plans": [ +
+ { +
+ "Node Type": "Seq Scan", +
+ "Parent Relationship": "Outer", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "T 3", +
+ "Alias": "r6", +
+ "Disabled": false +
+ } +
+ ] +
+ } +
+ ] +
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ - Plan: +
+ Node Type: "Limit" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Plan Node ID: 0 +
+ Plans: +
+ - Node Type: "Merge Join" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Semi" +
+ Disabled: false +
+ Inner Unique: false +
+ Merge Cond: "(ft1.c1 = ft2_1.c1)" +
+ Plan Node ID: 1 +
+ Plans: +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft1) INNER JOIN (ft2)" +
+ Plan Node ID: 2 +
+ - Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Relations: "(ft2 ft2_1) INNER JOIN (ft4)"+
+ Plan Node ID: 3 +
+ Remote Plans: +
+ Plan Node ID 2: +
+ - Plan: +
+ Node Type: "Index Only Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r2" +
+ Disabled: false +
+ Plan Node ID 3: +
+ - Plan: +
+ Node Type: "Merge Join" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Join Type: "Inner" +
+ Disabled: false +
+ Inner Unique: true +
+ Merge Cond: "(r5.\"C 1\" = r6.c1)" +
+ Plans: +
+ - Node Type: "Index Only Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "r5" +
+ Disabled: false +
+ - Node Type: "Sort" +
+ Parent Relationship: "Inner" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Disabled: false +
+ Sort Key: +
+ - "r6.c1" +
+ Plans: +
+ - Node Type: "Seq Scan" +
+ Parent Relationship: "Outer" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "T 3" +
+ Alias: "r6" +
+ Disabled: false
+(1 row)
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -6465,6 +7076,25 @@ SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
(3 rows)
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
+ QUERY PLAN
+---------------------------------------------------------------------------------------
+ Update on public.ft2
+ Plan Node ID: 0
+ -> Foreign Update on public.ft2
+ Remote SQL: UPDATE "S 1"."T 1" SET c2 = (c2 + 300) WHERE ((("C 1" % 10) = 3))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Update on "S 1"."T 1"
+ -> Seq Scan on "S 1"."T 1"
+ Output: (c2 + 300), ctid
+ Filter: (("T 1"."C 1" % 10) = 3)
+(12 rows)
+
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id;
@@ -12497,6 +13127,34 @@ SELECT * FROM insert_tbl ORDER BY a;
2505 | 505 | bar
(2 rows)
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+ QUERY PLAN
+-------------------------------------------------------------------------
+ Insert on public.insert_tbl
+ Remote SQL: INSERT INTO public.base_tbl4(a, b, c) VALUES ($1, $2, $3)
+ Batch Size: 1
+ Plan Node ID: 0
+ -> Append
+ Plan Node ID: 1
+ -> Seq Scan on public.local_tbl
+ Output: local_tbl.a, local_tbl.b, local_tbl.c
+ Plan Node ID: 2
+ -> Async Foreign Scan on public.remote_tbl
+ Output: remote_tbl.a, remote_tbl.b, remote_tbl.c
+ Remote SQL: SELECT a, b, c FROM public.base_tbl3
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Insert on public.base_tbl4
+ -> Result
+ Output: $1, $2, $3
+ Plan Node ID 3:
+ Seq Scan on public.base_tbl3
+ Output: a, b, c
+(22 rows)
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 79b16c3..bdd7c9f 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -17,6 +17,7 @@
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#include "commands/defrem.h"
+#include "commands/explain.h"
#include "commands/extension.h"
#include "libpq/libpq-be.h"
#include "postgres_fdw.h"
@@ -40,6 +41,15 @@ typedef struct PgFdwOption
*/
static PgFdwOption *postgres_fdw_options;
+/*
+ * Previously installed EXPLAIN hooks. Every hook function we install must
+ * call the previous one, so that other modules using the same hooks keep
+ * working no matter what order the modules happen to be loaded in.
+ */
+explain_per_node_hook_type prev_explain_per_node_hook = NULL;
+explain_per_plan_hook_type prev_explain_per_plan_hook = NULL;
+static explain_validate_options_hook_type prev_explain_validate_options_hook = NULL;
+
/*
* GUC parameters
*/
@@ -566,6 +576,64 @@ process_pgfdw_appname(const char *appname)
return buf.data;
}
+/*
+ * Get the PgFdwExplainState structure from an ExplainState; if there is
+ * none, create one, attach it to the ExplainState, and return it.
+ */
+static PgFdwExplainState *
+pgfdw_ensure_options(ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"));
+
+ if (pgfdw_explain_state == NULL)
+ {
+ pgfdw_explain_state = palloc0(sizeof(PgFdwExplainState));
+ SetExplainExtensionState(es, GetExplainExtensionId("postgres_fdw"), pgfdw_explain_state);
+ pgfdw_explain_state->all_remote_plans = NIL;
+ }
+
+ return pgfdw_explain_state;
+}
+
+/*
+ * Parse handler for EXPLAIN (REMOTE_PLANS).
+ */
+static void
+pgfdw_remote_plans_apply(ExplainState *es, DefElem *opt, ParseState *pstate)
+{
+ PgFdwExplainState *options = pgfdw_ensure_options(es);
+
+ options->remote_plans = defGetBoolean(opt);
+}
+
+static void
+postgresExplainValidateOptions(ExplainState *es, List *options, ParseState *pstate)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state = NULL;
+
+ if (prev_explain_validate_options_hook)
+ (*prev_explain_validate_options_hook) (es, options, pstate);
+
+ foreach(lc, options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0)
+ {
+ if (defGetBoolean(opt) && es->analyze)
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together"));
+
+ pgfdw_explain_state = pgfdw_ensure_options(es);
+ pgfdw_explain_state->options = options;
+ }
+ }
+}
+
/*
* Module load callback
*/
@@ -592,4 +660,15 @@ _PG_init(void)
NULL);
MarkGUCPrefixReserved("postgres_fdw");
+
+ RegisterExtensionExplainOption("remote_plans", pgfdw_remote_plans_apply,
+ GUCCheckBooleanExplainOption);
+
+ /* Install our EXPLAIN hooks, saving the previous ones for chaining. */
+ prev_explain_per_node_hook = explain_per_node_hook;
+ explain_per_node_hook = postgresExplainPerNode;
+ prev_explain_per_plan_hook = explain_per_plan_hook;
+ explain_per_plan_hook = postgresExplainPerPlan;
+ prev_explain_validate_options_hook = explain_validate_options_hook;
+ explain_validate_options_hook = postgresExplainValidateOptions;
}
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 8b660a6..aadca6f 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -139,6 +139,19 @@ enum FdwDirectModifyPrivateIndex
FdwDirectModifyPrivateSetProcessed,
};
+/*
+ * Track the extension id in the backend.
+ */
+static int extension_id = -1;
+
+static int
+get_extension_id(void)
+{
+ if (extension_id == -1)
+ extension_id = GetExplainExtensionId("postgres_fdw");
+ return extension_id;
+}
+
/*
* Execution state of a foreign scan using postgres_fdw.
*/
@@ -2916,6 +2929,106 @@ postgresEndDirectModify(ForeignScanState *node)
/* MemoryContext will be deleted automatically. */
}
+static void
+postgresExplainStatement(int plan_node_id,
+ PgFdwExplainState *pgfdw_explain_state,
+ PGconn *conn,
+ char *sql)
+{
+ PGresult *volatile res = NULL;
+ StringInfoData explain_sql;
+ int remote_version = PQserverVersion(conn);
+ ListCell *lc;
+
+ /*
+ * GENERIC_PLAN required because deparsed SQL may contain $n placeholders;
+ * only available from PG 16.
+ */
+ if (remote_version < 160000)
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("EXPLAIN option REMOTE_PLANS requires a remote server version of 16 or later"),
+ errdetail("The remote server version is %d.", remote_version));
+
+ /*
+ * Forward user-specified options as-is; force GENERIC_PLAN on.
+ */
+ initStringInfo(&explain_sql);
+ appendStringInfoString(&explain_sql, "EXPLAIN (GENERIC_PLAN TRUE");
+
+ foreach(lc, pgfdw_explain_state->options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0 ||
+ strcmp(opt->defname, "generic_plan") == 0)
+ continue;
+
+ if (opt->arg == NULL)
+ appendStringInfo(&explain_sql, ", %s", opt->defname);
+ else
+ appendStringInfo(&explain_sql, ", %s %s", opt->defname,
+ defGetString(opt));
+ }
+
+ appendStringInfo(&explain_sql, ") %s", sql);
+
+ PG_TRY();
+ {
+ int numrows,
+ i;
+ PgFdwExplainRemotePlans *explain;
+
+ /* Run the query and collect the remote plan */
+ res = pgfdw_exec_query(conn, explain_sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, explain_sql.data);
+
+ explain = (PgFdwExplainRemotePlans *) palloc(sizeof(PgFdwExplainRemotePlans));
+ initStringInfo(&explain->explain_plan);
+
+ numrows = PQntuples(res);
+
+ for (i = 0; i < numrows; i++)
+ appendStringInfo(&explain->explain_plan, "%s\n", PQgetvalue(res, i, 0));
+
+ if (explain->explain_plan.len > 0 && explain->explain_plan.data[explain->explain_plan.len - 1] == '\n')
+ explain->explain_plan.data[--explain->explain_plan.len] = '\0';
+
+ explain->plan_node_id = plan_node_id;
+ pgfdw_explain_state->all_remote_plans = lappend(pgfdw_explain_state->all_remote_plans, explain);
+ }
+ PG_FINALLY();
+ {
+ if (res)
+ PQclear(res);
+ }
+ PG_END_TRY();
+
+ pfree(explain_sql.data);
+}
+
+/*
+ * explain_remote_query
+ * Helper function to get connection and execute remote EXPLAIN
+ */
+static void
+explain_remote_query(int plan_node_id,
+ PgFdwExplainState *pgfdw_explain_state,
+ Oid foreign_table_oid, char *sql)
+{
+ UserMapping *user;
+ PGconn *conn;
+ ForeignTable *table;
+
+ table = GetForeignTable(foreign_table_oid);
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+
+ postgresExplainStatement(plan_node_id, pgfdw_explain_state, conn, sql);
+ ReleaseConnection(conn);
+}
+
/*
* postgresExplainForeignScan
* Produce extra output for EXPLAIN of a ForeignScan on a foreign table
@@ -2925,6 +3038,12 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
List *fdw_private = plan->fdw_private;
+ PgFdwExplainState *pgfdw_explain_state;
+ char *sql;
+ Oid foreign_table_oid = InvalidOid;
+
+ if (node->ss.ss_currentRelation)
+ foreign_table_oid = RelationGetRelid(node->ss.ss_currentRelation);
/*
* Identify foreign scans that are really joins or upper relations. The
@@ -2986,6 +3105,13 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
Assert(rte->rtekind == RTE_RELATION);
/* This logic should agree with explain.c's ExplainTargetRel */
relname = get_rel_name(rte->relid);
+
+ /*
+ * Save first table OID for getting server connection
+ */
+ if (!OidIsValid(foreign_table_oid))
+ foreign_table_oid = rte->relid;
+
if (es->verbose)
{
char *namespace;
@@ -3011,16 +3137,24 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
ExplainPropertyText("Relations", relations.data, es);
}
+ sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
+
/*
* Add remote query, when VERBOSE option is specified.
*/
if (es->verbose)
- {
- char *sql;
-
- sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ /* If we don't have a foreign table oid by now, something went wrong */
+ Assert(foreign_table_oid);
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ foreign_table_oid,
+ sql);
}
/*
@@ -3034,11 +3168,12 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
int subplan_index,
ExplainState *es)
{
+ char *sql = strVal(list_nth(fdw_private,
+ FdwModifyPrivateUpdateSql));
+ PgFdwExplainState *pgfdw_explain_state;
+
if (es->verbose)
{
- char *sql = strVal(list_nth(fdw_private,
- FdwModifyPrivateUpdateSql));
-
ExplainPropertyText("Remote SQL", sql, es);
/*
@@ -3048,6 +3183,13 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
if (rinfo->ri_BatchSize > 0)
ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
}
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(mtstate->ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ rinfo->ri_RelationDesc->rd_rel->oid,
+ sql);
}
/*
@@ -3060,13 +3202,21 @@ postgresExplainDirectModify(ForeignScanState *node, ExplainState *es)
{
List *fdw_private;
char *sql;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
+ sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
if (es->verbose)
- {
- fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
- sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ RelationGetRelid(node->ss.ss_currentRelation),
+ sql);
}
/*
@@ -8766,3 +8916,102 @@ get_batch_size_option(Relation rel)
return batch_size;
}
+
+void
+postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship, const char *plan_name,
+ ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ if (prev_explain_per_node_hook)
+ (*prev_explain_per_node_hook) (planstate, ancestors, relationship,
+ plan_name, es);
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state == NULL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ ExplainPropertyInteger("Plan Node ID", NULL, planstate->plan->plan_node_id, es);
+}
+
+static void
+pgfdwFormatRemotePlan(PgFdwExplainRemotePlans *explain,
+ ExplainState *es,
+ int plan_node_id)
+{
+ char *token;
+ StringInfoData remote_plan_name;
+
+ initStringInfo(&remote_plan_name);
+ appendStringInfo(&remote_plan_name, "Plan Node ID %d", plan_node_id);
+
+ ExplainOpenGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Plan Node ID %d:", plan_node_id);
+ appendStringInfoString(es->str, "\n");
+ }
+
+ while ((token = strsep(&explain->explain_plan.data, "\n")) != NULL)
+ {
+ if (es->format == EXPLAIN_FORMAT_JSON ||
+ es->format == EXPLAIN_FORMAT_YAML)
+ appendStringInfoString(es->str, "\n");
+
+ appendStringInfoSpaces(es->str, (es->indent == 0) ? 2 : es->indent * 2);
+ appendStringInfoString(es->str, token);
+
+ if (es->format == EXPLAIN_FORMAT_XML ||
+ es->format == EXPLAIN_FORMAT_TEXT)
+ appendStringInfoString(es->str, "\n");
+ }
+
+ ExplainCloseGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+ pfree(remote_plan_name.data);
+}
+
+void
+postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ if (prev_explain_per_plan_hook)
+ (*prev_explain_per_plan_hook) (plannedstmt, into, es, queryString,
+ params, queryEnv);
+
+ pgfdw_explain_state = GetExplainExtensionState(es, get_extension_id());
+
+ if (pgfdw_explain_state == NULL ||
+ pgfdw_explain_state->all_remote_plans == NIL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ ExplainOpenGroup("Remote Plans", "Remote Plans", true, es);
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Remote Plans:\n");
+ appendStringInfo(es->str, "-------------\n");
+ }
+
+ /* Process every remote plan captured */
+ foreach(lc, pgfdw_explain_state->all_remote_plans)
+ {
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) lfirst(lc);
+
+ pgfdwFormatRemotePlan(explain,
+ es,
+ explain->plan_node_id);
+ }
+
+ ExplainCloseGroup("Remote Plans", "Remote Plans", true, es);
+}
diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h
index a2bb1ff..ccc7f76 100644
--- a/contrib/postgres_fdw/postgres_fdw.h
+++ b/contrib/postgres_fdw/postgres_fdw.h
@@ -13,6 +13,8 @@
#ifndef POSTGRES_FDW_H
#define POSTGRES_FDW_H
+#include "commands/explain.h"
+#include "commands/explain_state.h"
#include "foreign/foreign.h"
#include "lib/stringinfo.h"
#include "libpq/libpq-be-fe.h"
@@ -151,10 +153,36 @@ typedef enum PgFdwSamplingMethod
ANALYZE_SAMPLE_BERNOULLI, /* TABLESAMPLE bernoulli */
} PgFdwSamplingMethod;
+typedef struct PgFdwExplainRemotePlans
+{
+ int plan_node_id;
+ StringInfoData explain_plan;
+
+} PgFdwExplainRemotePlans;
+
+typedef struct PgFdwExplainState
+{
+ List *all_remote_plans;
+
+ /* EXPLAIN options */
+ bool remote_plans;
+ List *options; /* raw user DefElem list, for forwarding */
+} PgFdwExplainState;
+
/* in postgres_fdw.c */
extern int set_transmission_modes(void);
extern void reset_transmission_modes(int nestlevel);
extern void process_pending_request(AsyncRequest *areq);
+extern void postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship,
+ const char *plan_name,
+ ExplainState *es);
+extern void postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv);
/* in connection.c */
extern PGconn *GetConnection(UserMapping *user, bool will_prep_stmt,
@@ -180,6 +208,13 @@ extern List *ExtractExtensionList(const char *extensionsString,
extern char *process_pgfdw_appname(const char *appname);
extern char *pgfdw_application_name;
+/*
+ * Previous values of the EXPLAIN hooks we install in _PG_init. The hook
+ * functions live in postgres_fdw.c, so these have to be visible there.
+ */
+extern explain_per_node_hook_type prev_explain_per_node_hook;
+extern explain_per_plan_hook_type prev_explain_per_plan_hook;
+
/* in deparse.c */
extern void classifyConditions(PlannerInfo *root,
RelOptInfo *baserel,
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index e701995..1e68708 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -311,6 +311,11 @@ SELECT * FROM ft1 t1 WHERE t1.c3 = (SELECT MAX(c3) FROM ft2 t2) ORDER BY c1;
WITH t1 AS (SELECT * FROM ft1 WHERE c1 <= 10) SELECT t2.c1, t2.c2, t2.c3, t2.c4 FROM t1, ft2 t2 WHERE t1.c1 = t2.c1 ORDER BY t1.c1;
-- fixed values
SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
+-- with WHERE clause and remote_plans with different formats
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT XML, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+EXPLAIN (REMOTE_PLANS TRUE, FORMAT TEXT, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -338,6 +343,19 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 left join ft1 t2 full join ft2
EXPLAIN (VERBOSE, COSTS OFF)
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
+
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+
+-- Tables on multiple foreign connections: ft5 lives on server loopback and
+-- ft6 on server loopback2, so the join cannot be pushed down as a single
+-- foreign join. Each side is scanned over its own connection, so REMOTE_PLANS
+-- must collect and print one remote plan per connection.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) WHERE t1.c1 = 10;
+
RESET enable_hashjoin;
RESET enable_nestloop;
@@ -379,6 +397,11 @@ EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c8 = 'foo'; -- can't be
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
@@ -1562,6 +1585,33 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
ORDER BY ft1.c1 LIMIT 5;
+-- EXPLAIN remote_plans
+EXPLAIN (remote_plans, format text, costs off, analyze)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format text, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format xml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format json, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (remote_plans, format yaml, costs off)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -1645,6 +1695,9 @@ DELETE FROM fpo_part_parent
FOR PORTION OF c4 FROM '2024-06-01' TO '2024-06-15' WHERE c2 = 1; -- okay
SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with remote_plans
+EXPLAIN (remote_plans, verbose, costs off)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
@@ -4287,6 +4340,9 @@ INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_t
SELECT * FROM insert_tbl ORDER BY a;
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index b9e1b04..b457611 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -1197,6 +1197,93 @@ CREATE SUBSCRIPTION my_subscription SERVER subscription_server PUBLICATION testp
The query that is actually sent to the remote server for execution can
be examined using <command>EXPLAIN VERBOSE</command>.
</para>
+
+ <para>
+ In addition to the remote query itself, the plan that the remote server
+ chooses for that query can be examined with the
+ <literal>REMOTE_PLANS</literal> option of <command>EXPLAIN</command>.
+ For every foreign scan or foreign modification in the local plan,
+ <filename>postgres_fdw</filename> runs <command>EXPLAIN</command> on the
+ remote server for the corresponding remote query and prints the result in a
+ <literal>Remote Plans</literal> section, keyed by the plan node id of the
+ local node. For example:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS) SELECT * FROM foreign_tbl WHERE id = 42;
+ QUERY PLAN
+-----------------------------------------------------------
+ Foreign Scan on public.foreign_tbl
+ Output: id, val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = 42))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = 42)
+</programlisting>
+ When the local plan uses a parameterized foreign scan (for example, as
+ the inner side of a nested loop join), the remote SQL contains parameter
+ placeholders. The remote plan is a generic plan in this case:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS, COSTS OFF)
+ SELECT * FROM local_tbl a, foreign_tbl b WHERE a.id = 1 AND b.id = a.val;
+ QUERY PLAN
+-----------------------------------------------------------
+ Nested Loop
+ Output: a.id, a.val, b.id, b.val
+ -> Seq Scan on public.local_tbl a
+ Output: a.id, a.val
+ Filter: (a.id = 1)
+ -> Foreign Scan on public.foreign_tbl b
+ Output: b.id, b.val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = $1::integer))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = $1)
+</programlisting>
+ </para>
+
+ <para>
+ The <literal>REMOTE_PLANS</literal> option is registered when
+ <filename>postgres_fdw</filename> is loaded, so the module must be loaded
+ (for example with <command>CREATE EXTENSION postgres_fdw</command>) before
+ the option can be used. The following restrictions apply:
+ <itemizedlist>
+ <listitem>
+ <para>
+ It cannot be combined with <literal>ANALYZE</literal>; doing so raises an
+ error. The remote query is only planned, never executed, so the foreign
+ server is not affected and no remote rows are fetched.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ The remote server must be running <productname>PostgreSQL</productname>
+ 16 or later, because <literal>REMOTE_PLANS</literal> relies on the
+ <literal>GENERIC_PLAN</literal> option of <command>EXPLAIN</command>,
+ which was introduced in that release. As shown in the parameterized
+ example above, the plan shown by <literal>REMOTE_PLANS</literal> is
+ always a generic plan, which may differ from the plan the remote
+ server actually uses at execution time when specific parameter values
+ are available.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ All <command>EXPLAIN</command> options specified by the user (other than
+ <literal>REMOTE_PLANS</literal> itself and
+ <literal>GENERIC_PLAN</literal>) are forwarded to the remote server.
+ If the remote server is running an older version that does not recognize
+ a forwarded option, it will report an error.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
</sect2>
<sect2 id="postgres-fdw-remote-query-execution-environment">
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 56c1f99..be16b39 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2308,6 +2308,8 @@ PgChecksumMode
PgFdwAnalyzeState
PgFdwConnState
PgFdwDirectModifyState
+PgFdwExplainRemotePlans
+PgFdwExplainState
PgFdwModifyState
PgFdwOption
PgFdwPathExtraData
--
2.47.3
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-08-04 20:55 Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
parent: Dinesh Salve <cooltodinesh@gmail.com>
0 siblings, 0 replies; 31+ messages in thread
From: Bharath Rupireddy @ 2026-08-04 20:55 UTC (permalink / raw)
To: Dinesh Salve <cooltodinesh@gmail.com>; +Cc: Yilin Zhang <jiezhilove@126.com>; Sami Imseih <samimseih@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>
Hi,
On Mon, Jul 27, 2026 at 11:27 PM Dinesh Salve <cooltodinesh@gmail.com> wrote:
>
> A minor update in patch after observing cfbot failures.
>
> Root cause was - _PG_init saved the previous explain* hooks but never called them, so when postgres_fdw.so was lazily loaded during planning it clobbered pg_plan_advice's per-plan hook and its "Generated Plan Advice" output vanished — breaking contrib/pg_plan_advice/t/001_foreign_scan.pl on every platform.
Thanks for working on this, Dinesh!
Thanks, Sami, for pointing me to this!
It seems useful especially in distributed/sharded PostgreSQL database
architectures that rely on postgres_fdw. The use of explain plans
needs no introduction in production query performance analysis. In
distributed databases, many times there can be tens of remote
databases, and analyzing query performance issues across all the
remote databases may not always be possible (simply that one needs to
hop across remote databases and one may not have permissions to run
queries at all, etc.), and even if one is able to run them, it's hard
to figure out and get it exactly right to collect the plans from
different remote databases. (Again, others who have seen these
problems firsthand can explain this better than me.)
I haven't read the whole thread, but I remember the first time we
talked off-list about this problem. With that context, I just happened
to look at the v6 patch and it seems the tests and expected outputs
are too verbose, making the patch huge and hard to review. IMO, we
don't need to print all the flavors of explain plans (JSON/XML/YAML).
How about running a simple join or aggregate on a couple of remote
tables joining with a local table and just printing the explain plan
(no JSON/XML/YAML) like any other explain test? Is there any problem
with this?
Another point, why are we not supporting explain analyze?
Here are some code-level comments on the patch:
1/
+static int
+get_extension_id(void)
+{
+ if (extension_id == -1)
+ extension_id = GetExplainExtensionId("postgres_fdw");
+ return extension_id;
Why not get the extension id at once in _PG_init and use the static
variable directly, instead of spreading the get function calls
everywhere?
2/
+ <literal>GENERIC_PLAN</literal>) are forwarded to the remote server.
+ If the remote server is running an older version that does not recognize
+ /*
+ * GENERIC_PLAN required because deparsed SQL may contain $n placeholders;
+ * only available from PG 16.
+ */
It's worth mentioning that otherwise it causes an ERROR for
parameterized queries.
3/ Add some error cases where the remote explain query gives an error,
to see how it is handled in postgresExplainStatement's PG try-catch
block.
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-08-05 10:31 solai v <solai.cdac@gmail.com>
parent: Yilin Zhang <jiezhilove@126.com>
1 sibling, 1 reply; 31+ messages in thread
From: solai v @ 2026-08-05 10:31 UTC (permalink / raw)
To: dinesh salve <cooltodinesh@gmail.com>; +Cc: Sami Imseih <samimseih@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>; Yilin Zhang <jiezhilove@126.com>
Hi Dinesh,
I tested the latest v6 patch. I set up two PostgreSQL instances (one
local and one remote) connected through postgres_fdw, created a
foreign table, and verified the behavior before and after applying the
patch.
Before applying the patch, EXPLAIN on the foreign table only displayed
a Foreign Scan node. EXPLAIN (VERBOSE) showed the generated Remote
SQL, but it did not provide any information about how the remote
PostgreSQL server planned to execute the query.
After applying the patch, rebuilding PostgreSQL, and restarting both
instances, I verified that EXPLAIN (REMOTE_PLANS) now displays a new
Remote Plans section. The output correctly included the execution plan
generated by the remote PostgreSQL server (for example, Seq Scan on
emp) along with the corresponding Plan Node ID.
I also verified the following:
EXPLAIN (REMOTE_PLANS) successfully displays the remote execution plan.
EXPLAIN (REMOTE_PLANS) with a WHERE clause correctly reflects the
filter condition in the remote plan.
EXPLAIN (REMOTE_PLANS, VERBOSE) continues to display the existing
Remote SQL output together with the new Remote Plans section.
EXPLAIN (REMOTE_PLANS, ANALYZE) correctly reports:
ERROR: EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together
which matches the current implementation.
I did not encounter any issues during my testing, and the feature
behaved as expected in the scenarios I tested.
Thanks for working on this feature.
Regards,
solai
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-08-05 10:47 Dinesh Salve <cooltodinesh@gmail.com>
parent: solai v <solai.cdac@gmail.com>
0 siblings, 3 replies; 31+ messages in thread
From: Dinesh Salve @ 2026-08-05 10:47 UTC (permalink / raw)
To: solai v <solai.cdac@gmail.com>; Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>; +Cc: Sami Imseih <samimseih@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>; Yilin Zhang <jiezhilove@126.com>
Thanks a lot Solai for testing the patch, appreciate it.
Hi Bharath,
Thanks for the inputs, attached v7 patch to make review easier.
> IMO, we don't need to print all the flavors of explain plans
I have removed formatting related tests from file postgres_fdw.sql and
moved to a separate file remote_plans_formats.sql.
We still need tests around formatting as my changes introduce some new
elements.
> Another point, why are we not supporting explain analyze?
This will be part of follow-up work, I wanted agreement on the shape first
from the community.
One design I considered is an auto_explain-style GUC asking the remote to
emit the plan for the statement it is already
running, but we cannot assume an arbitrary foreign server has that, so it
needs a fallback and more thought.
> 1/ Why not get the extension id at once in _PG_init
Fixed, also I moved all the EXPLAIN plumbing into postgres_fdw.c behind
postgres_fdw_explain_init(), called from
_PG_init. The extension id, the saved hook pointers and both hook
functions are now static.
Addressed other comments regarding documentation around GENERIC_PLAN option
and added error case handling non-existent remote table.
Attachments:
v7-0001-postgres_fdw-show-remote-EXPLAIN-plans-via-REMOTE.patch (application/octet-stream, 45.1K) download
From b4dcd228402909a25a453e317520269d0685accc Mon Sep 17 00:00:00 2001
From: Dinesh Salve <cooltodinesh@gmail.com>
Date: Mon, 27 Jul 2026 21:22:24 +0530
Subject: [PATCH v7] postgres_fdw: show remote EXPLAIN plans via REMOTE_PLANS
option
Add a REMOTE_PLANS option to EXPLAIN that, for every foreign scan or
foreign modification, runs EXPLAIN on the remote server for the
corresponding remote query and prints the result in a "Remote Plans"
section keyed by the local plan node id.
The remote query that postgres_fdw sends often contains $n parameter
placeholders (parameterized foreign scans and joins, subquery outputs,
and INSERT/UPDATE/DELETE), which a plain remote EXPLAIN cannot plan and
fails with "there is no parameter $1". REMOTE_PLANS therefore forces
GENERIC_PLAN on the remote EXPLAIN, which plans such statements without
bound values. GENERIC_PLAN is only available from PostgreSQL 16, so
REMOTE_PLANS errors out on older remote servers.
REMOTE_PLANS cannot be combined with ANALYZE. All user-specified EXPLAIN
options (other than REMOTE_PLANS and GENERIC_PLAN) are forwarded to the
remote server as-is. If the remote server does not recognize a forwarded
option, it reports an error.
The option is registered, and the EXPLAIN hooks it needs are installed,
by postgres_fdw_explain_init(), which _PG_init calls. The work is split
across three hooks: explain_validate_options_hook rejects REMOTE_PLANS
together with ANALYZE and records the user's option list for forwarding,
explain_per_node_hook labels each node with its plan node id, and
explain_per_plan_hook prints the remote plans collected while the plan
was walked. Each of these chains to the hook it replaced, so other
modules using the same hooks keep working regardless of the order in
which the modules are loaded.
Since the library is loaded on demand, the option is only recognized once
postgres_fdw has been loaded into the session, whether by an earlier query
against a foreign table, by LOAD, or by a preload GUC. Note that CREATE
EXTENSION alone does not load it into the current session.
Tests for the option itself live alongside the existing tests for the
plans they report on, in postgres_fdw.sql. The non-text output formats
are covered separately in remote_plans_formats.sql, so that the volume of
JSON/XML/YAML output does not swamp the main test file.
---
contrib/postgres_fdw/Makefile | 2 +-
.../postgres_fdw/expected/postgres_fdw.out | 194 +++++++++
.../expected/remote_plans_formats.out | 114 ++++++
contrib/postgres_fdw/meson.build | 1 +
contrib/postgres_fdw/option.c | 3 +
contrib/postgres_fdw/postgres_fdw.c | 379 +++++++++++++++++-
contrib/postgres_fdw/postgres_fdw.h | 1 +
contrib/postgres_fdw/sql/postgres_fdw.sql | 47 +++
.../postgres_fdw/sql/remote_plans_formats.sql | 19 +
doc/src/sgml/postgres-fdw.sgml | 99 +++++
src/tools/pgindent/typedefs.list | 2 +
11 files changed, 848 insertions(+), 13 deletions(-)
create mode 100644 contrib/postgres_fdw/expected/remote_plans_formats.out
create mode 100644 contrib/postgres_fdw/sql/remote_plans_formats.sql
diff --git a/contrib/postgres_fdw/Makefile b/contrib/postgres_fdw/Makefile
index b8c78b5..671f82c 100644
--- a/contrib/postgres_fdw/Makefile
+++ b/contrib/postgres_fdw/Makefile
@@ -16,7 +16,7 @@ SHLIB_LINK_INTERNAL = $(libpq)
EXTENSION = postgres_fdw
DATA = postgres_fdw--1.0.sql postgres_fdw--1.0--1.1.sql postgres_fdw--1.1--1.2.sql postgres_fdw--1.2--1.3.sql
-REGRESS = postgres_fdw query_cancel
+REGRESS = postgres_fdw remote_plans_formats query_cancel
ISOLATION = eval_plan_qual
ISOLATION_OPTS = --load-extension=postgres_fdw
TAP_TESTS = 1
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index d19121b..1cf5a41 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -471,6 +471,36 @@ SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
fixed |
(1 row)
+-- with WHERE clause and REMOTE_PLANS
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = 101)
+(10 rows)
+
+-- an error raised by the remote EXPLAIN is reported to the client; without
+-- REMOTE_PLANS this plan never contacts the remote server at all
+CREATE FOREIGN TABLE remote_plans_bad (c1 int)
+ SERVER loopback OPTIONS (schema_name 'S 1', table_name 'no_such_table');
+EXPLAIN (COSTS OFF) SELECT * FROM remote_plans_bad;
+ QUERY PLAN
+----------------------------------
+ Foreign Scan on remote_plans_bad
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, COSTS OFF) SELECT * FROM remote_plans_bad;
+ERROR: relation "S 1.no_such_table" does not exist
+CONTEXT: remote SQL command: EXPLAIN (GENERIC_PLAN TRUE, costs off) SELECT c1 FROM "S 1".no_such_table
+DROP FOREIGN TABLE remote_plans_bad;
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -646,6 +676,57 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2
110 | 110 | 110
(10 rows)
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------------------------------------
+ Foreign Scan
+ Output: t1.c1, t2.c1
+ Relations: (public.ft1 t1) INNER JOIN (public.ft2 t2)
+ Remote SQL: SELECT r1."C 1", r2."C 1" FROM ("S 1"."T 1" r1 INNER JOIN "S 1"."T 1" r2 ON (((r2."C 1" = r1."C 1")) AND ((r1.c2 = 10))))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Seq Scan on "S 1"."T 1" r2
+ Output: r2."C 1", r2."C 1"
+ Filter: (r2.c2 = 10)
+(11 rows)
+
+-- Tables on multiple foreign connections: ft5 lives on server loopback and
+-- ft6 on server loopback2, so the join cannot be pushed down as a single
+-- foreign join. Each side is scanned over its own connection, so REMOTE_PLANS
+-- must collect and print one remote plan per connection.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) WHERE t1.c1 = 10;
+ QUERY PLAN
+------------------------------------------------------------------
+ Nested Loop
+ Disabled: true
+ Output: t1.c1, t2.c1
+ Plan Node ID: 0
+ -> Foreign Scan on public.ft5 t1
+ Output: t1.c1, t1.c2, t1.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 4" WHERE ((c1 = 10))
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft6 t2
+ Output: t2.c1, t2.c2, t2.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 4" WHERE ((c1 = 10))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Seq Scan on "S 1"."T 4"
+ Output: c1
+ Filter: ("T 4".c1 = 10)
+ Plan Node ID 2:
+ Seq Scan on "S 1"."T 4"
+ Output: c1
+ Filter: ("T 4".c1 = 10)
+(22 rows)
+
RESET enable_hashjoin;
RESET enable_nestloop;
-- Test executing assertion in estimate_path_cost_size() that makes sure that
@@ -790,6 +871,32 @@ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
47 | 7 | 00047 | Tue Feb 17 00:00:00 1970 PST | Tue Feb 17 00:00:00 1970 | 7 | 7 | foo | 7 | 7 | 00007 | Thu Jan 08 00:00:00 1970 PST | Thu Jan 08 00:00:00 1970 | 7 | 7 | foo
(1 row)
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+ QUERY PLAN
+-------------------------------------------------------------------------------------------------------------
+ Nested Loop
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8, b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Plan Node ID: 0
+ -> Index Scan using t1_pkey on "S 1"."T 1" a
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8
+ Index Cond: (a."C 1" = 47)
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft2 b
+ Output: b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = $1::integer))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = $1)
+(17 rows)
+
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM ft2 a, ft2 b
@@ -5191,6 +5298,46 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
Remote SQL: SELECT r5."C 1", r6.c1 FROM ("S 1"."T 1" r5 INNER JOIN "S 1"."T 3" r6 ON (((r5."C 1" = r6.c1)))) ORDER BY r5."C 1" ASC NULLS LAST
(13 rows)
+-- EXPLAIN with REMOTE_PLANS
+-- REMOTE_PLANS forces GENERIC_PLAN on the remote EXPLAIN, so it cannot be
+-- combined with ANALYZE
+EXPLAIN (REMOTE_PLANS, COSTS OFF, ANALYZE)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ERROR: EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together
+EXPLAIN (REMOTE_PLANS, COSTS OFF)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ Limit
+ Plan Node ID: 0
+ -> Merge Semi Join
+ Merge Cond: (ft1.c1 = ft2_1.c1)
+ Plan Node ID: 1
+ -> Foreign Scan
+ Relations: (ft1) INNER JOIN (ft2)
+ Plan Node ID: 2
+ -> Foreign Scan
+ Relations: (ft2 ft2_1) INNER JOIN (ft4)
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Only Scan using t1_pkey on "T 1" r2
+ Plan Node ID 3:
+ Merge Join
+ Merge Cond: (r5."C 1" = r6.c1)
+ -> Index Only Scan using t1_pkey on "T 1" r5
+ -> Sort
+ Sort Key: r6.c1
+ -> Seq Scan on "T 3" r6
+(22 rows)
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -6465,6 +6612,25 @@ SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
(3 rows)
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with REMOTE_PLANS
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
+ QUERY PLAN
+---------------------------------------------------------------------------------------
+ Update on public.ft2
+ Plan Node ID: 0
+ -> Foreign Update on public.ft2
+ Remote SQL: UPDATE "S 1"."T 1" SET c2 = (c2 + 300) WHERE ((("C 1" % 10) = 3))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Update on "S 1"."T 1"
+ -> Seq Scan on "S 1"."T 1"
+ Output: (c2 + 300), ctid
+ Filter: (("T 1"."C 1" % 10) = 3)
+(12 rows)
+
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id;
@@ -12497,6 +12663,34 @@ SELECT * FROM insert_tbl ORDER BY a;
2505 | 505 | bar
(2 rows)
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+ QUERY PLAN
+-------------------------------------------------------------------------
+ Insert on public.insert_tbl
+ Remote SQL: INSERT INTO public.base_tbl4(a, b, c) VALUES ($1, $2, $3)
+ Batch Size: 1
+ Plan Node ID: 0
+ -> Append
+ Plan Node ID: 1
+ -> Seq Scan on public.local_tbl
+ Output: local_tbl.a, local_tbl.b, local_tbl.c
+ Plan Node ID: 2
+ -> Async Foreign Scan on public.remote_tbl
+ Output: remote_tbl.a, remote_tbl.b, remote_tbl.c
+ Remote SQL: SELECT a, b, c FROM public.base_tbl3
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Insert on public.base_tbl4
+ -> Result
+ Output: $1, $2, $3
+ Plan Node ID 3:
+ Seq Scan on public.base_tbl3
+ Output: a, b, c
+(22 rows)
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/contrib/postgres_fdw/expected/remote_plans_formats.out b/contrib/postgres_fdw/expected/remote_plans_formats.out
new file mode 100644
index 0000000..37b64b4
--- /dev/null
+++ b/contrib/postgres_fdw/expected/remote_plans_formats.out
@@ -0,0 +1,114 @@
+-- ===================================================================
+-- test EXPLAIN (REMOTE_PLANS) in the non-text output formats
+-- ===================================================================
+-- The behaviour of REMOTE_PLANS itself is tested in postgres_fdw.sql, next
+-- to the tests for the plans it reports on. This file only covers how the
+-- collected remote plans are embedded in each output format.
+-- This runs after postgres_fdw.sql in the same database and reuses the
+-- server, user mapping and foreign tables created there.
+LOAD 'postgres_fdw';
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "ft1", +
+ "Alias": "t1", +
+ "Disabled": false, +
+ "Plan Node ID": 0 +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 0": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Only Scan",+
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "T 1", +
+ "Disabled": false, +
+ "Index Cond": "(\"C 1\" = 101)"+
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, FORMAT XML, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>ft1</Relation-Name> +
+ <Alias>t1</Alias> +
+ <Disabled>false</Disabled> +
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-0> +
+ <explain xmlns="http://www.postgresql.org/2009/explain">+
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>T 1</Alias> +
+ <Disabled>false</Disabled> +
+ <Index-Cond>("C 1" = 101)</Index-Cond> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-0> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------
+ - Plan: +
+ Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "ft1" +
+ Alias: "t1" +
+ Disabled: false +
+ Plan Node ID: 0 +
+ Remote Plans: +
+ Plan Node ID 0: +
+ - Plan: +
+ Node Type: "Index Only Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "T 1" +
+ Disabled: false +
+ Index Cond: "(\"C 1\" = 101)"
+(1 row)
+
diff --git a/contrib/postgres_fdw/meson.build b/contrib/postgres_fdw/meson.build
index 3e2ed06..6a9bb65 100644
--- a/contrib/postgres_fdw/meson.build
+++ b/contrib/postgres_fdw/meson.build
@@ -38,6 +38,7 @@ tests += {
'regress': {
'sql': [
'postgres_fdw',
+ 'remote_plans_formats',
'query_cancel',
],
'regress_args': ['--dlpath', meson.project_build_root() / 'src/test/regress'],
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 79b16c3..5d180c9 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -592,4 +592,7 @@ _PG_init(void)
NULL);
MarkGUCPrefixReserved("postgres_fdw");
+
+ /* Register EXPLAIN (REMOTE_PLANS) and install the hooks it needs. */
+ postgres_fdw_explain_init();
}
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 8b660a6..91e22bd 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -19,6 +19,7 @@
#include "access/table.h"
#include "catalog/pg_opfamily.h"
#include "commands/defrem.h"
+#include "commands/explain.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "commands/vacuum.h"
@@ -139,6 +140,44 @@ enum FdwDirectModifyPrivateIndex
FdwDirectModifyPrivateSetProcessed,
};
+/*
+ * One remote plan collected while walking the local plan, identified by the
+ * plan node id of the local node that produced the remote query.
+ */
+typedef struct PgFdwExplainRemotePlans
+{
+ int plan_node_id;
+ StringInfoData explain_plan;
+} PgFdwExplainRemotePlans;
+
+/*
+ * Our private state within an ExplainState, created on demand while the
+ * EXPLAIN options are parsed.
+ */
+typedef struct PgFdwExplainState
+{
+ List *all_remote_plans;
+
+ /* EXPLAIN options */
+ bool remote_plans;
+ List *options; /* raw user DefElem list, for forwarding */
+} PgFdwExplainState;
+
+/*
+ * Our slot in an ExplainState's extension state array, assigned once by
+ * postgres_fdw_explain_init().
+ */
+static int postgres_fdw_extension_id;
+
+/*
+ * Previously installed EXPLAIN hooks. Every hook function we install must
+ * call the previous one, so that other modules using the same hooks keep
+ * working no matter what order the modules happen to be loaded in.
+ */
+static explain_per_node_hook_type prev_explain_per_node_hook = NULL;
+static explain_per_plan_hook_type prev_explain_per_plan_hook = NULL;
+static explain_validate_options_hook_type prev_explain_validate_options_hook = NULL;
+
/*
* Execution state of a foreign scan using postgres_fdw.
*/
@@ -2916,6 +2955,107 @@ postgresEndDirectModify(ForeignScanState *node)
/* MemoryContext will be deleted automatically. */
}
+static void
+postgresExplainStatement(int plan_node_id,
+ PgFdwExplainState *pgfdw_explain_state,
+ PGconn *conn,
+ char *sql)
+{
+ PGresult *volatile res = NULL;
+ StringInfoData explain_sql;
+ int remote_version = PQserverVersion(conn);
+ ListCell *lc;
+
+ /*
+ * The deparsed SQL may contain $n placeholders, which a plain remote
+ * EXPLAIN cannot plan: it fails with "there is no parameter $1". We
+ * therefore force GENERIC_PLAN, which is only available from PG 16.
+ */
+ if (remote_version < 160000)
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("EXPLAIN option REMOTE_PLANS requires a remote server version of 16 or later"),
+ errdetail("The remote server version is %d.", remote_version));
+
+ /*
+ * Forward user-specified options as-is; force GENERIC_PLAN on.
+ */
+ initStringInfo(&explain_sql);
+ appendStringInfoString(&explain_sql, "EXPLAIN (GENERIC_PLAN TRUE");
+
+ foreach(lc, pgfdw_explain_state->options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0 ||
+ strcmp(opt->defname, "generic_plan") == 0)
+ continue;
+
+ if (opt->arg == NULL)
+ appendStringInfo(&explain_sql, ", %s", opt->defname);
+ else
+ appendStringInfo(&explain_sql, ", %s %s", opt->defname,
+ defGetString(opt));
+ }
+
+ appendStringInfo(&explain_sql, ") %s", sql);
+
+ PG_TRY();
+ {
+ int numrows,
+ i;
+ PgFdwExplainRemotePlans *explain;
+
+ /* Run the query and collect the remote plan */
+ res = pgfdw_exec_query(conn, explain_sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, explain_sql.data);
+
+ explain = (PgFdwExplainRemotePlans *) palloc(sizeof(PgFdwExplainRemotePlans));
+ initStringInfo(&explain->explain_plan);
+
+ numrows = PQntuples(res);
+
+ for (i = 0; i < numrows; i++)
+ appendStringInfo(&explain->explain_plan, "%s\n", PQgetvalue(res, i, 0));
+
+ if (explain->explain_plan.len > 0 && explain->explain_plan.data[explain->explain_plan.len - 1] == '\n')
+ explain->explain_plan.data[--explain->explain_plan.len] = '\0';
+
+ explain->plan_node_id = plan_node_id;
+ pgfdw_explain_state->all_remote_plans = lappend(pgfdw_explain_state->all_remote_plans, explain);
+ }
+ PG_FINALLY();
+ {
+ if (res)
+ PQclear(res);
+ }
+ PG_END_TRY();
+
+ pfree(explain_sql.data);
+}
+
+/*
+ * explain_remote_query
+ * Helper function to get connection and execute remote EXPLAIN
+ */
+static void
+explain_remote_query(int plan_node_id,
+ PgFdwExplainState *pgfdw_explain_state,
+ Oid foreign_table_oid, char *sql)
+{
+ UserMapping *user;
+ PGconn *conn;
+ ForeignTable *table;
+
+ table = GetForeignTable(foreign_table_oid);
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+
+ postgresExplainStatement(plan_node_id, pgfdw_explain_state, conn, sql);
+ ReleaseConnection(conn);
+}
+
/*
* postgresExplainForeignScan
* Produce extra output for EXPLAIN of a ForeignScan on a foreign table
@@ -2925,6 +3065,12 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
List *fdw_private = plan->fdw_private;
+ PgFdwExplainState *pgfdw_explain_state;
+ char *sql;
+ Oid foreign_table_oid = InvalidOid;
+
+ if (node->ss.ss_currentRelation)
+ foreign_table_oid = RelationGetRelid(node->ss.ss_currentRelation);
/*
* Identify foreign scans that are really joins or upper relations. The
@@ -2986,6 +3132,13 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
Assert(rte->rtekind == RTE_RELATION);
/* This logic should agree with explain.c's ExplainTargetRel */
relname = get_rel_name(rte->relid);
+
+ /*
+ * Save first table OID for getting server connection
+ */
+ if (!OidIsValid(foreign_table_oid))
+ foreign_table_oid = rte->relid;
+
if (es->verbose)
{
char *namespace;
@@ -3011,16 +3164,24 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
ExplainPropertyText("Relations", relations.data, es);
}
+ sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
+
/*
* Add remote query, when VERBOSE option is specified.
*/
if (es->verbose)
- {
- char *sql;
-
- sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+
+ /* If we don't have a foreign table oid by now, something went wrong */
+ Assert(foreign_table_oid);
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ foreign_table_oid,
+ sql);
}
/*
@@ -3034,11 +3195,12 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
int subplan_index,
ExplainState *es)
{
+ char *sql = strVal(list_nth(fdw_private,
+ FdwModifyPrivateUpdateSql));
+ PgFdwExplainState *pgfdw_explain_state;
+
if (es->verbose)
{
- char *sql = strVal(list_nth(fdw_private,
- FdwModifyPrivateUpdateSql));
-
ExplainPropertyText("Remote SQL", sql, es);
/*
@@ -3048,6 +3210,13 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
if (rinfo->ri_BatchSize > 0)
ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
}
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(mtstate->ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ rinfo->ri_RelationDesc->rd_rel->oid,
+ sql);
}
/*
@@ -3060,13 +3229,21 @@ postgresExplainDirectModify(ForeignScanState *node, ExplainState *es)
{
List *fdw_private;
char *sql;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
+ sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
if (es->verbose)
- {
- fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
- sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ RelationGetRelid(node->ss.ss_currentRelation),
+ sql);
}
/*
@@ -8766,3 +8943,181 @@ get_batch_size_option(Relation rel)
return batch_size;
}
+
+/*
+ * Get the PgFdwExplainState structure from an ExplainState; if there is
+ * none, create one, attach it to the ExplainState, and return it.
+ */
+static PgFdwExplainState *
+pgfdw_ensure_options(ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+
+ if (pgfdw_explain_state == NULL)
+ {
+ pgfdw_explain_state = palloc0(sizeof(PgFdwExplainState));
+ SetExplainExtensionState(es, postgres_fdw_extension_id, pgfdw_explain_state);
+ pgfdw_explain_state->all_remote_plans = NIL;
+ }
+
+ return pgfdw_explain_state;
+}
+
+/*
+ * Parse handler for EXPLAIN (REMOTE_PLANS).
+ */
+static void
+pgfdw_remote_plans_apply(ExplainState *es, DefElem *opt, ParseState *pstate)
+{
+ PgFdwExplainState *options = pgfdw_ensure_options(es);
+
+ options->remote_plans = defGetBoolean(opt);
+}
+
+static void
+postgresExplainValidateOptions(ExplainState *es, List *options, ParseState *pstate)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state = NULL;
+
+ if (prev_explain_validate_options_hook)
+ (*prev_explain_validate_options_hook) (es, options, pstate);
+
+ foreach(lc, options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0)
+ {
+ if (defGetBoolean(opt) && es->analyze)
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together"));
+
+ pgfdw_explain_state = pgfdw_ensure_options(es);
+ pgfdw_explain_state->options = options;
+ }
+ }
+}
+
+static void
+postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship, const char *plan_name,
+ ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ if (prev_explain_per_node_hook)
+ (*prev_explain_per_node_hook) (planstate, ancestors, relationship,
+ plan_name, es);
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+
+ if (pgfdw_explain_state == NULL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ ExplainPropertyInteger("Plan Node ID", NULL, planstate->plan->plan_node_id, es);
+}
+
+static void
+pgfdwFormatRemotePlan(PgFdwExplainRemotePlans *explain,
+ ExplainState *es,
+ int plan_node_id)
+{
+ char *token;
+ StringInfoData remote_plan_name;
+
+ initStringInfo(&remote_plan_name);
+ appendStringInfo(&remote_plan_name, "Plan Node ID %d", plan_node_id);
+
+ ExplainOpenGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Plan Node ID %d:", plan_node_id);
+ appendStringInfoString(es->str, "\n");
+ }
+
+ while ((token = strsep(&explain->explain_plan.data, "\n")) != NULL)
+ {
+ if (es->format == EXPLAIN_FORMAT_JSON ||
+ es->format == EXPLAIN_FORMAT_YAML)
+ appendStringInfoString(es->str, "\n");
+
+ appendStringInfoSpaces(es->str, (es->indent == 0) ? 2 : es->indent * 2);
+ appendStringInfoString(es->str, token);
+
+ if (es->format == EXPLAIN_FORMAT_XML ||
+ es->format == EXPLAIN_FORMAT_TEXT)
+ appendStringInfoString(es->str, "\n");
+ }
+
+ ExplainCloseGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+ pfree(remote_plan_name.data);
+}
+
+static void
+postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ if (prev_explain_per_plan_hook)
+ (*prev_explain_per_plan_hook) (plannedstmt, into, es, queryString,
+ params, queryEnv);
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+
+ if (pgfdw_explain_state == NULL ||
+ pgfdw_explain_state->all_remote_plans == NIL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ ExplainOpenGroup("Remote Plans", "Remote Plans", true, es);
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Remote Plans:\n");
+ appendStringInfo(es->str, "-------------\n");
+ }
+
+ /* Process every remote plan captured */
+ foreach(lc, pgfdw_explain_state->all_remote_plans)
+ {
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) lfirst(lc);
+
+ pgfdwFormatRemotePlan(explain,
+ es,
+ explain->plan_node_id);
+ }
+
+ ExplainCloseGroup("Remote Plans", "Remote Plans", true, es);
+}
+
+/*
+ * Register EXPLAIN (REMOTE_PLANS) and install the hooks that implement it.
+ * Called from _PG_init.
+ */
+void
+postgres_fdw_explain_init(void)
+{
+ postgres_fdw_extension_id = GetExplainExtensionId("postgres_fdw");
+
+ RegisterExtensionExplainOption("remote_plans", pgfdw_remote_plans_apply,
+ GUCCheckBooleanExplainOption);
+
+ /* Install our EXPLAIN hooks, saving the previous ones for chaining. */
+ prev_explain_per_node_hook = explain_per_node_hook;
+ explain_per_node_hook = postgresExplainPerNode;
+ prev_explain_per_plan_hook = explain_per_plan_hook;
+ explain_per_plan_hook = postgresExplainPerPlan;
+ prev_explain_validate_options_hook = explain_validate_options_hook;
+ explain_validate_options_hook = postgresExplainValidateOptions;
+}
diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h
index a2bb1ff..c043a30 100644
--- a/contrib/postgres_fdw/postgres_fdw.h
+++ b/contrib/postgres_fdw/postgres_fdw.h
@@ -155,6 +155,7 @@ typedef enum PgFdwSamplingMethod
extern int set_transmission_modes(void);
extern void reset_transmission_modes(int nestlevel);
extern void process_pending_request(AsyncRequest *areq);
+extern void postgres_fdw_explain_init(void);
/* in connection.c */
extern PGconn *GetConnection(UserMapping *user, bool will_prep_stmt,
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index e701995..a82cccf 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -311,6 +311,15 @@ SELECT * FROM ft1 t1 WHERE t1.c3 = (SELECT MAX(c3) FROM ft2 t2) ORDER BY c1;
WITH t1 AS (SELECT * FROM ft1 WHERE c1 <= 10) SELECT t2.c1, t2.c2, t2.c3, t2.c4 FROM t1, ft2 t2 WHERE t1.c1 = t2.c1 ORDER BY t1.c1;
-- fixed values
SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
+-- with WHERE clause and REMOTE_PLANS
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+-- an error raised by the remote EXPLAIN is reported to the client; without
+-- REMOTE_PLANS this plan never contacts the remote server at all
+CREATE FOREIGN TABLE remote_plans_bad (c1 int)
+ SERVER loopback OPTIONS (schema_name 'S 1', table_name 'no_such_table');
+EXPLAIN (COSTS OFF) SELECT * FROM remote_plans_bad;
+EXPLAIN (REMOTE_PLANS, COSTS OFF) SELECT * FROM remote_plans_bad;
+DROP FOREIGN TABLE remote_plans_bad;
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -338,6 +347,19 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 left join ft1 t2 full join ft2
EXPLAIN (VERBOSE, COSTS OFF)
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
+
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+
+-- Tables on multiple foreign connections: ft5 lives on server loopback and
+-- ft6 on server loopback2, so the join cannot be pushed down as a single
+-- foreign join. Each side is scanned over its own connection, so REMOTE_PLANS
+-- must collect and print one remote plan per connection.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) WHERE t1.c1 = 10;
+
RESET enable_hashjoin;
RESET enable_nestloop;
@@ -379,6 +401,11 @@ EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c8 = 'foo'; -- can't be
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
@@ -1562,6 +1589,20 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
ORDER BY ft1.c1 LIMIT 5;
+-- EXPLAIN with REMOTE_PLANS
+-- REMOTE_PLANS forces GENERIC_PLAN on the remote EXPLAIN, so it cannot be
+-- combined with ANALYZE
+EXPLAIN (REMOTE_PLANS, COSTS OFF, ANALYZE)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (REMOTE_PLANS, COSTS OFF)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -1645,6 +1686,9 @@ DELETE FROM fpo_part_parent
FOR PORTION OF c4 FROM '2024-06-01' TO '2024-06-15' WHERE c2 = 1; -- okay
SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with REMOTE_PLANS
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
@@ -4287,6 +4331,9 @@ INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_t
SELECT * FROM insert_tbl ORDER BY a;
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
diff --git a/contrib/postgres_fdw/sql/remote_plans_formats.sql b/contrib/postgres_fdw/sql/remote_plans_formats.sql
new file mode 100644
index 0000000..0d7e25c
--- /dev/null
+++ b/contrib/postgres_fdw/sql/remote_plans_formats.sql
@@ -0,0 +1,19 @@
+-- ===================================================================
+-- test EXPLAIN (REMOTE_PLANS) in the non-text output formats
+-- ===================================================================
+-- The behaviour of REMOTE_PLANS itself is tested in postgres_fdw.sql, next
+-- to the tests for the plans it reports on. This file only covers how the
+-- collected remote plans are embedded in each output format.
+-- This runs after postgres_fdw.sql in the same database and reuses the
+-- server, user mapping and foreign tables created there.
+
+LOAD 'postgres_fdw';
+
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
+
+EXPLAIN (REMOTE_PLANS, FORMAT XML, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
+
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index b9e1b04..96e5041 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -1197,6 +1197,105 @@ CREATE SUBSCRIPTION my_subscription SERVER subscription_server PUBLICATION testp
The query that is actually sent to the remote server for execution can
be examined using <command>EXPLAIN VERBOSE</command>.
</para>
+
+ <para>
+ In addition to the remote query itself, the plan that the remote server
+ chooses for that query can be examined with the
+ <literal>REMOTE_PLANS</literal> option of <command>EXPLAIN</command>.
+ For every foreign scan or foreign modification in the local plan,
+ <filename>postgres_fdw</filename> runs <command>EXPLAIN</command> on the
+ remote server for the corresponding remote query and prints the result in a
+ <literal>Remote Plans</literal> section, keyed by the plan node id of the
+ local node. For example:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS) SELECT * FROM foreign_tbl WHERE id = 42;
+ QUERY PLAN
+-----------------------------------------------------------
+ Foreign Scan on public.foreign_tbl
+ Output: id, val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = 42))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = 42)
+</programlisting>
+ When the local plan uses a parameterized foreign scan (for example, as
+ the inner side of a nested loop join), the remote SQL contains parameter
+ placeholders, which a plain <command>EXPLAIN</command> on the remote server
+ could not plan; it would fail with <literal>there is no parameter $1</literal>.
+ <literal>REMOTE_PLANS</literal> therefore asks the remote server for a
+ generic plan in this case:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS, COSTS OFF)
+ SELECT * FROM local_tbl a, foreign_tbl b WHERE a.id = 1 AND b.id = a.val;
+ QUERY PLAN
+-----------------------------------------------------------
+ Nested Loop
+ Output: a.id, a.val, b.id, b.val
+ -> Seq Scan on public.local_tbl a
+ Output: a.id, a.val
+ Filter: (a.id = 1)
+ -> Foreign Scan on public.foreign_tbl b
+ Output: b.id, b.val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = $1::integer))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = $1)
+</programlisting>
+ </para>
+
+ <para>
+ The <literal>REMOTE_PLANS</literal> option is registered when the
+ <filename>postgres_fdw</filename> library is loaded into the session. The
+ library is loaded on demand, the first time the session plans or executes a
+ query against a foreign table, so in a session that has not yet touched a
+ foreign table the option is not recognized and
+ <command>EXPLAIN</command> reports
+ <literal>unrecognized EXPLAIN option "remote_plans"</literal>. Note that
+ <command>CREATE EXTENSION postgres_fdw</command> alone does not load the
+ library into the current session. To make the option available up front,
+ use <command>LOAD 'postgres_fdw'</command>, or list the library in
+ <xref linkend="guc-session-preload-libraries"/> or
+ <xref linkend="guc-shared-preload-libraries"/>.
+ The following restrictions apply:
+ <itemizedlist>
+ <listitem>
+ <para>
+ It cannot be combined with <literal>ANALYZE</literal>; doing so raises an
+ error. The remote query is only planned, never executed, so the foreign
+ server is not affected and no remote rows are fetched.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ The remote server must be running <productname>PostgreSQL</productname>
+ 16 or later, because <literal>REMOTE_PLANS</literal> relies on the
+ <literal>GENERIC_PLAN</literal> option of <command>EXPLAIN</command>,
+ which was introduced in that release. As shown in the parameterized
+ example above, the plan shown by <literal>REMOTE_PLANS</literal> is
+ always a generic plan, which may differ from the plan the remote
+ server actually uses at execution time when specific parameter values
+ are available.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ All <command>EXPLAIN</command> options specified by the user (other than
+ <literal>REMOTE_PLANS</literal> itself and
+ <literal>GENERIC_PLAN</literal>) are forwarded to the remote server.
+ If the remote server is running an older version that does not recognize
+ a forwarded option, it will report an error.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
</sect2>
<sect2 id="postgres-fdw-remote-query-execution-environment">
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 56c1f99..be16b39 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2308,6 +2308,8 @@ PgChecksumMode
PgFdwAnalyzeState
PgFdwConnState
PgFdwDirectModifyState
+PgFdwExplainRemotePlans
+PgFdwExplainState
PgFdwModifyState
PgFdwOption
PgFdwPathExtraData
--
2.47.3
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-08-06 07:34 solai v <solai.cdac@gmail.com>
parent: Dinesh Salve <cooltodinesh@gmail.com>
2 siblings, 0 replies; 31+ messages in thread
From: solai v @ 2026-08-06 07:34 UTC (permalink / raw)
To: Dinesh Salve <cooltodinesh@gmail.com>; +Cc: Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>; Sami Imseih <samimseih@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>; Yilin Zhang <jiezhilove@126.com>
Hi Dinesh,
I tested the v7-0001-postgres_fdw-show-remote-EXPLAIN-plans-via-REMOTE.patch .
I verified the updated changes, including the new handling for a
non-existent remote table, and everything worked as expected. I also
confirmed that the existing REMOTE_PLANS functionality continues to
work correctly, and the postgres_fdw regression test passed
successfully.
I didn't notice any regressions during my testing.
Regards,
solai
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-08-07 01:27 Yilin Zhang <jiezhilove@126.com>
parent: Dinesh Salve <cooltodinesh@gmail.com>
2 siblings, 0 replies; 31+ messages in thread
From: Yilin Zhang @ 2026-08-07 01:27 UTC (permalink / raw)
To: Dinesh Salve <cooltodinesh@gmail.com>; +Cc: solai v <solai.cdac@gmail.com>; Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>; Sami Imseih <samimseih@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, "Jeff Davis" <pgsql@j-davis.com>
At 2026-08-05 18:47:51, "Dinesh Salve" <cooltodinesh@gmail.com> wrote:
Thanks a lot Solai for testing the patch, appreciate it.
Hi Bharath,
Thanks for the inputs, attached v7 patch to make review easier.
> IMO, we don't need to print all the flavors of explain plans
I have removed formatting related tests from file postgres_fdw.sql and moved to a separate file remote_plans_formats.sql.
We still need tests around formatting as my changes introduce some new elements.
> Another point, why are we not supporting explain analyze?
This will be part of follow-up work, I wanted agreement on the shape first from the community.
One design I considered is an auto_explain-style GUC asking the remote to emit the plan for the statement it is already
running, but we cannot assume an arbitrary foreign server has that, so it needs a fallback and more thought.
> 1/ Why not get the extension id at once in _PG_init
Fixed, also I moved all the EXPLAIN plumbing into postgres_fdw.c behind postgres_fdw_explain_init(), called from
_PG_init. The extension id, the saved hook pointers and both hook functions are now static.
Addressed other comments regarding documentation around GENERIC_PLAN option and added error case handling non-existent remote table.
Hi,
Thanks for Dinesh's recent patch, LGTM.
Best regards,
--
Yilin Zhang
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-08-13 07:30 Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
parent: Dinesh Salve <cooltodinesh@gmail.com>
2 siblings, 1 reply; 31+ messages in thread
From: Bharath Rupireddy @ 2026-08-13 07:30 UTC (permalink / raw)
To: Dinesh Salve <cooltodinesh@gmail.com>; +Cc: solai v <solai.cdac@gmail.com>; Sami Imseih <samimseih@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>; Yilin Zhang <jiezhilove@126.com>
Hi,
On Wed, Aug 5, 2026 at 3:48 AM Dinesh Salve <cooltodinesh@gmail.com> wrote:
>
> Thanks for the inputs, attached v7 patch to make review easier.
Thanks for the patch.
I have a couple of design questions before proceeding with the patch review.
+ /*
+ * The deparsed SQL may contain $n placeholders, which a plain remote
+ * EXPLAIN cannot plan: it fails with "there is no parameter $1". We
+ * therefore force GENERIC_PLAN, which is only available from PG 16.
+ */
I understand that reasoning, but why always enforce GENERIC_PLAN? When
there are no placeholders in the query, sending it seems fine but
unnecessary. I looked at the code comment around fdw_exprs in
postgresGetForeignPlan() and it looks like when there are placeholders
it would tell us that. Can we use that to skip enforcing the option
when there are none? Am I missing something? Was this discussed
upthread?
> > Another point, why are we not supporting explain analyze?
> This will be part of follow-up work, I wanted agreement on the shape first from the community.
> One design I considered is an auto_explain-style GUC asking the remote to emit the plan for the statement it is already
> running, but we cannot assume an arbitrary foreign server has that, so it needs a fallback and more thought.
Having the remote EXPLAIN support first makes sense. However, having a
high-level design for EXPLAIN ANALYZE support would make the feature
more concrete. IIUC, is the difficulty here that since GENERIC_PLAN is
always enforced and it is mutually exclusive with ANALYZE, it makes it
harder? Am I missing something? Are there any other issues?
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
^ permalink raw reply [nested|flat] 31+ messages in thread
* Re: explain plans for foreign servers
@ 2026-09-13 14:14 Dinesh Salve <cooltodinesh@gmail.com>
parent: Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
0 siblings, 0 replies; 31+ messages in thread
From: Dinesh Salve @ 2026-09-13 14:14 UTC (permalink / raw)
To: Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>; +Cc: solai v <solai.cdac@gmail.com>; Sami Imseih <samimseih@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@postgresql.org, Jeff Davis <pgsql@j-davis.com>; Yilin Zhang <jiezhilove@126.com>
Hi Bharath,
> Having the remote EXPLAIN support first makes sense. However, having a
> high-level design for EXPLAIN ANALYZE support would make the feature
> more concrete.
In this thread, a possible high level design for EXPLAIN ANALYZE support
was discussed and here is the one of approach. Idea is to capture the plan
of the remote statement that postgres_fdw already executes, rather than
issuing a separate remote EXPLAIN ANALYZE. The remote backend could use an
auto_explain style facility to retain the completed plan, including runtime
statistics, at ExecutorEnd or when the FDW cursor is closed.
After completing the remote query, postgres_fdw would either -
1. issue a separate statement to retrieve that stored plan and associate it
with the corresponding local plan-node ID.
2. Or a new guc set on remote connection can request remote Postgresql to
transport the plan through NOTICE.
Transporting the plan through NOTICE is fragile, while returning an
additional result set conflicts with the extended query protocol, so a
dedicated retrieval function from approach 1 or separate protocol mechanism
for this would be preferable. This design would require explicit capability
detection on remote PostgreSQL server. GENERIC_PLAN is only an additional
constraint for queries containing placeholders: it need not be combined
with ANALYZE as here we capture the actual plan using the bound parameter
values from the original remote execution.
I am proposing we expose the remote_plans option now as that feature itself
would make our user's life a bit easy and in parallel I will groom this
design approach on top of other suggestions if any.
Updated the patch to add `GENERIC_PLAN` only when the remote SQL contains
parameter placeholders. Placeholder detection uses fdw_exprs as suggested.
Thank,
Dinesh
Attachments:
v8-0001-postgres_fdw-show-remote-EXPLAIN-plans-via-REMOTE.patch (application/octet-stream, 49.3K) download
From cd72b15d4a86eb165e3cb8cb381a6ae55778a74a Mon Sep 17 00:00:00 2001
From: Dinesh Salve <cooltodinesh@gmail.com>
Date: Thu, 20 Aug 2026 20:03:28 +0530
Subject: [PATCH v8] postgres_fdw: show remote EXPLAIN plans via REMOTE_PLANS
option
Add a REMOTE_PLANS option to EXPLAIN that, for every foreign scan or
foreign modification, runs EXPLAIN on the remote server for the
corresponding remote query and prints the result in a "Remote Plans"
section keyed by the local plan node id.
The remote query that postgres_fdw sends can contain $n parameter
placeholders, which a plain remote EXPLAIN cannot plan and fails with
"there is no parameter $1". For statements with placeholders,
REMOTE_PLANS adds GENERIC_PLAN to the remote EXPLAIN so that the statement
can be planned without bound values. Statements without placeholders do
not need GENERIC_PLAN and are sent without it.
For foreign scans and direct modifications, the ForeignScan node's
fdw_exprs list identifies whether the deparsed query has parameters.
Ordinary UPDATE and DELETE statements always have a parameter for ctid.
For an ordinary INSERT, parameters are present only when at least one
target attribute is not generated, since generated attributes are
deparsed as DEFAULT.
GENERIC_PLAN is only available from PostgreSQL 16, so REMOTE_PLANS
requires a server of that version or later only for statements containing
placeholders.
REMOTE_PLANS cannot be combined with ANALYZE. All user-specified EXPLAIN
options (other than REMOTE_PLANS and GENERIC_PLAN) are forwarded to the
remote server as-is. If the remote server does not recognize a forwarded
option, it reports an error.
The option is registered, and the EXPLAIN hooks it needs are installed,
by postgres_fdw_explain_init(), which _PG_init calls. The work is split
across three hooks: explain_validate_options_hook rejects REMOTE_PLANS
together with ANALYZE and records the user's option list for forwarding,
explain_per_node_hook labels each node with its plan node id, and
explain_per_plan_hook prints the remote plans collected while the plan
was walked. Each of these chains to the hook it replaced, so other
modules using the same hooks keep working regardless of the order in
which the modules are loaded.
Since the library is loaded on demand, the option is only recognized once
postgres_fdw has been loaded into the session, whether by an earlier query
against a foreign table, by LOAD, or by a preload GUC. Note that CREATE
EXTENSION alone does not load it into the current session.
Tests for the option itself live alongside the existing tests for the
plans they report on, in postgres_fdw.sql. The non-text output formats
are covered separately in remote_plans_formats.sql, so that the volume of
JSON/XML/YAML output does not swamp the main test file.
---
contrib/postgres_fdw/Makefile | 2 +-
.../postgres_fdw/expected/postgres_fdw.out | 219 +++++++++
.../expected/remote_plans_formats.out | 114 +++++
contrib/postgres_fdw/meson.build | 1 +
contrib/postgres_fdw/option.c | 3 +
contrib/postgres_fdw/postgres_fdw.c | 440 +++++++++++++++++-
contrib/postgres_fdw/postgres_fdw.h | 1 +
contrib/postgres_fdw/sql/postgres_fdw.sql | 56 +++
.../postgres_fdw/sql/remote_plans_formats.sql | 19 +
doc/src/sgml/postgres-fdw.sgml | 101 ++++
src/tools/pgindent/typedefs.list | 2 +
11 files changed, 945 insertions(+), 13 deletions(-)
create mode 100644 contrib/postgres_fdw/expected/remote_plans_formats.out
create mode 100644 contrib/postgres_fdw/sql/remote_plans_formats.sql
diff --git a/contrib/postgres_fdw/Makefile b/contrib/postgres_fdw/Makefile
index b8c78b58804..671f82cdb42 100644
--- a/contrib/postgres_fdw/Makefile
+++ b/contrib/postgres_fdw/Makefile
@@ -16,7 +16,7 @@ SHLIB_LINK_INTERNAL = $(libpq)
EXTENSION = postgres_fdw
DATA = postgres_fdw--1.0.sql postgres_fdw--1.0--1.1.sql postgres_fdw--1.1--1.2.sql postgres_fdw--1.2--1.3.sql
-REGRESS = postgres_fdw query_cancel
+REGRESS = postgres_fdw remote_plans_formats query_cancel
ISOLATION = eval_plan_qual
ISOLATION_OPTS = --load-extension=postgres_fdw
TAP_TESTS = 1
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index a6295674daf..4399e18b4b4 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -471,6 +471,36 @@ SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
fixed |
(1 row)
+-- with WHERE clause and REMOTE_PLANS
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------
+ Foreign Scan on public.ft1 t1
+ Output: c1, c2, c3, c4, c5, c6, c7, c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = 101))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = 101)
+(10 rows)
+
+-- an error raised by the remote EXPLAIN is reported to the client; without
+-- REMOTE_PLANS this plan never contacts the remote server at all
+CREATE FOREIGN TABLE remote_plans_bad (c1 int)
+ SERVER loopback OPTIONS (schema_name 'S 1', table_name 'no_such_table');
+EXPLAIN (COSTS OFF) SELECT * FROM remote_plans_bad;
+ QUERY PLAN
+----------------------------------
+ Foreign Scan on remote_plans_bad
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, COSTS OFF) SELECT * FROM remote_plans_bad;
+ERROR: relation "S 1.no_such_table" does not exist
+CONTEXT: remote SQL command: EXPLAIN (costs off) SELECT c1 FROM "S 1".no_such_table
+DROP FOREIGN TABLE remote_plans_bad;
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -646,6 +676,57 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2
110 | 110 | 110
(10 rows)
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------------------------------------
+ Foreign Scan
+ Output: t1.c1, t2.c1
+ Relations: (public.ft1 t1) INNER JOIN (public.ft2 t2)
+ Remote SQL: SELECT r1."C 1", r2."C 1" FROM ("S 1"."T 1" r1 INNER JOIN "S 1"."T 1" r2 ON (((r2."C 1" = r1."C 1")) AND ((r1.c2 = 10))))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Seq Scan on "S 1"."T 1" r2
+ Output: r2."C 1", r2."C 1"
+ Filter: (r2.c2 = 10)
+(11 rows)
+
+-- Tables on multiple foreign connections: ft5 lives on server loopback and
+-- ft6 on server loopback2, so the join cannot be pushed down as a single
+-- foreign join. Each side is scanned over its own connection, so REMOTE_PLANS
+-- must collect and print one remote plan per connection.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) WHERE t1.c1 = 10;
+ QUERY PLAN
+------------------------------------------------------------------
+ Nested Loop
+ Disabled: true
+ Output: t1.c1, t2.c1
+ Plan Node ID: 0
+ -> Foreign Scan on public.ft5 t1
+ Output: t1.c1, t1.c2, t1.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 4" WHERE ((c1 = 10))
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft6 t2
+ Output: t2.c1, t2.c2, t2.c3
+ Remote SQL: SELECT c1 FROM "S 1"."T 4" WHERE ((c1 = 10))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Seq Scan on "S 1"."T 4"
+ Output: c1
+ Filter: ("T 4".c1 = 10)
+ Plan Node ID 2:
+ Seq Scan on "S 1"."T 4"
+ Output: c1
+ Filter: ("T 4".c1 = 10)
+(22 rows)
+
RESET enable_hashjoin;
RESET enable_nestloop;
-- Test executing assertion in estimate_path_cost_size() that makes sure that
@@ -790,6 +871,32 @@ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
47 | 7 | 00047 | Tue Feb 17 00:00:00 1970 PST | Tue Feb 17 00:00:00 1970 | 7 | 7 | foo | 7 | 7 | 00007 | Thu Jan 08 00:00:00 1970 PST | Thu Jan 08 00:00:00 1970 | 7 | 7 | foo
(1 row)
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+ QUERY PLAN
+-------------------------------------------------------------------------------------------------------------
+ Nested Loop
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8, b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Plan Node ID: 0
+ -> Index Scan using t1_pkey on "S 1"."T 1" a
+ Output: a."C 1", a.c2, a.c3, a.c4, a.c5, a.c6, a.c7, a.c8
+ Index Cond: (a."C 1" = 47)
+ Plan Node ID: 1
+ -> Foreign Scan on public.ft2 b
+ Output: b.c1, b.c2, b.c3, b.c4, b.c5, b.c6, b.c7, b.c8
+ Remote SQL: SELECT "C 1", c2, c3, c4, c5, c6, c7, c8 FROM "S 1"."T 1" WHERE (("C 1" = $1::integer))
+ Plan Node ID: 2
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Scan using t1_pkey on "S 1"."T 1"
+ Output: "C 1", c2, c3, c4, c5, c6, c7, c8
+ Index Cond: ("T 1"."C 1" = $1)
+(17 rows)
+
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM ft2 a, ft2 b
@@ -5816,6 +5923,45 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
Remote SQL: SELECT r5."C 1", r6.c1 FROM ("S 1"."T 1" r5 INNER JOIN "S 1"."T 3" r6 ON (((r5."C 1" = r6.c1)))) ORDER BY r5."C 1" ASC NULLS LAST
(13 rows)
+-- EXPLAIN with REMOTE_PLANS
+-- REMOTE_PLANS cannot be combined with ANALYZE
+EXPLAIN (REMOTE_PLANS, COSTS OFF, ANALYZE)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ERROR: EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together
+EXPLAIN (REMOTE_PLANS, COSTS OFF)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+ QUERY PLAN
+-------------------------------------------------------
+ Limit
+ Plan Node ID: 0
+ -> Merge Semi Join
+ Merge Cond: (ft1.c1 = ft2_1.c1)
+ Plan Node ID: 1
+ -> Foreign Scan
+ Relations: (ft1) INNER JOIN (ft2)
+ Plan Node ID: 2
+ -> Foreign Scan
+ Relations: (ft2 ft2_1) INNER JOIN (ft4)
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 2:
+ Index Only Scan using t1_pkey on "T 1" r2
+ Plan Node ID 3:
+ Merge Join
+ Merge Cond: (r5."C 1" = r6.c1)
+ -> Index Only Scan using t1_pkey on "T 1" r5
+ -> Sort
+ Sort Key: r6.c1
+ -> Seq Scan on "T 3" r6
+(22 rows)
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -7090,6 +7236,25 @@ SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
(3 rows)
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with REMOTE_PLANS
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
+ QUERY PLAN
+---------------------------------------------------------------------------------------
+ Update on public.ft2
+ Plan Node ID: 0
+ -> Foreign Update on public.ft2
+ Remote SQL: UPDATE "S 1"."T 1" SET c2 = (c2 + 300) WHERE ((("C 1" % 10) = 3))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Update on "S 1"."T 1"
+ -> Seq Scan on "S 1"."T 1"
+ Output: (c2 + 300), ctid
+ Filter: (("T 1"."C 1" % 10) = 3)
+(12 rows)
+
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id;
@@ -13188,6 +13353,58 @@ SELECT * FROM insert_tbl ORDER BY a;
2505 | 505 | bar
(2 rows)
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+ QUERY PLAN
+-------------------------------------------------------------------------
+ Insert on public.insert_tbl
+ Remote SQL: INSERT INTO public.base_tbl4(a, b, c) VALUES ($1, $2, $3)
+ Batch Size: 1
+ Plan Node ID: 0
+ -> Append
+ Plan Node ID: 1
+ -> Seq Scan on public.local_tbl
+ Output: local_tbl.a, local_tbl.b, local_tbl.c
+ Plan Node ID: 2
+ -> Async Foreign Scan on public.remote_tbl
+ Output: remote_tbl.a, remote_tbl.b, remote_tbl.c
+ Remote SQL: SELECT a, b, c FROM public.base_tbl3
+ Plan Node ID: 3
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Insert on public.base_tbl4
+ -> Result
+ Output: $1, $2, $3
+ Plan Node ID 3:
+ Seq Scan on public.base_tbl3
+ Output: a, b, c
+(22 rows)
+
+-- An INSERT whose target list contains only generated columns has no
+-- placeholders, despite having a nonempty targetAttrs list.
+CREATE TABLE generated_tbl (a int GENERATED ALWAYS AS (1) STORED);
+CREATE FOREIGN TABLE generated_ft (a int GENERATED ALWAYS AS (1) STORED)
+ SERVER loopback OPTIONS (table_name 'generated_tbl');
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO generated_ft DEFAULT VALUES;
+ QUERY PLAN
+--------------------------------------------------------------------
+ Insert on public.generated_ft
+ Remote SQL: INSERT INTO public.generated_tbl(a) VALUES (DEFAULT)
+ Batch Size: 1
+ Plan Node ID: 0
+ -> Result
+ Output: NULL::integer
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Insert on public.generated_tbl
+ -> Result
+ Output: NULL::integer
+(13 rows)
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
@@ -13233,8 +13450,10 @@ DELETE FROM join_tbl;
DROP TABLE local_tbl;
DROP FOREIGN TABLE remote_tbl;
DROP FOREIGN TABLE insert_tbl;
+DROP FOREIGN TABLE generated_ft;
DROP TABLE base_tbl3;
DROP TABLE base_tbl4;
+DROP TABLE generated_tbl;
RESET enable_mergejoin;
RESET enable_hashjoin;
-- Test that UPDATE/DELETE with inherited target works with async_capable enabled
diff --git a/contrib/postgres_fdw/expected/remote_plans_formats.out b/contrib/postgres_fdw/expected/remote_plans_formats.out
new file mode 100644
index 00000000000..37b64b44f77
--- /dev/null
+++ b/contrib/postgres_fdw/expected/remote_plans_formats.out
@@ -0,0 +1,114 @@
+-- ===================================================================
+-- test EXPLAIN (REMOTE_PLANS) in the non-text output formats
+-- ===================================================================
+-- The behaviour of REMOTE_PLANS itself is tested in postgres_fdw.sql, next
+-- to the tests for the plans it reports on. This file only covers how the
+-- collected remote plans are embedded in each output format.
+-- This runs after postgres_fdw.sql in the same database and reuses the
+-- server, user mapping and foreign tables created there.
+LOAD 'postgres_fdw';
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------------
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Foreign Scan", +
+ "Operation": "Select", +
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Relation Name": "ft1", +
+ "Alias": "t1", +
+ "Disabled": false, +
+ "Plan Node ID": 0 +
+ }, +
+ "Remote Plans": { +
+ "Plan Node ID 0": [ +
+ [ +
+ { +
+ "Plan": { +
+ "Node Type": "Index Only Scan",+
+ "Parallel Aware": false, +
+ "Async Capable": false, +
+ "Scan Direction": "Forward", +
+ "Index Name": "t1_pkey", +
+ "Relation Name": "T 1", +
+ "Alias": "T 1", +
+ "Disabled": false, +
+ "Index Cond": "(\"C 1\" = 101)"+
+ } +
+ } +
+ ] +
+ ] +
+ } +
+ } +
+ ]
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, FORMAT XML, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+------------------------------------------------------------------
+ <explain xmlns="http://www.postgresql.org/2009/explain"> +
+ <Query> +
+ <Plan> +
+ <Node-Type>Foreign Scan</Node-Type> +
+ <Operation>Select</Operation> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Relation-Name>ft1</Relation-Name> +
+ <Alias>t1</Alias> +
+ <Disabled>false</Disabled> +
+ <Plan-Node-ID>0</Plan-Node-ID> +
+ </Plan> +
+ <Remote-Plans> +
+ <Plan-Node-ID-0> +
+ <explain xmlns="http://www.postgresql.org/2009/explain">+
+ <Query> +
+ <Plan> +
+ <Node-Type>Index Only Scan</Node-Type> +
+ <Parallel-Aware>false</Parallel-Aware> +
+ <Async-Capable>false</Async-Capable> +
+ <Scan-Direction>Forward</Scan-Direction> +
+ <Index-Name>t1_pkey</Index-Name> +
+ <Relation-Name>T 1</Relation-Name> +
+ <Alias>T 1</Alias> +
+ <Disabled>false</Disabled> +
+ <Index-Cond>("C 1" = 101)</Index-Cond> +
+ </Plan> +
+ </Query> +
+ </explain> +
+ </Plan-Node-ID-0> +
+ </Remote-Plans> +
+ </Query> +
+ </explain>
+(1 row)
+
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
+ QUERY PLAN
+-----------------------------------------
+ - Plan: +
+ Node Type: "Foreign Scan" +
+ Operation: "Select" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Relation Name: "ft1" +
+ Alias: "t1" +
+ Disabled: false +
+ Plan Node ID: 0 +
+ Remote Plans: +
+ Plan Node ID 0: +
+ - Plan: +
+ Node Type: "Index Only Scan" +
+ Parallel Aware: false +
+ Async Capable: false +
+ Scan Direction: "Forward" +
+ Index Name: "t1_pkey" +
+ Relation Name: "T 1" +
+ Alias: "T 1" +
+ Disabled: false +
+ Index Cond: "(\"C 1\" = 101)"
+(1 row)
+
diff --git a/contrib/postgres_fdw/meson.build b/contrib/postgres_fdw/meson.build
index 3e2ed06b766..6a9bb651d02 100644
--- a/contrib/postgres_fdw/meson.build
+++ b/contrib/postgres_fdw/meson.build
@@ -38,6 +38,7 @@ tests += {
'regress': {
'sql': [
'postgres_fdw',
+ 'remote_plans_formats',
'query_cancel',
],
'regress_args': ['--dlpath', meson.project_build_root() / 'src/test/regress'],
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 5b539c4eeef..67ac0825947 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -592,4 +592,7 @@ _PG_init(void)
NULL);
MarkGUCPrefixReserved("postgres_fdw");
+
+ /* Register EXPLAIN (REMOTE_PLANS) and install the hooks it needs. */
+ postgres_fdw_explain_init();
}
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index adfdb91cc20..2a42924962d 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -19,6 +19,7 @@
#include "access/table.h"
#include "catalog/pg_opfamily.h"
#include "commands/defrem.h"
+#include "commands/explain.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "commands/vacuum.h"
@@ -165,6 +166,44 @@ enum FdwDirectModifyPrivateIndex
FdwDirectModifyPrivateMinRTIndex,
};
+/*
+ * One remote plan collected while walking the local plan, identified by the
+ * plan node id of the local node that produced the remote query.
+ */
+typedef struct PgFdwExplainRemotePlans
+{
+ int plan_node_id;
+ StringInfoData explain_plan;
+} PgFdwExplainRemotePlans;
+
+/*
+ * Our private state within an ExplainState, created on demand while the
+ * EXPLAIN options are parsed.
+ */
+typedef struct PgFdwExplainState
+{
+ List *all_remote_plans;
+
+ /* EXPLAIN options */
+ bool remote_plans;
+ List *options; /* raw user DefElem list, for forwarding */
+} PgFdwExplainState;
+
+/*
+ * Our slot in an ExplainState's extension state array, assigned once by
+ * postgres_fdw_explain_init().
+ */
+static int postgres_fdw_extension_id;
+
+/*
+ * Previously installed EXPLAIN hooks. Every hook function we install must
+ * call the previous one, so that other modules using the same hooks keep
+ * working no matter what order the modules happen to be loaded in.
+ */
+static explain_per_node_hook_type prev_explain_per_node_hook = NULL;
+static explain_per_plan_hook_type prev_explain_per_plan_hook = NULL;
+static explain_validate_options_hook_type prev_explain_validate_options_hook = NULL;
+
/*
* Execution state of a foreign scan using postgres_fdw.
*/
@@ -3067,6 +3106,121 @@ postgresEndDirectModify(ForeignScanState *node)
/* MemoryContext will be deleted automatically. */
}
+static void
+postgresExplainStatement(int plan_node_id,
+ PgFdwExplainState *pgfdw_explain_state,
+ PGconn *conn,
+ char *sql,
+ bool has_params)
+{
+ PGresult *volatile res = NULL;
+ StringInfoData explain_sql;
+ int remote_version = PQserverVersion(conn);
+ bool first = true;
+ ListCell *lc;
+
+ /*
+ * The deparsed SQL may contain $n placeholders, which a plain remote
+ * EXPLAIN cannot plan: it fails with "there is no parameter $1". We
+ * therefore force GENERIC_PLAN when placeholders are present and that
+ * option is only available from PG 16.
+ */
+ if (has_params && remote_version < 160000)
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("EXPLAIN option REMOTE_PLANS requires a remote server version of 16 or later for parameterized queries"),
+ errdetail("The remote server version is %d.", remote_version));
+
+ /* Forward user-specified options as-is. */
+ initStringInfo(&explain_sql);
+ appendStringInfoString(&explain_sql, "EXPLAIN");
+
+ if (has_params)
+ {
+ appendStringInfoString(&explain_sql, " (GENERIC_PLAN TRUE");
+ first = false;
+ }
+
+ foreach(lc, pgfdw_explain_state->options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0 ||
+ strcmp(opt->defname, "generic_plan") == 0)
+ continue;
+
+ appendStringInfoString(&explain_sql, first ? " (" : ", ");
+ first = false;
+
+ if (opt->arg == NULL)
+ appendStringInfoString(&explain_sql, opt->defname);
+ else
+ appendStringInfo(&explain_sql, "%s %s", opt->defname,
+ defGetString(opt));
+ }
+
+ if (!first)
+ appendStringInfoChar(&explain_sql, ')');
+ appendStringInfo(&explain_sql, " %s", sql);
+
+ PG_TRY();
+ {
+ int numrows,
+ i;
+ PgFdwExplainRemotePlans *explain;
+
+ /* Run the query and collect the remote plan */
+ res = pgfdw_exec_query(conn, explain_sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, explain_sql.data);
+
+ explain = (PgFdwExplainRemotePlans *) palloc(sizeof(PgFdwExplainRemotePlans));
+ initStringInfo(&explain->explain_plan);
+
+ numrows = PQntuples(res);
+
+ for (i = 0; i < numrows; i++)
+ appendStringInfo(&explain->explain_plan, "%s\n", PQgetvalue(res, i, 0));
+
+ if (explain->explain_plan.len > 0 && explain->explain_plan.data[explain->explain_plan.len - 1] == '\n')
+ explain->explain_plan.data[--explain->explain_plan.len] = '\0';
+
+ explain->plan_node_id = plan_node_id;
+ pgfdw_explain_state->all_remote_plans = lappend(pgfdw_explain_state->all_remote_plans, explain);
+ }
+ PG_FINALLY();
+ {
+ if (res)
+ PQclear(res);
+ }
+ PG_END_TRY();
+
+ pfree(explain_sql.data);
+}
+
+/*
+ * explain_remote_query
+ * Helper function to get connection and execute remote EXPLAIN
+ */
+static void
+explain_remote_query(int plan_node_id,
+ PgFdwExplainState *pgfdw_explain_state,
+ Oid foreign_table_oid, char *sql,
+ bool has_params)
+{
+ UserMapping *user;
+ PGconn *conn;
+ ForeignTable *table;
+
+ table = GetForeignTable(foreign_table_oid);
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+
+ postgresExplainStatement(plan_node_id, pgfdw_explain_state, conn, sql,
+ has_params);
+ ReleaseConnection(conn);
+}
+
/*
* postgresExplainForeignScan
* Produce extra output for EXPLAIN of a ForeignScan on a foreign table
@@ -3076,6 +3230,12 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
List *fdw_private = plan->fdw_private;
+ PgFdwExplainState *pgfdw_explain_state;
+ char *sql;
+ Oid foreign_table_oid = InvalidOid;
+
+ if (node->ss.ss_currentRelation)
+ foreign_table_oid = RelationGetRelid(node->ss.ss_currentRelation);
/*
* Identify foreign scans that are really joins or upper relations. The
@@ -3196,6 +3356,12 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
Assert(rte->rtekind == RTE_RELATION);
+ /*
+ * Save first table OID for getting server connection.
+ */
+ if (!OidIsValid(foreign_table_oid))
+ foreign_table_oid = rte->relid;
+
/*
* This logic should agree with explain.c's
* ExplainTargetRel
@@ -3228,16 +3394,25 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
ExplainPropertyText("Relations", relations.data, es);
}
+ sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
+
/*
* Add remote query, when VERBOSE option is specified.
*/
if (es->verbose)
- {
- char *sql;
-
- sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+
+ /* If we don't have a foreign table oid by now, something went wrong */
+ Assert(foreign_table_oid);
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ foreign_table_oid,
+ sql,
+ plan->fdw_exprs != NIL);
}
/*
@@ -3251,11 +3426,13 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
int subplan_index,
ExplainState *es)
{
+ char *sql = strVal(list_nth(fdw_private,
+ FdwModifyPrivateUpdateSql));
+ PgFdwExplainState *pgfdw_explain_state;
+ bool has_params;
+
if (es->verbose)
{
- char *sql = strVal(list_nth(fdw_private,
- FdwModifyPrivateUpdateSql));
-
ExplainPropertyText("Remote SQL", sql, es);
/*
@@ -3265,6 +3442,57 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
if (rinfo->ri_BatchSize > 0)
ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
}
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ {
+ switch (mtstate->operation)
+ {
+ case CMD_UPDATE:
+ case CMD_DELETE:
+ /* The row identifier is always sent as $1. */
+ has_params = true;
+ break;
+ case CMD_INSERT:
+ {
+ TupleDesc tupdesc = RelationGetDescr(rinfo->ri_RelationDesc);
+ List *target_attrs = (List *) list_nth(fdw_private,
+ FdwModifyPrivateTargetAttnums);
+ ListCell *lc;
+
+ /*
+ * A nonempty target_attrs list does not necessarily imply
+ * parameters. Generated columns are deparsed as DEFAULT.
+ * The INSERT has parameters only if at least one target
+ * attribute is not generated.
+ */
+ has_params = false;
+ foreach(lc, target_attrs)
+ {
+ AttrNumber attnum = lfirst_int(lc);
+ CompactAttribute *attr =
+ TupleDescCompactAttr(tupdesc, attnum - 1);
+
+ /* '\0' identifies an ordinary, non-generated column. */
+ if (attr->attgenerated == '\0')
+ {
+ has_params = true;
+ break;
+ }
+ }
+ break;
+ }
+ default:
+ elog(ERROR, "unexpected operation: %d",
+ (int) mtstate->operation);
+ }
+
+ explain_remote_query(mtstate->ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ rinfo->ri_RelationDesc->rd_rel->oid,
+ sql,
+ has_params);
+ }
}
/*
@@ -3275,15 +3503,25 @@ postgresExplainForeignModify(ModifyTableState *mtstate,
static void
postgresExplainDirectModify(ForeignScanState *node, ExplainState *es)
{
+ ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
List *fdw_private;
char *sql;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ fdw_private = plan->fdw_private;
+ sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
if (es->verbose)
- {
- fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
- sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
ExplainPropertyText("Remote SQL", sql, es);
- }
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+
+ if (pgfdw_explain_state && pgfdw_explain_state->remote_plans)
+ explain_remote_query(node->ss.ps.plan->plan_node_id,
+ pgfdw_explain_state,
+ RelationGetRelid(node->ss.ss_currentRelation),
+ sql,
+ plan->fdw_exprs != NIL);
}
/*
@@ -9296,3 +9534,181 @@ get_batch_size_option(Relation rel)
return batch_size;
}
+
+/*
+ * Get the PgFdwExplainState structure from an ExplainState; if there is
+ * none, create one, attach it to the ExplainState, and return it.
+ */
+static PgFdwExplainState *
+pgfdw_ensure_options(ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+
+ if (pgfdw_explain_state == NULL)
+ {
+ pgfdw_explain_state = palloc0(sizeof(PgFdwExplainState));
+ SetExplainExtensionState(es, postgres_fdw_extension_id, pgfdw_explain_state);
+ pgfdw_explain_state->all_remote_plans = NIL;
+ }
+
+ return pgfdw_explain_state;
+}
+
+/*
+ * Parse handler for EXPLAIN (REMOTE_PLANS).
+ */
+static void
+pgfdw_remote_plans_apply(ExplainState *es, DefElem *opt, ParseState *pstate)
+{
+ PgFdwExplainState *options = pgfdw_ensure_options(es);
+
+ options->remote_plans = defGetBoolean(opt);
+}
+
+static void
+postgresExplainValidateOptions(ExplainState *es, List *options, ParseState *pstate)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state = NULL;
+
+ if (prev_explain_validate_options_hook)
+ (*prev_explain_validate_options_hook) (es, options, pstate);
+
+ foreach(lc, options)
+ {
+ DefElem *opt = (DefElem *) lfirst(lc);
+
+ if (strcmp(opt->defname, "remote_plans") == 0)
+ {
+ if (defGetBoolean(opt) && es->analyze)
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("EXPLAIN options REMOTE_PLANS and ANALYZE cannot be used together"));
+
+ pgfdw_explain_state = pgfdw_ensure_options(es);
+ pgfdw_explain_state->options = options;
+ }
+ }
+}
+
+static void
+postgresExplainPerNode(PlanState *planstate, List *ancestors,
+ const char *relationship, const char *plan_name,
+ ExplainState *es)
+{
+ PgFdwExplainState *pgfdw_explain_state;
+
+ if (prev_explain_per_node_hook)
+ (*prev_explain_per_node_hook) (planstate, ancestors, relationship,
+ plan_name, es);
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+
+ if (pgfdw_explain_state == NULL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ ExplainPropertyInteger("Plan Node ID", NULL, planstate->plan->plan_node_id, es);
+}
+
+static void
+pgfdwFormatRemotePlan(PgFdwExplainRemotePlans *explain,
+ ExplainState *es,
+ int plan_node_id)
+{
+ char *token;
+ StringInfoData remote_plan_name;
+
+ initStringInfo(&remote_plan_name);
+ appendStringInfo(&remote_plan_name, "Plan Node ID %d", plan_node_id);
+
+ ExplainOpenGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Plan Node ID %d:", plan_node_id);
+ appendStringInfoString(es->str, "\n");
+ }
+
+ while ((token = strsep(&explain->explain_plan.data, "\n")) != NULL)
+ {
+ if (es->format == EXPLAIN_FORMAT_JSON ||
+ es->format == EXPLAIN_FORMAT_YAML)
+ appendStringInfoString(es->str, "\n");
+
+ appendStringInfoSpaces(es->str, (es->indent == 0) ? 2 : es->indent * 2);
+ appendStringInfoString(es->str, token);
+
+ if (es->format == EXPLAIN_FORMAT_XML ||
+ es->format == EXPLAIN_FORMAT_TEXT)
+ appendStringInfoString(es->str, "\n");
+ }
+
+ ExplainCloseGroup(remote_plan_name.data, remote_plan_name.data, false, es);
+ pfree(remote_plan_name.data);
+}
+
+static void
+postgresExplainPerPlan(PlannedStmt *plannedstmt,
+ IntoClause *into,
+ ExplainState *es,
+ const char *queryString,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv)
+{
+ ListCell *lc;
+ PgFdwExplainState *pgfdw_explain_state;
+
+ if (prev_explain_per_plan_hook)
+ (*prev_explain_per_plan_hook) (plannedstmt, into, es, queryString,
+ params, queryEnv);
+
+ pgfdw_explain_state = GetExplainExtensionState(es, postgres_fdw_extension_id);
+
+ if (pgfdw_explain_state == NULL ||
+ pgfdw_explain_state->all_remote_plans == NIL ||
+ !pgfdw_explain_state->remote_plans)
+ return;
+
+ ExplainOpenGroup("Remote Plans", "Remote Plans", true, es);
+ if (es->format == EXPLAIN_FORMAT_TEXT)
+ {
+ appendStringInfo(es->str, "Remote Plans:\n");
+ appendStringInfo(es->str, "-------------\n");
+ }
+
+ /* Process every remote plan captured */
+ foreach(lc, pgfdw_explain_state->all_remote_plans)
+ {
+ PgFdwExplainRemotePlans *explain = (PgFdwExplainRemotePlans *) lfirst(lc);
+
+ pgfdwFormatRemotePlan(explain,
+ es,
+ explain->plan_node_id);
+ }
+
+ ExplainCloseGroup("Remote Plans", "Remote Plans", true, es);
+}
+
+/*
+ * Register EXPLAIN (REMOTE_PLANS) and install the hooks that implement it.
+ * Called from _PG_init.
+ */
+void
+postgres_fdw_explain_init(void)
+{
+ postgres_fdw_extension_id = GetExplainExtensionId("postgres_fdw");
+
+ RegisterExtensionExplainOption("remote_plans", pgfdw_remote_plans_apply,
+ GUCCheckBooleanExplainOption);
+
+ /* Install our EXPLAIN hooks, saving the previous ones for chaining. */
+ prev_explain_per_node_hook = explain_per_node_hook;
+ explain_per_node_hook = postgresExplainPerNode;
+ prev_explain_per_plan_hook = explain_per_plan_hook;
+ explain_per_plan_hook = postgresExplainPerPlan;
+ prev_explain_validate_options_hook = explain_validate_options_hook;
+ explain_validate_options_hook = postgresExplainValidateOptions;
+}
diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h
index da7da1c2ea9..f1eea65fb21 100644
--- a/contrib/postgres_fdw/postgres_fdw.h
+++ b/contrib/postgres_fdw/postgres_fdw.h
@@ -165,6 +165,7 @@ typedef enum PgFdwSamplingMethod
extern int set_transmission_modes(void);
extern void reset_transmission_modes(int nestlevel);
extern void process_pending_request(AsyncRequest *areq);
+extern void postgres_fdw_explain_init(void);
/* in connection.c */
extern PGconn *GetConnection(UserMapping *user, bool will_prep_stmt,
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index eaeb90485e8..063d6c5f21b 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -311,6 +311,15 @@ SELECT * FROM ft1 t1 WHERE t1.c3 = (SELECT MAX(c3) FROM ft2 t2) ORDER BY c1;
WITH t1 AS (SELECT * FROM ft1 WHERE c1 <= 10) SELECT t2.c1, t2.c2, t2.c3, t2.c4 FROM t1, ft2 t2 WHERE t1.c1 = t2.c1 ORDER BY t1.c1;
-- fixed values
SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1;
+-- with WHERE clause and REMOTE_PLANS
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101;
+-- an error raised by the remote EXPLAIN is reported to the client; without
+-- REMOTE_PLANS this plan never contacts the remote server at all
+CREATE FOREIGN TABLE remote_plans_bad (c1 int)
+ SERVER loopback OPTIONS (schema_name 'S 1', table_name 'no_such_table');
+EXPLAIN (COSTS OFF) SELECT * FROM remote_plans_bad;
+EXPLAIN (REMOTE_PLANS, COSTS OFF) SELECT * FROM remote_plans_bad;
+DROP FOREIGN TABLE remote_plans_bad;
-- Test forcing the remote server to produce sorted data for a merge join.
SET enable_hashjoin TO false;
SET enable_nestloop TO false;
@@ -338,6 +347,19 @@ SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 left join ft1 t2 full join ft2
EXPLAIN (VERBOSE, COSTS OFF)
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;
+
+-- Join push-down test
+-- Ensure join conditions are pushed down to the foreign server
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c2 = 10;
+
+-- Tables on multiple foreign connections: ft5 lives on server loopback and
+-- ft6 on server loopback2, so the join cannot be pushed down as a single
+-- foreign join. Each side is scanned over its own connection, so REMOTE_PLANS
+-- must collect and print one remote plan per connection.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) WHERE t1.c1 = 10;
+
RESET enable_hashjoin;
RESET enable_nestloop;
@@ -379,6 +401,11 @@ EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c8 = 'foo'; -- can't be
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
+-- REMOTE_PLANS over a parameterized foreign scan: the deparsed remote SQL
+-- carries a $1 placeholder, which only plans on the remote side because
+-- REMOTE_PLANS forces GENERIC_PLAN.
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+ SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2;
-- check both safe and unsafe join conditions
EXPLAIN (VERBOSE, COSTS OFF)
@@ -1836,6 +1863,19 @@ SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
ORDER BY ft1.c1 LIMIT 5;
+-- EXPLAIN with REMOTE_PLANS
+-- REMOTE_PLANS cannot be combined with ANALYZE
+EXPLAIN (REMOTE_PLANS, COSTS OFF, ANALYZE)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+EXPLAIN (REMOTE_PLANS, COSTS OFF)
+SELECT ft1.c1 FROM ft1 JOIN ft2 on ft1.c1 = ft2.c1 WHERE
+ ft1.c1 IN (
+ SELECT ft2.c1 FROM ft2 JOIN ft4 ON ft2.c1 = ft4.c1)
+ ORDER BY ft1.c1 LIMIT 5;
+
-- ===================================================================
-- test writable foreign table stuff
-- ===================================================================
@@ -1919,6 +1959,9 @@ DELETE FROM fpo_part_parent
FOR PORTION OF c4 FROM '2024-06-01' TO '2024-06-15' WHERE c2 = 1; -- okay
SELECT c1, c2, c3, c4 FROM fpo_part_local ORDER BY c4;
DROP TABLE fpo_part_parent;
+-- test write on foreign tables with REMOTE_PLANS
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+UPDATE ft2 SET c2 = c2 + 300 WHERE c1 % 10 = 3;
-- Test UPDATE/DELETE with RETURNING on a three-table join
INSERT INTO ft2 (c1,c2,c3)
@@ -4571,6 +4614,17 @@ INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_t
SELECT * FROM insert_tbl ORDER BY a;
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);
+
+-- An INSERT whose target list contains only generated columns has no
+-- placeholders, despite having a nonempty targetAttrs list.
+CREATE TABLE generated_tbl (a int GENERATED ALWAYS AS (1) STORED);
+CREATE FOREIGN TABLE generated_ft (a int GENERATED ALWAYS AS (1) STORED)
+ SERVER loopback OPTIONS (table_name 'generated_tbl');
+EXPLAIN (REMOTE_PLANS, VERBOSE, COSTS OFF)
+INSERT INTO generated_ft DEFAULT VALUES;
+
-- Check with direct modify
EXPLAIN (VERBOSE, COSTS OFF)
WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *)
@@ -4584,8 +4638,10 @@ DELETE FROM join_tbl;
DROP TABLE local_tbl;
DROP FOREIGN TABLE remote_tbl;
DROP FOREIGN TABLE insert_tbl;
+DROP FOREIGN TABLE generated_ft;
DROP TABLE base_tbl3;
DROP TABLE base_tbl4;
+DROP TABLE generated_tbl;
RESET enable_mergejoin;
RESET enable_hashjoin;
diff --git a/contrib/postgres_fdw/sql/remote_plans_formats.sql b/contrib/postgres_fdw/sql/remote_plans_formats.sql
new file mode 100644
index 00000000000..0d7e25ce9a5
--- /dev/null
+++ b/contrib/postgres_fdw/sql/remote_plans_formats.sql
@@ -0,0 +1,19 @@
+-- ===================================================================
+-- test EXPLAIN (REMOTE_PLANS) in the non-text output formats
+-- ===================================================================
+-- The behaviour of REMOTE_PLANS itself is tested in postgres_fdw.sql, next
+-- to the tests for the plans it reports on. This file only covers how the
+-- collected remote plans are embedded in each output format.
+-- This runs after postgres_fdw.sql in the same database and reuses the
+-- server, user mapping and foreign tables created there.
+
+LOAD 'postgres_fdw';
+
+EXPLAIN (REMOTE_PLANS, FORMAT JSON, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
+
+EXPLAIN (REMOTE_PLANS, FORMAT XML, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
+
+EXPLAIN (REMOTE_PLANS, FORMAT YAML, COSTS OFF)
+SELECT c1 FROM ft1 t1 WHERE t1.c1 = 101;
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 80f79c017d6..b8b04552930 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -1229,6 +1229,107 @@ CREATE SUBSCRIPTION my_subscription SERVER subscription_server PUBLICATION testp
The query that is actually sent to the remote server for execution can
be examined using <command>EXPLAIN VERBOSE</command>.
</para>
+
+ <para>
+ In addition to the remote query itself, the plan that the remote server
+ chooses for that query can be examined with the
+ <literal>REMOTE_PLANS</literal> option of <command>EXPLAIN</command>.
+ For every foreign scan or foreign modification in the local plan,
+ <filename>postgres_fdw</filename> runs <command>EXPLAIN</command> on the
+ remote server for the corresponding remote query and prints the result in a
+ <literal>Remote Plans</literal> section, keyed by the plan node id of the
+ local node. For example:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS) SELECT * FROM foreign_tbl WHERE id = 42;
+ QUERY PLAN
+-----------------------------------------------------------
+ Foreign Scan on public.foreign_tbl
+ Output: id, val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = 42))
+ Plan Node ID: 0
+ Remote Plans:
+ -------------
+ Plan Node ID 0:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = 42)
+</programlisting>
+ When the local plan uses a parameterized foreign scan (for example, as
+ the inner side of a nested loop join), the remote SQL contains parameter
+ placeholders, which a plain <command>EXPLAIN</command> on the remote server
+ could not plan; it would fail with <literal>there is no parameter $1</literal>.
+ <literal>REMOTE_PLANS</literal> therefore asks the remote server for a
+ generic plan in this case:
+<programlisting>
+EXPLAIN (VERBOSE, REMOTE_PLANS, COSTS OFF)
+ SELECT * FROM local_tbl a, foreign_tbl b WHERE a.id = 1 AND b.id = a.val;
+ QUERY PLAN
+-----------------------------------------------------------
+ Nested Loop
+ Output: a.id, a.val, b.id, b.val
+ -> Seq Scan on public.local_tbl a
+ Output: a.id, a.val
+ Filter: (a.id = 1)
+ -> Foreign Scan on public.foreign_tbl b
+ Output: b.id, b.val
+ Remote SQL: SELECT id, val FROM public.tbl WHERE ((id = $1::integer))
+ Plan Node ID: 1
+ Remote Plans:
+ -------------
+ Plan Node ID 1:
+ Index Scan using tbl_pkey on public.tbl
+ Output: id, val
+ Index Cond: (tbl.id = $1)
+</programlisting>
+ </para>
+
+ <para>
+ The <literal>REMOTE_PLANS</literal> option is registered when the
+ <filename>postgres_fdw</filename> library is loaded into the session. The
+ library is loaded on demand, the first time the session plans or executes a
+ query against a foreign table, so in a session that has not yet touched a
+ foreign table the option is not recognized and
+ <command>EXPLAIN</command> reports
+ <literal>unrecognized EXPLAIN option "remote_plans"</literal>. Note that
+ <command>CREATE EXTENSION postgres_fdw</command> alone does not load the
+ library into the current session. To make the option available up front,
+ use <command>LOAD 'postgres_fdw'</command>, or list the library in
+ <xref linkend="guc-session-preload-libraries"/> or
+ <xref linkend="guc-shared-preload-libraries"/>.
+ The following restrictions apply:
+ <itemizedlist>
+ <listitem>
+ <para>
+ It cannot be combined with <literal>ANALYZE</literal>; doing so raises an
+ error. The remote query is only planned, never executed, so the foreign
+ server is not affected and no remote rows are fetched.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ For a remote query containing parameter placeholders, the remote server
+ must be running <productname>PostgreSQL</productname> 16 or later,
+ because <literal>REMOTE_PLANS</literal> uses the
+ <literal>GENERIC_PLAN</literal> option of <command>EXPLAIN</command>,
+ which was introduced in that release. As shown in the parameterized
+ example above, the plan shown for such a query is a generic plan, which
+ may differ from the plan the remote server actually uses at execution
+ time when specific parameter values are available. For a remote query
+ without parameter placeholders, <literal>GENERIC_PLAN</literal> is not
+ requested and this version restriction does not apply.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ All <command>EXPLAIN</command> options specified by the user (other than
+ <literal>REMOTE_PLANS</literal> itself and
+ <literal>GENERIC_PLAN</literal>) are forwarded to the remote server.
+ If the remote server is running an older version that does not recognize
+ a forwarded option, it will report an error.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
</sect2>
<sect2 id="postgres-fdw-remote-query-execution-environment">
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index cdf5a7d0b11..168fdc7cef2 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2286,6 +2286,8 @@ PgChecksumMode
PgFdwAnalyzeState
PgFdwConnState
PgFdwDirectModifyState
+PgFdwExplainRemotePlans
+PgFdwExplainState
PgFdwModifyState
PgFdwOption
PgFdwPathExtraData
--
2.53.0
^ permalink raw reply [nested|flat] 31+ messages in thread
end of thread, other threads:[~2026-09-13 14:14 UTC | newest]
Thread overview: 31+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2024-11-11 15:42 explain plans for foreign servers dinesh salve <cooltodinesh@gmail.com>
2024-11-12 00:33 ` Andy Fan <zhihuifan1213@163.com>
2024-11-12 10:46 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2024-11-22 21:02 ` dinesh salve <cooltodinesh@gmail.com>
2024-11-25 16:53 ` Anton Shmigirilov <a.shmigirilov@postgrespro.ru>
2024-12-14 12:49 ` dinesh salve <cooltodinesh@gmail.com>
2025-02-26 19:13 ` Sami Imseih <samimseih@gmail.com>
2025-03-05 19:00 ` Jeff Davis <pgsql@j-davis.com>
2025-03-05 19:12 ` Tom Lane <tgl@sss.pgh.pa.us>
2025-03-05 19:26 ` Sami Imseih <samimseih@gmail.com>
2025-03-05 23:24 ` Jeff Davis <pgsql@j-davis.com>
2025-11-18 03:25 ` dinesh salve <cooltodinesh@gmail.com>
2025-12-03 22:40 ` Sami Imseih <samimseih@gmail.com>
2025-12-04 00:34 ` Sami Imseih <samimseih@gmail.com>
2025-12-09 21:08 ` Sami Imseih <samimseih@gmail.com>
2026-01-07 10:00 ` dinesh salve <cooltodinesh@gmail.com>
2026-01-10 00:16 ` Sami Imseih <samimseih@gmail.com>
2026-06-19 19:04 ` dinesh salve <cooltodinesh@gmail.com>
2026-07-03 18:35 ` Sami Imseih <samimseih@gmail.com>
2026-07-04 17:07 ` dinesh salve <cooltodinesh@gmail.com>
2026-07-08 18:12 ` dinesh salve <cooltodinesh@gmail.com>
2026-07-24 03:05 ` Yilin Zhang <jiezhilove@126.com>
2026-07-27 16:04 ` Dinesh Salve <cooltodinesh@gmail.com>
2026-07-28 06:26 ` Dinesh Salve <cooltodinesh@gmail.com>
2026-08-04 20:55 ` Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
2026-08-05 10:31 ` solai v <solai.cdac@gmail.com>
2026-08-05 10:47 ` Dinesh Salve <cooltodinesh@gmail.com>
2026-08-06 07:34 ` solai v <solai.cdac@gmail.com>
2026-08-07 01:27 ` Yilin Zhang <jiezhilove@126.com>
2026-08-13 07:30 ` Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
2026-09-13 14:14 ` Dinesh Salve <cooltodinesh@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