pg.ddx.io pgsql-hackers@postgresql.org mailing list archive
help / color / mirror / Atom feedImport Statistics in postgres_fdw before resorting to sampling.
89+ messages / 8 participants
[nested] [flat]
Commits from this thread:
2026-05-16 aa1f93a338 postgres_fdw: Replace buffers in RemoteAttributeMapping with pointers.
* Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-08-12 17:02 Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2025-08-12 17:02 UTC (permalink / raw)
To: pgsql-hackers
Attached is my current work on adding remote fetching of statistics to
postgres_fdw, and opening the possibility of doing so to other foreign data
wrappers.
This involves adding two new options to postgres_fdw at the server and
table level.
The first option, fetch_stats, defaults to true at both levels. If enabled,
it will cause an ANALYZE of a postgres_fdw foreign table to first attempt
to fetch relation and attribute statistics from the remote table. If this
succeeds, then those statistics are imported into the local foreign table,
allowing us to skip a potentially expensive sampling operation.
The second option, remote_analyze, defaults to false at both levels, and
only comes into play if the first fetch succeeds but no attribute
statistics (i.e. the stats from pg_stats) are found. If enabled then the
function will attempt to ANALYZE the remote table, and if that is
successful then a second attempt at fetching remote statistics will be made.
If no statistics were fetched, then the operation will fall back to the
normal sampling operation per settings.
Note patches 0001 and 0002 are already a part of a separate thread
https://www.postgresql.org/message-id/flat/CADkLM%3DcpUiJ3QF7aUthTvaVMmgQcm7QqZBRMDLhBRTR%2BgJX-Og%4...
regarding a bug (0001) and a nitpick (0002) that came about as a
side-effect to this effort, and but I expect those to be resolved one way
or another soon. Any feedback on those two can be handled there.
Attachments: download all (3 files, .tar.gz)
v1-0001-Fix-remote-sampling-tests-in-postgres_fdw.patch (text/x-patch, 3.6K) download
From 98a15ff9a348f875558a5a9bba44a6e21f09d019 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Mon, 11 Aug 2025 10:05:08 -0400
Subject: [PATCH v1 1/3] Fix remote sampling tests in postgres_fdw.
These tests were changing the sampling setting of a foreign server, but
then were analyzing a local table, which doesn't actually test the
sampling.
Changed the ANALYZE commands to analyze the foreign table, and changed
the foreign table definition to point to a valid local table.
---
contrib/postgres_fdw/expected/postgres_fdw.out | 12 ++++++------
contrib/postgres_fdw/sql/postgres_fdw.sql | 12 ++++++------
2 files changed, 12 insertions(+), 12 deletions(-)
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index a434eb1395e..d3323b04676 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -12649,7 +12649,7 @@ ALTER SERVER loopback2 OPTIONS (DROP parallel_abort);
-- ===================================================================
CREATE TABLE analyze_table (id int, a text, b bigint);
CREATE FOREIGN TABLE analyze_ftable (id int, a text, b bigint)
- SERVER loopback OPTIONS (table_name 'analyze_rtable1');
+ SERVER loopback OPTIONS (table_name 'analyze_table');
INSERT INTO analyze_table (SELECT x FROM generate_series(1,1000) x);
ANALYZE analyze_table;
SET default_statistics_target = 10;
@@ -12657,15 +12657,15 @@ ANALYZE analyze_table;
ALTER SERVER loopback OPTIONS (analyze_sampling 'invalid');
ERROR: invalid value for string option "analyze_sampling": invalid
ALTER SERVER loopback OPTIONS (analyze_sampling 'auto');
-ANALYZE analyze_table;
+ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'system');
-ANALYZE analyze_table;
+ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'bernoulli');
-ANALYZE analyze_table;
+ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'random');
-ANALYZE analyze_table;
+ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'off');
-ANALYZE analyze_table;
+ANALYZE analyze_ftable;
-- cleanup
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index d9bed565c81..2c609e060b7 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -4365,7 +4365,7 @@ ALTER SERVER loopback2 OPTIONS (DROP parallel_abort);
CREATE TABLE analyze_table (id int, a text, b bigint);
CREATE FOREIGN TABLE analyze_ftable (id int, a text, b bigint)
- SERVER loopback OPTIONS (table_name 'analyze_rtable1');
+ SERVER loopback OPTIONS (table_name 'analyze_table');
INSERT INTO analyze_table (SELECT x FROM generate_series(1,1000) x);
ANALYZE analyze_table;
@@ -4376,19 +4376,19 @@ ANALYZE analyze_table;
ALTER SERVER loopback OPTIONS (analyze_sampling 'invalid');
ALTER SERVER loopback OPTIONS (analyze_sampling 'auto');
-ANALYZE analyze_table;
+ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'system');
-ANALYZE analyze_table;
+ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'bernoulli');
-ANALYZE analyze_table;
+ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'random');
-ANALYZE analyze_table;
+ANALYZE analyze_ftable;
ALTER SERVER loopback OPTIONS (SET analyze_sampling 'off');
-ANALYZE analyze_table;
+ANALYZE analyze_ftable;
-- cleanup
DROP FOREIGN TABLE analyze_ftable;
base-commit: b227b0bb4e032e19b3679bedac820eba3ac0d1cf
--
2.50.1
v1-0002-Use-psql-vars-to-eliminate-the-need-for-DO-blocks.patch (text/x-patch, 7.1K) download
From 652292d2c227c34588b130221b9e3efafbea28fb Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sun, 10 Aug 2025 19:36:52 -0400
Subject: [PATCH v1 2/3] Use psql vars to eliminate the need for DO blocks.
Several statements need to reference the current connection's current
database name and current port value. Until now, this has been
accomplished by creating dynamic SQL statements inside of a DO block,
which isn't as easy to read, and takes away some of the granularity of
any error messages that might occur, however unlikely.
By capturing the connection-specific settings into psql vars, it becomes
possible to write the SQL statements with simple :'varname'
interpolations.
---
.../postgres_fdw/expected/postgres_fdw.out | 44 ++++++------------
contrib/postgres_fdw/sql/postgres_fdw.sql | 46 ++++++-------------
2 files changed, 29 insertions(+), 61 deletions(-)
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index d3323b04676..6af35d04a4e 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -2,23 +2,16 @@
-- create FDW objects
-- ===================================================================
CREATE EXTENSION postgres_fdw;
+SELECT current_database() AS current_database,
+ current_setting('port') AS current_port
+\gset
CREATE SERVER testserver1 FOREIGN DATA WRAPPER postgres_fdw;
-DO $d$
- BEGIN
- EXECUTE $$CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw
- OPTIONS (dbname '$$||current_database()||$$',
- port '$$||current_setting('port')||$$'
- )$$;
- EXECUTE $$CREATE SERVER loopback2 FOREIGN DATA WRAPPER postgres_fdw
- OPTIONS (dbname '$$||current_database()||$$',
- port '$$||current_setting('port')||$$'
- )$$;
- EXECUTE $$CREATE SERVER loopback3 FOREIGN DATA WRAPPER postgres_fdw
- OPTIONS (dbname '$$||current_database()||$$',
- port '$$||current_setting('port')||$$'
- )$$;
- END;
-$d$;
+CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw
+ OPTIONS (dbname :'current_database', port :'current_port');
+CREATE SERVER loopback2 FOREIGN DATA WRAPPER postgres_fdw
+ OPTIONS (dbname :'current_database', port :'current_port');
+CREATE SERVER loopback3 FOREIGN DATA WRAPPER postgres_fdw
+ OPTIONS (dbname :'current_database', port :'current_port');
CREATE USER MAPPING FOR public SERVER testserver1
OPTIONS (user 'value', password 'value');
CREATE USER MAPPING FOR CURRENT_USER SERVER loopback;
@@ -235,12 +228,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work
ALTER SERVER loopback OPTIONS (SET dbname 'no such database');
SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should fail
ERROR: could not connect to server "loopback"
-DO $d$
- BEGIN
- EXECUTE $$ALTER SERVER loopback
- OPTIONS (SET dbname '$$||current_database()||$$')$$;
- END;
-$d$;
+ALTER SERVER loopback OPTIONS (SET dbname :'current_database');
SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
c3 | c4
-------+------------------------------
@@ -10643,14 +10631,8 @@ SHOW is_superuser;
(1 row)
-- This will be OK, we can create the FDW
-DO $d$
- BEGIN
- EXECUTE $$CREATE SERVER loopback_nopw FOREIGN DATA WRAPPER postgres_fdw
- OPTIONS (dbname '$$||current_database()||$$',
- port '$$||current_setting('port')||$$'
- )$$;
- END;
-$d$;
+CREATE SERVER loopback_nopw FOREIGN DATA WRAPPER postgres_fdw
+ OPTIONS (dbname :'current_database', port :'current_port');
-- But creation of user mappings for non-superusers should fail
CREATE USER MAPPING FOR public SERVER loopback_nopw;
CREATE USER MAPPING FOR CURRENT_USER SERVER loopback_nopw;
@@ -12724,3 +12706,5 @@ SELECT server_name,
-- Clean up
\set VERBOSITY default
RESET debug_discard_caches;
+\unset current_database
+\unset current_port
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 2c609e060b7..63bba3982cb 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -4,24 +4,17 @@
CREATE EXTENSION postgres_fdw;
-CREATE SERVER testserver1 FOREIGN DATA WRAPPER postgres_fdw;
-DO $d$
- BEGIN
- EXECUTE $$CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw
- OPTIONS (dbname '$$||current_database()||$$',
- port '$$||current_setting('port')||$$'
- )$$;
- EXECUTE $$CREATE SERVER loopback2 FOREIGN DATA WRAPPER postgres_fdw
- OPTIONS (dbname '$$||current_database()||$$',
- port '$$||current_setting('port')||$$'
- )$$;
- EXECUTE $$CREATE SERVER loopback3 FOREIGN DATA WRAPPER postgres_fdw
- OPTIONS (dbname '$$||current_database()||$$',
- port '$$||current_setting('port')||$$'
- )$$;
- END;
-$d$;
+SELECT current_database() AS current_database,
+ current_setting('port') AS current_port
+\gset
+CREATE SERVER testserver1 FOREIGN DATA WRAPPER postgres_fdw;
+CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw
+ OPTIONS (dbname :'current_database', port :'current_port');
+CREATE SERVER loopback2 FOREIGN DATA WRAPPER postgres_fdw
+ OPTIONS (dbname :'current_database', port :'current_port');
+CREATE SERVER loopback3 FOREIGN DATA WRAPPER postgres_fdw
+ OPTIONS (dbname :'current_database', port :'current_port');
CREATE USER MAPPING FOR public SERVER testserver1
OPTIONS (user 'value', password 'value');
CREATE USER MAPPING FOR CURRENT_USER SERVER loopback;
@@ -233,12 +226,7 @@ ALTER FOREIGN TABLE ft2 ALTER COLUMN c1 OPTIONS (column_name 'C 1');
SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work
ALTER SERVER loopback OPTIONS (SET dbname 'no such database');
SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should fail
-DO $d$
- BEGIN
- EXECUTE $$ALTER SERVER loopback
- OPTIONS (SET dbname '$$||current_database()||$$')$$;
- END;
-$d$;
+ALTER SERVER loopback OPTIONS (SET dbname :'current_database');
SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Test that alteration of user mapping options causes reconnection
@@ -3375,14 +3363,8 @@ SET ROLE regress_nosuper;
SHOW is_superuser;
-- This will be OK, we can create the FDW
-DO $d$
- BEGIN
- EXECUTE $$CREATE SERVER loopback_nopw FOREIGN DATA WRAPPER postgres_fdw
- OPTIONS (dbname '$$||current_database()||$$',
- port '$$||current_setting('port')||$$'
- )$$;
- END;
-$d$;
+CREATE SERVER loopback_nopw FOREIGN DATA WRAPPER postgres_fdw
+ OPTIONS (dbname :'current_database', port :'current_port');
-- But creation of user mappings for non-superusers should fail
CREATE USER MAPPING FOR public SERVER loopback_nopw;
@@ -4435,3 +4417,5 @@ SELECT server_name,
-- Clean up
\set VERBOSITY default
RESET debug_discard_caches;
+\unset current_database
+\unset current_port
--
2.50.1
v1-0003-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 37.4K) download
From c44fd420b1a2c9cb6475782867a4a339760367ad Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 7 Aug 2025 23:58:38 -0400
Subject: [PATCH v1 3/3] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via two new options, fetch_stats and remote_analyze,
both are available at the server level and table level. If fetch_stats
is true, then the ANALYZE command will first attempt to fetch statistics
from the remote table and import those statistics locally.
If remote_analyze is true, and if the first attempt to fetch remote
statistics found no attribute statistics, then an attempt will be made
to ANALYZE the remote table before a second and final attempt to fetch
remote statistics.
If no statistics are found, then ANALYZE will fall back to the normal
behavior of sampling and local analysis.
This operation will only work on remote relations that can have stored
statistics: tables, partitioned tables, and materialized views. If the
remote relation is a view then remote fetching/analyzing is just wasted
effort and the user is better of setting fetch_stats to false for that
table.
The default for fetch_stats is true at both server and table level. The
default for remote_analyze is false at both the server and table level.
In both cases, setting a value at the table level will override the
corresponding server-level setting.
---
src/include/foreign/fdwapi.h | 12 +
src/backend/commands/analyze.c | 46 +-
doc/src/sgml/postgres-fdw.sgml | 35 +-
.../postgres_fdw/expected/postgres_fdw.out | 64 +-
contrib/postgres_fdw/option.c | 10 +
contrib/postgres_fdw/postgres_fdw.c | 546 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 37 +-
7 files changed, 746 insertions(+), 4 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index b4da4e6a16a..f0a7db424db 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -19,6 +19,15 @@
/* To avoid including explain.h here, reference ExplainState thus: */
struct ExplainState;
+/* result of ImportStatistics */
+typedef enum
+{
+ FDW_IMPORT_STATS_OK = 0, /* was able to import statistics */
+ FDW_IMPORT_STATS_DISABLED, /* import disabled for this table */
+ FDW_IMPORT_STATS_NOTFOUND, /* no remote attribute stats found */
+ FDW_IMPORT_STATS_FAILED /* remote query failure of some kind */
+} FdwImportStatsResult;
+
/*
* Callback function signatures --- see fdwhandler.sgml for more info.
@@ -157,6 +166,8 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef FdwImportStatsResult (*ImportStatistics_function) (Relation relation);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +266,7 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 40d66537ad7..6cd93ae173d 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -197,13 +197,57 @@ analyze_rel(Oid relid, RangeVar *relation,
{
/*
* For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * supports statistics import and/or analysis.
*/
FdwRoutine *fdwroutine;
bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
+ if (fdwroutine->ImportStatistics != NULL)
+ {
+ FdwImportStatsResult res;
+
+ /*
+ * Fetching pre-existing remote stats is not guaranteed to be a quick
+ * operation.
+ *
+ * XXX: Should this be it's own fetch type? If not, then there might be
+ * confusion when a long stats-fetch fails, followed by a regular analyze,
+ * which would make it look like the table was analyzed twice.
+ */
+ pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
+ RelationGetRelid(onerel));
+
+ res = fdwroutine->ImportStatistics(onerel);
+
+ pgstat_progress_end_command();
+
+ /*
+ * If we were able to import statistics, then there is no need to collect
+ * samples for local analysis.
+ */
+ switch(res)
+ {
+ case FDW_IMPORT_STATS_OK:
+ relation_close(onerel, NoLock);
+ return;
+ break;
+ case FDW_IMPORT_STATS_DISABLED:
+ break;
+ case FDW_IMPORT_STATS_NOTFOUND:
+ ereport(INFO,
+ (errmsg("Found no remote statistics for \"%s\"",
+ RelationGetRelationName(onerel))));
+ break;
+ case FDW_IMPORT_STATS_FAILED:
+ default:
+ ereport(INFO,
+ (errmsg("Fetching remote statistics from \"%s\" failed",
+ RelationGetRelationName(onerel))));
+ }
+ }
+
if (fdwroutine->AnalyzeForeignTable != NULL)
ok = fdwroutine->AnalyzeForeignTable(onerel,
&acquirefunc,
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 781a01067f7..c395d1061d5 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,39 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will first attempt to fetch and import the existing relation and
+ attribute statistics from the remote table, and only attempt regular
+ data sampling if no statistics were availble. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines wheter an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ is only meaningful if the foreign table has
+ <literal>fetch_stats</literal> enabled at either the server or table
+ level.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 6af35d04a4e..35a6723f076 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -628,6 +628,7 @@ INSERT INTO loct_empty
SELECT id, 'AAA' || to_char(id, 'FM000') FROM generate_series(1, 100) id;
DELETE FROM loct_empty;
ANALYZE ft_empty;
+INFO: Found no remote statistics for "ft_empty"
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_empty ORDER BY c1;
QUERY PLAN
-------------------------------------------------------------------------------
@@ -4548,7 +4549,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -4565,6 +4567,9 @@ CONTEXT: whole-row reference to foreign table "ftx"
SELECT sum(c2), array_agg(c8) FROM ft1 GROUP BY c8; -- ERROR
ERROR: invalid input syntax for type integer: "foo"
CONTEXT: processing expression at position 2 in select list
+ANALYZE ft1; -- WARNING
+WARNING: invalid input syntax for type integer: "foo"
+ALTER FOREIGN TABLE ft1 OPTIONS ( fetch_stats 'false' );
ANALYZE ft1; -- ERROR
ERROR: invalid input syntax for type integer: "foo"
CONTEXT: column "c8" of foreign table "ft1"
@@ -7097,6 +7102,7 @@ INSERT INTO loct2 VALUES (1002, 'bar');
CREATE FOREIGN TABLE remt2 (c1 int, c2 text) SERVER loopback OPTIONS (table_name 'loct2');
ANALYZE loct1;
ANALYZE remt2;
+INFO: Found no remote statistics for "remt2"
SET enable_mergejoin TO false;
SET enable_hashjoin TO false;
SET enable_material TO false;
@@ -8776,6 +8782,7 @@ alter foreign table foo2 options (use_remote_estimate 'true');
create index i_loct1_f1 on loct1(f1);
create index i_foo_f1 on foo(f1);
analyze foo;
+INFO: Found no remote statistics for "foo2"
analyze loct1;
-- inner join; expressions in the clauses appear in the equivalence class list
explain (verbose, costs off)
@@ -9005,7 +9012,9 @@ insert into remt1 values (2, 'bar');
insert into remt2 values (1, 'foo');
insert into remt2 values (2, 'bar');
analyze remt1;
+INFO: Found no remote statistics for "remt1"
analyze remt2;
+INFO: Found no remote statistics for "remt2"
explain (verbose, costs off)
update parent set b = parent.b || remt2.b from remt2 where parent.a = remt2.a returning *;
QUERY PLAN
@@ -10305,6 +10314,8 @@ CREATE FOREIGN TABLE ftprt1_p1 PARTITION OF fprt1 FOR VALUES FROM (0) TO (250)
CREATE FOREIGN TABLE ftprt1_p2 PARTITION OF fprt1 FOR VALUES FROM (250) TO (500)
SERVER loopback OPTIONS (TABLE_NAME 'fprt1_p2');
ANALYZE fprt1;
+INFO: Found no remote statistics for "ftprt1_p1"
+INFO: Found no remote statistics for "ftprt1_p2"
ANALYZE fprt1_p1;
ANALYZE fprt1_p2;
CREATE TABLE fprt2 (a int, b int, c varchar) PARTITION BY RANGE(b);
@@ -10320,6 +10331,8 @@ ALTER TABLE fprt2 ATTACH PARTITION ftprt2_p1 FOR VALUES FROM (0) TO (250);
CREATE FOREIGN TABLE ftprt2_p2 PARTITION OF fprt2 FOR VALUES FROM (250) TO (500)
SERVER loopback OPTIONS (table_name 'fprt2_p2', use_remote_estimate 'true');
ANALYZE fprt2;
+INFO: Found no remote statistics for "ftprt2_p1"
+INFO: Found no remote statistics for "ftprt2_p2"
ANALYZE fprt2_p1;
ANALYZE fprt2_p2;
-- inner join three tables
@@ -10507,9 +10520,15 @@ CREATE FOREIGN TABLE fpagg_tab_p1 PARTITION OF pagg_tab FOR VALUES FROM (0) TO (
CREATE FOREIGN TABLE fpagg_tab_p2 PARTITION OF pagg_tab FOR VALUES FROM (10) TO (20) SERVER loopback OPTIONS (table_name 'pagg_tab_p2');
CREATE FOREIGN TABLE fpagg_tab_p3 PARTITION OF pagg_tab FOR VALUES FROM (20) TO (30) SERVER loopback OPTIONS (table_name 'pagg_tab_p3');
ANALYZE pagg_tab;
+INFO: Found no remote statistics for "fpagg_tab_p1"
+INFO: Found no remote statistics for "fpagg_tab_p2"
+INFO: Found no remote statistics for "fpagg_tab_p3"
ANALYZE fpagg_tab_p1;
+INFO: Found no remote statistics for "fpagg_tab_p1"
ANALYZE fpagg_tab_p2;
+INFO: Found no remote statistics for "fpagg_tab_p2"
ANALYZE fpagg_tab_p3;
+INFO: Found no remote statistics for "fpagg_tab_p3"
-- When GROUP BY clause matches with PARTITION KEY.
-- Plan with partitionwise aggregates is disabled
SET enable_partitionwise_aggregate TO false;
@@ -11455,6 +11474,8 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
EXPLAIN (VERBOSE, COSTS OFF)
@@ -11561,6 +11582,9 @@ CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
+INFO: Found no remote statistics for "async_p3"
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
QUERY PLAN
@@ -11597,6 +11621,8 @@ DROP TABLE base_tbl3;
CREATE TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000);
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
QUERY PLAN
@@ -12652,6 +12678,42 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table', remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 04788b7e8b3..7f069373e82 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,8 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +280,14 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_size is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 456b267f70b..096cd4d0fdd 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -22,6 +22,8 @@
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -402,6 +404,7 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static FdwImportStatsResult postgresImportStatistics(Relation relation);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +549,114 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+
+/* relallfrozen introduced in v18 */
+static const char *relstats_query_18 =
+ "SELECT c.relpages, c.reltuples, c.relallvisible, c.relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* trust reltuples = 0 as of v14 */
+static const char *relstats_query_14 =
+ "SELECT c.relpages, c.reltuples, c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case.)
+ * This ambiguity allegedly can cause the planner to choose inefficient
+ * plans after restoring to v18 or newer. To deal with this, let's just
+ * set reltuples to -1 in that case.
+ */
+static const char *relstats_query_default =
+ "SELECT c.relpages, "
+ "CASE c.reltuples WHEN 0 THEN -1 ELSE c.reltuples END AS reltuples, "
+ "c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns {
+ RELSTATS_RELPAGES = 0,
+ RELSTATS_RELTUPLES,
+ RELSTATS_RELALLVISIBLE,
+ RELSTATS_RELALLFROZEN,
+ RELSTATS_NUM_FIELDS
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+static const char *attstats_query_default =
+ "SELECT s.attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns {
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS
+};
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +706,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5047,440 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Process optional argument.
+ *
+ * Cannot be the first argument in the SQL function call.
+ *
+ * It is safe to presume that argname and argtype are quote-safe.
+ *
+ * Argument values can potentially be quite large, so free the quoted string
+ * after use.
+ */
+static void
+append_optional(StringInfo str, PGresult *res, int row, int field,
+ const char *argname, const char *argtype)
+{
+ if (!PQgetisnull(res, row, field))
+ {
+ /* Argument values can be quite large, so free after use */
+ char *argval_l = quote_literal_cstr(PQgetvalue(res, row, field));
+
+ appendStringInfo(str, ",\n\t'%s', %s::%s", argname, argval_l, argtype);
+
+ pfree(argval_l);
+ }
+}
+
+
+/*
+ * Generate a pg_restore_relation_stats command.
+ */
+static char *
+restore_relation_stats_sql(PGresult *res, const char *schemaname_l,
+ const char *relname_l,
+ const int server_version_num)
+{
+ StringInfoData sql;
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s",
+ server_version_num, schemaname_l, relname_l);
+
+ append_optional(&sql, res, 0, RELSTATS_RELPAGES, "relpages", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELTUPLES, "reltuples", "real");
+ append_optional(&sql, res, 0, RELSTATS_RELALLVISIBLE, "relallvisible", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELALLFROZEN, "relallfrozen", "integer");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Generate a pg_restore_attribute_stats command.
+ */
+static char *
+restore_attribute_stats_sql(PGresult *res, int row, const char *schemaname_l,
+ const char *relname_l, const AttrNumber attnum,
+ const int server_version_num)
+{
+ StringInfoData sql;
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s,\n"
+ "\t'attnum', %d::smallint,\n"
+ "\t'inherited', false::boolean",
+ server_version_num, schemaname_l, relname_l, attnum);
+
+ append_optional(&sql, res, row, ATTSTATS_NULL_FRAC, "null_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_AVG_WIDTH, "avg_width", "integer");
+ append_optional(&sql, res, row, ATTSTATS_N_DISTINCT, "n_distinct", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_VALS, "most_common_vals", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_FREQS, "most_common_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_HISTOGRAM_BOUNDS, "histogram_bounds", "text");
+ append_optional(&sql, res, row, ATTSTATS_CORRELATION, "correlation", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEMS, "most_common_elems", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEM_FREQS, "most_common_elem_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_ELEM_COUNT_HISTOGRAM, "elem_count_histogram", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_LENGTH_HISTOGRAM, "range_length_histogram", "text");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_EMPTY_FRAC, "range_empty_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_BOUNDS_HISTOGRAM, "range_bounds_histogram", "text");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static FdwImportStatsResult
+postgresImportStatistics(Relation relation)
+{
+
+ ForeignTable *table;
+ ForeignServer *server;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ bool fetch_stats = true;
+ bool remote_analyze = false;
+ int server_version_num;
+
+ const char *relation_sql;
+ const char *attribute_sql;
+ const char *schemaname;
+ const char *relname;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+
+ const char *schemaname_l;
+ const char *relname_l;
+
+ char *relimport_sql;
+
+ PGresult *res;
+ TupleDesc tupdesc;
+ const char *sql_params[2];
+ int sql_param_formats[2] = {0, 0};
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ fetch_stats = defGetBoolean(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ fetch_stats = defGetBoolean(def);
+ else if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ if (fetch_stats == false)
+ return FDW_IMPORT_STATS_DISABLED;
+
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+
+ relname = RelationGetRelationName(relation);
+
+ schemaname_l = quote_literal_cstr(schemaname);
+ relname_l = quote_literal_cstr(relname);
+
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+ sql_params[0] = remote_schemaname;
+ sql_params[1] = remote_relname;
+
+ if (server_version_num >= 180000)
+ relation_sql = relstats_query_18;
+ else if (server_version_num >= 140000)
+ relation_sql = relstats_query_14;
+ else
+ relation_sql = relstats_query_default;
+
+ if (server_version_num >= 170000)
+ attribute_sql = attstats_query_17;
+ else if (server_version_num >= 90200)
+ attribute_sql = attstats_query_9_2;
+ else if (server_version_num >= 90000)
+ attribute_sql = attstats_query_9_0;
+ else
+ attribute_sql = attstats_query_default;
+
+ /*
+ * pg_restore_attribute_stats
+ *
+ * We do this before relation stats because we may retry it if no stats were
+ * found.
+ */
+ if (!PQsendQueryParams(conn, attribute_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, attribute_sql);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ res = pgfdw_get_result(conn);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, res, conn, attribute_sql);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * If we got a query response of the right shape, but there were no rows,
+ * then the remote is just missing statistics
+ */
+ if (PQntuples(res) == 0)
+ {
+ StringInfoData buf;
+
+ PQclear(res);
+
+ /*
+ * If remote_analyze is not enabled, any failure to find statistics are
+ * considered temporary. This is not an error, but we should fall back
+ * to regular local analyzis if enabled.
+ */
+ if (!remote_analyze)
+ {
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_NOTFOUND;
+ }
+
+ /*
+ * Analyze the remote table and try again. If it's still empty, then that's
+ * an error indicating that we probably shouldn't do remote analysis going
+ * forward.
+ */
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s.%s",
+ quote_identifier(remote_schemaname),
+ quote_identifier(remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL || PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ pgfdw_report(NOTICE, res, conn, buf.data);
+ pfree(buf.data);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ PQclear(res);
+ pfree(buf.data);
+
+ /* retry attribute stats query */
+ if (!PQsendQueryParams(conn, attribute_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, attribute_sql);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+ res = pgfdw_get_result(conn);
+
+ /* getting nothing on the second try is a failure */
+ if (PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) == 0
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, res, conn, attribute_sql);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+ }
+
+ SPI_connect();
+
+ /*
+ * Walk all local table attributes looking for name matches in the result
+ * set and perform a pg_restore_attribute_stats() on each match.
+ *
+ * XXX: the result set is sorted by attname, so perhaps we could do a binary
+ * search of the result set. Alternately we could collect the local attributes
+ * in a list and sort that by remote name, which would allow us to iterate via
+ * a merge.
+ *
+ * XXX: what should be done if match_found = false?
+ */
+ tupdesc = RelationGetDescr(relation);
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+ bool match_found = false;
+
+ /* Ignore dropped columns. */
+ if (TupleDescAttr(tupdesc, i)->attisdropped)
+ continue;
+
+ /* Ignore generated columns, but maybe this should fail the import? */
+ if (TupleDescAttr(tupdesc, i)->attgenerated)
+ continue;
+
+ attnum = TupleDescAttr(tupdesc, i)->attnum;
+
+ /* default remote_colname is attname */
+ remote_colname = NameStr(TupleDescAttr(tupdesc, i)->attname);
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), i + 1);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ for (int j = 0; j < PQntuples(res); j++)
+ {
+ char *attimport_sql;
+
+ if (PQgetisnull(res, j, ATTSTATS_ATTNAME))
+ continue;
+
+ if (strcmp(PQgetvalue(res, j, ATTSTATS_ATTNAME), remote_colname) != 0)
+ continue;
+
+ match_found = true;
+ attimport_sql = restore_attribute_stats_sql(res, j, schemaname_l, relname_l, attnum, server_version_num);
+
+ if (SPI_execute(attimport_sql, false, 1) != SPI_OK_SELECT)
+ {
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics import failed %s", attimport_sql)));
+ SPI_finish();
+ ReleaseConnection(conn);
+ pfree(attimport_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ pfree(attimport_sql);
+ }
+
+ /* TODO: should this be an error? What action could we take to remediate? */
+ if (!match_found)
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics found for %s.%s but no columns matched",
+ quote_identifier(schemaname),
+ quote_identifier(relname))));
+ }
+ PQclear(res);
+
+ /*
+ * pg_restore_relation_stats
+ */
+ if (!PQsendQueryParams(conn, relation_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, relation_sql);
+ SPI_finish();
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ res = pgfdw_get_result(conn);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS)
+ {
+ /* unable to get relation stats, fall back on table sampling */
+ pgfdw_report(INFO, res, conn, attribute_sql);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ relimport_sql = restore_relation_stats_sql(res, schemaname_l, relname_l, server_version_num);
+
+ if (SPI_execute(relimport_sql, false, 0) != SPI_OK_SELECT)
+ {
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Relation statistics import failed %s", relimport_sql)));
+ SPI_finish();
+ ReleaseConnection(conn);
+ pfree(relimport_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ pfree(relimport_sql);
+
+ SPI_finish();
+
+ return FDW_IMPORT_STATS_OK;
+}
+
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 63bba3982cb..de575ce5bbd 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -1278,7 +1278,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -1287,6 +1288,8 @@ SELECT ftx.x1, ft2.c2, ftx.x8 FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2
SELECT ftx.x1, ft2.c2, ftx FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2
WHERE ftx.x1 = ft2.c1 AND ftx.x1 = 1; -- ERROR
SELECT sum(c2), array_agg(c8) FROM ft1 GROUP BY c8; -- ERROR
+ANALYZE ft1; -- WARNING
+ALTER FOREIGN TABLE ft1 OPTIONS ( fetch_stats 'false' );
ANALYZE ft1; -- ERROR
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE user_enum;
@@ -4376,6 +4379,38 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table', remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
--
2.50.1
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-08-14 07:37 Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Ashutosh Bapat @ 2025-08-14 07:37 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: pgsql-hackers
On Tue, Aug 12, 2025 at 10:33 PM Corey Huinker <corey.huinker@gmail.com> wrote:
>
>
> Attached is my current work on adding remote fetching of statistics to postgres_fdw, and opening the possibility of doing so to other foreign data wrappers.
>
> This involves adding two new options to postgres_fdw at the server and table level.
>
> The first option, fetch_stats, defaults to true at both levels. If enabled, it will cause an ANALYZE of a postgres_fdw foreign table to first attempt to fetch relation and attribute statistics from the remote table. If this succeeds, then those statistics are imported into the local foreign table, allowing us to skip a potentially expensive sampling operation.
>
> The second option, remote_analyze, defaults to false at both levels, and only comes into play if the first fetch succeeds but no attribute statistics (i.e. the stats from pg_stats) are found. If enabled then the function will attempt to ANALYZE the remote table, and if that is successful then a second attempt at fetching remote statistics will be made.
>
> If no statistics were fetched, then the operation will fall back to the normal sampling operation per settings.
>
> Note patches 0001 and 0002 are already a part of a separate thread https://www.postgresql.org/message-id/flat/CADkLM%3DcpUiJ3QF7aUthTvaVMmgQcm7QqZBRMDLhBRTR%2BgJX-Og%4... regarding a bug (0001) and a nitpick (0002) that came about as a side-effect to this effort, and but I expect those to be resolved one way or another soon. Any feedback on those two can be handled there.
I think this is very useful to avoid fetching rows from foreign server
and analyzing them locally.
This isn't a full review. I looked at the patches mainly to find out
how does it fit into the current method of analysing a foreign table.
Right now, do_analyze_rel() is called with FDW specific acquireFunc,
which collects a sample of rows. The sample is passed to attribute
specific compute_stats which fills VacAttrStats for that attribute.
VacAttrStats for all the attributes is passed to update_attstats(),
which updates pg_statistics. The patch changes that to fetch the
statistics from the foreign server and call pg_restore_attribute_stats
for each attribute. Instead I was expecting that after fetching the
stats from the foreign server, it would construct VacAttrStats and
call update_attstats(). That might be marginally faster since it
avoids SPI call and updates stats for all the attributes. Did you
consider this alternate approach and why it was discarded?
If a foreign table points to an inheritance parent on the foreign
server, we will receive two rows for that table - one with inherited =
false and other with true in that order. I think the stats with
inherited=true are relevant to the local server since querying the
parent will fetch rows from children. Since that stats is applied
last, the pg_statistics will retain the intended statistics. But why
to fetch two rows in the first place and waste computing cycles?
--
Best Wishes,
Ashutosh Bapat
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-08-14 18:34 Corey Huinker <corey.huinker@gmail.com>
parent: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2025-08-14 18:34 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: pgsql-hackers
>
>
> This isn't a full review. I looked at the patches mainly to find out
> how does it fit into the current method of analysing a foreign table.
>
Any degree of review is welcome. We're chasing views, reviews, etc.
> Right now, do_analyze_rel() is called with FDW specific acquireFunc,
> which collects a sample of rows. The sample is passed to attribute
> specific compute_stats which fills VacAttrStats for that attribute.
> VacAttrStats for all the attributes is passed to update_attstats(),
> which updates pg_statistics. The patch changes that to fetch the
> statistics from the foreign server and call pg_restore_attribute_stats
> for each attribute.
That recap is accurate.
> Instead I was expecting that after fetching the
> stats from the foreign server, it would construct VacAttrStats and
> call update_attstats(). That might be marginally faster since it
> avoids SPI call and updates stats for all the attributes. Did you
> consider this alternate approach and why it was discarded?
>
It might be marginally faster, but it would duplicate a lot of the
pair-checking (must have a most-common-freqs with a most-common-vals, etc)
and type-checking logic (the vals in a most-common vals must all input
coerce to the correct datatype for the _destination_ column, etc), and
we've already got that in pg_restore_attribute_stats. There used to be a
non-fcinfo function that took a long list of Datums and isnull boolean
pairs, but that wasn't pretty to look at and was replaced with the
positional fcinfo version we have today. This use case might be a reason to
bring that back, or expose the existing positional fcinfo function
(presently static) if we want to avoid SPI badly enough. As it is, the SPI
code is fairly future proof in that it isn't required to add new stat types
as they are created. My first attempt at this patch attempted to make a
FunctionCallInvoke() on the variadic pg_restore_attribute_stats, but that
would require a filled out fn_expr, and to get that we'd have to duplicate
a lot of logic from the parser, so the infrastructure isn't available to
easily call a variadic function.
>
> If a foreign table points to an inheritance parent on the foreign
> server, we will receive two rows for that table - one with inherited =
> false and other with true in that order. I think the stats with
> inherited=true are relevant to the local server since querying the
> parent will fetch rows from children. Since that stats is applied
> last, the pg_statistics will retain the intended statistics. But why
> to fetch two rows in the first place and waste computing cycles?
>
Glad you agree that we're fetching the right statistics.
That was the only way I could think of to do one client fetch and still get
exactly one row back.
Anything else involved fetching the inh=true first, and if that failed
fetching the inh=false statistics. That adds extra round-trips especially
given that inherited statistics are more rare than non-inherited
statistics. Moreoever, we're making decisions (analyze yes/no, fallback to
sampling yes/no) based on whether or not we got statistics back from the
foreign server at all, and having to consider the result of two fetches
instead of one makes that logic more complicated.
If, however, you were referring to the work we're handing the remote
server, I'm open to queries that you think would be more lightweight.
However, the pg_stats view is a security barrier view, so we reduce
overhead by passing through that barrier as few times as possible.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-09-12 05:17 Corey Huinker <corey.huinker@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2025-09-12 05:17 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: pgsql-hackers
Rebased.
Attachments:
v2-0001-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 37.5K) download
From 85f4d02ccef96d80063457a7870caf5f94e12859 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 7 Aug 2025 23:58:38 -0400
Subject: [PATCH v2] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via two new options, fetch_stats and remote_analyze,
both are available at the server level and table level. If fetch_stats
is true, then the ANALYZE command will first attempt to fetch statistics
from the remote table and import those statistics locally.
If remote_analyze is true, and if the first attempt to fetch remote
statistics found no attribute statistics, then an attempt will be made
to ANALYZE the remote table before a second and final attempt to fetch
remote statistics.
If no statistics are found, then ANALYZE will fall back to the normal
behavior of sampling and local analysis.
This operation will only work on remote relations that can have stored
statistics: tables, partitioned tables, and materialized views. If the
remote relation is a view then remote fetching/analyzing is just wasted
effort and the user is better of setting fetch_stats to false for that
table.
The default for fetch_stats is true at both server and table level. The
default for remote_analyze is false at both the server and table level.
In both cases, setting a value at the table level will override the
corresponding server-level setting.
---
src/include/foreign/fdwapi.h | 12 +
src/backend/commands/analyze.c | 46 +-
doc/src/sgml/postgres-fdw.sgml | 35 +-
.../postgres_fdw/expected/postgres_fdw.out | 64 +-
contrib/postgres_fdw/option.c | 10 +
contrib/postgres_fdw/postgres_fdw.c | 546 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 37 +-
7 files changed, 746 insertions(+), 4 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index b4da4e6a16a..f0a7db424db 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -19,6 +19,15 @@
/* To avoid including explain.h here, reference ExplainState thus: */
struct ExplainState;
+/* result of ImportStatistics */
+typedef enum
+{
+ FDW_IMPORT_STATS_OK = 0, /* was able to import statistics */
+ FDW_IMPORT_STATS_DISABLED, /* import disabled for this table */
+ FDW_IMPORT_STATS_NOTFOUND, /* no remote attribute stats found */
+ FDW_IMPORT_STATS_FAILED /* remote query failure of some kind */
+} FdwImportStatsResult;
+
/*
* Callback function signatures --- see fdwhandler.sgml for more info.
@@ -157,6 +166,8 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef FdwImportStatsResult (*ImportStatistics_function) (Relation relation);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +266,7 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 8ea2913d906..eada41660ee 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -196,13 +196,57 @@ analyze_rel(Oid relid, RangeVar *relation,
{
/*
* For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * supports statistics import and/or analysis.
*/
FdwRoutine *fdwroutine;
bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
+ if (fdwroutine->ImportStatistics != NULL)
+ {
+ FdwImportStatsResult res;
+
+ /*
+ * Fetching pre-existing remote stats is not guaranteed to be a quick
+ * operation.
+ *
+ * XXX: Should this be it's own fetch type? If not, then there might be
+ * confusion when a long stats-fetch fails, followed by a regular analyze,
+ * which would make it look like the table was analyzed twice.
+ */
+ pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
+ RelationGetRelid(onerel));
+
+ res = fdwroutine->ImportStatistics(onerel);
+
+ pgstat_progress_end_command();
+
+ /*
+ * If we were able to import statistics, then there is no need to collect
+ * samples for local analysis.
+ */
+ switch(res)
+ {
+ case FDW_IMPORT_STATS_OK:
+ relation_close(onerel, NoLock);
+ return;
+ break;
+ case FDW_IMPORT_STATS_DISABLED:
+ break;
+ case FDW_IMPORT_STATS_NOTFOUND:
+ ereport(INFO,
+ (errmsg("Found no remote statistics for \"%s\"",
+ RelationGetRelationName(onerel))));
+ break;
+ case FDW_IMPORT_STATS_FAILED:
+ default:
+ ereport(INFO,
+ (errmsg("Fetching remote statistics from \"%s\" failed",
+ RelationGetRelationName(onerel))));
+ }
+ }
+
if (fdwroutine->AnalyzeForeignTable != NULL)
ok = fdwroutine->AnalyzeForeignTable(onerel,
&acquirefunc,
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 781a01067f7..c395d1061d5 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,39 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will first attempt to fetch and import the existing relation and
+ attribute statistics from the remote table, and only attempt regular
+ data sampling if no statistics were availble. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines wheter an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ is only meaningful if the foreign table has
+ <literal>fetch_stats</literal> enabled at either the server or table
+ level.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 18d727d7790..78ed7631025 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -628,6 +628,7 @@ INSERT INTO loct_empty
SELECT id, 'AAA' || to_char(id, 'FM000') FROM generate_series(1, 100) id;
DELETE FROM loct_empty;
ANALYZE ft_empty;
+INFO: Found no remote statistics for "ft_empty"
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_empty ORDER BY c1;
QUERY PLAN
-------------------------------------------------------------------------------
@@ -4548,7 +4549,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -4565,6 +4567,9 @@ CONTEXT: whole-row reference to foreign table "ftx"
SELECT sum(c2), array_agg(c8) FROM ft1 GROUP BY c8; -- ERROR
ERROR: invalid input syntax for type integer: "foo"
CONTEXT: processing expression at position 2 in select list
+ANALYZE ft1; -- WARNING
+WARNING: invalid input syntax for type integer: "foo"
+ALTER FOREIGN TABLE ft1 OPTIONS ( fetch_stats 'false' );
ANALYZE ft1; -- ERROR
ERROR: invalid input syntax for type integer: "foo"
CONTEXT: column "c8" of foreign table "ft1"
@@ -7097,6 +7102,7 @@ INSERT INTO loct2 VALUES (1002, 'bar');
CREATE FOREIGN TABLE remt2 (c1 int, c2 text) SERVER loopback OPTIONS (table_name 'loct2');
ANALYZE loct1;
ANALYZE remt2;
+INFO: Found no remote statistics for "remt2"
SET enable_mergejoin TO false;
SET enable_hashjoin TO false;
SET enable_material TO false;
@@ -8776,6 +8782,7 @@ alter foreign table foo2 options (use_remote_estimate 'true');
create index i_loct1_f1 on loct1(f1);
create index i_foo_f1 on foo(f1);
analyze foo;
+INFO: Found no remote statistics for "foo2"
analyze loct1;
-- inner join; expressions in the clauses appear in the equivalence class list
explain (verbose, costs off)
@@ -9005,7 +9012,9 @@ insert into remt1 values (2, 'bar');
insert into remt2 values (1, 'foo');
insert into remt2 values (2, 'bar');
analyze remt1;
+INFO: Found no remote statistics for "remt1"
analyze remt2;
+INFO: Found no remote statistics for "remt2"
explain (verbose, costs off)
update parent set b = parent.b || remt2.b from remt2 where parent.a = remt2.a returning *;
QUERY PLAN
@@ -10305,6 +10314,8 @@ CREATE FOREIGN TABLE ftprt1_p1 PARTITION OF fprt1 FOR VALUES FROM (0) TO (250)
CREATE FOREIGN TABLE ftprt1_p2 PARTITION OF fprt1 FOR VALUES FROM (250) TO (500)
SERVER loopback OPTIONS (TABLE_NAME 'fprt1_p2');
ANALYZE fprt1;
+INFO: Found no remote statistics for "ftprt1_p1"
+INFO: Found no remote statistics for "ftprt1_p2"
ANALYZE fprt1_p1;
ANALYZE fprt1_p2;
CREATE TABLE fprt2 (a int, b int, c varchar) PARTITION BY RANGE(b);
@@ -10320,6 +10331,8 @@ ALTER TABLE fprt2 ATTACH PARTITION ftprt2_p1 FOR VALUES FROM (0) TO (250);
CREATE FOREIGN TABLE ftprt2_p2 PARTITION OF fprt2 FOR VALUES FROM (250) TO (500)
SERVER loopback OPTIONS (table_name 'fprt2_p2', use_remote_estimate 'true');
ANALYZE fprt2;
+INFO: Found no remote statistics for "ftprt2_p1"
+INFO: Found no remote statistics for "ftprt2_p2"
ANALYZE fprt2_p1;
ANALYZE fprt2_p2;
-- inner join three tables
@@ -10507,9 +10520,15 @@ CREATE FOREIGN TABLE fpagg_tab_p1 PARTITION OF pagg_tab FOR VALUES FROM (0) TO (
CREATE FOREIGN TABLE fpagg_tab_p2 PARTITION OF pagg_tab FOR VALUES FROM (10) TO (20) SERVER loopback OPTIONS (table_name 'pagg_tab_p2');
CREATE FOREIGN TABLE fpagg_tab_p3 PARTITION OF pagg_tab FOR VALUES FROM (20) TO (30) SERVER loopback OPTIONS (table_name 'pagg_tab_p3');
ANALYZE pagg_tab;
+INFO: Found no remote statistics for "fpagg_tab_p1"
+INFO: Found no remote statistics for "fpagg_tab_p2"
+INFO: Found no remote statistics for "fpagg_tab_p3"
ANALYZE fpagg_tab_p1;
+INFO: Found no remote statistics for "fpagg_tab_p1"
ANALYZE fpagg_tab_p2;
+INFO: Found no remote statistics for "fpagg_tab_p2"
ANALYZE fpagg_tab_p3;
+INFO: Found no remote statistics for "fpagg_tab_p3"
-- When GROUP BY clause matches with PARTITION KEY.
-- Plan with partitionwise aggregates is disabled
SET enable_partitionwise_aggregate TO false;
@@ -11455,6 +11474,8 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
EXPLAIN (VERBOSE, COSTS OFF)
@@ -11561,6 +11582,9 @@ CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
+INFO: Found no remote statistics for "async_p3"
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
QUERY PLAN
@@ -11597,6 +11621,8 @@ DROP TABLE base_tbl3;
CREATE TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000);
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
QUERY PLAN
@@ -12652,6 +12678,42 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table', remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 04788b7e8b3..7f069373e82 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,8 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +280,14 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_size is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 456b267f70b..096cd4d0fdd 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -22,6 +22,8 @@
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -402,6 +404,7 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static FdwImportStatsResult postgresImportStatistics(Relation relation);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +549,114 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+
+/* relallfrozen introduced in v18 */
+static const char *relstats_query_18 =
+ "SELECT c.relpages, c.reltuples, c.relallvisible, c.relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* trust reltuples = 0 as of v14 */
+static const char *relstats_query_14 =
+ "SELECT c.relpages, c.reltuples, c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case.)
+ * This ambiguity allegedly can cause the planner to choose inefficient
+ * plans after restoring to v18 or newer. To deal with this, let's just
+ * set reltuples to -1 in that case.
+ */
+static const char *relstats_query_default =
+ "SELECT c.relpages, "
+ "CASE c.reltuples WHEN 0 THEN -1 ELSE c.reltuples END AS reltuples, "
+ "c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns {
+ RELSTATS_RELPAGES = 0,
+ RELSTATS_RELTUPLES,
+ RELSTATS_RELALLVISIBLE,
+ RELSTATS_RELALLFROZEN,
+ RELSTATS_NUM_FIELDS
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+static const char *attstats_query_default =
+ "SELECT s.attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns {
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS
+};
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +706,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5047,440 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Process optional argument.
+ *
+ * Cannot be the first argument in the SQL function call.
+ *
+ * It is safe to presume that argname and argtype are quote-safe.
+ *
+ * Argument values can potentially be quite large, so free the quoted string
+ * after use.
+ */
+static void
+append_optional(StringInfo str, PGresult *res, int row, int field,
+ const char *argname, const char *argtype)
+{
+ if (!PQgetisnull(res, row, field))
+ {
+ /* Argument values can be quite large, so free after use */
+ char *argval_l = quote_literal_cstr(PQgetvalue(res, row, field));
+
+ appendStringInfo(str, ",\n\t'%s', %s::%s", argname, argval_l, argtype);
+
+ pfree(argval_l);
+ }
+}
+
+
+/*
+ * Generate a pg_restore_relation_stats command.
+ */
+static char *
+restore_relation_stats_sql(PGresult *res, const char *schemaname_l,
+ const char *relname_l,
+ const int server_version_num)
+{
+ StringInfoData sql;
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s",
+ server_version_num, schemaname_l, relname_l);
+
+ append_optional(&sql, res, 0, RELSTATS_RELPAGES, "relpages", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELTUPLES, "reltuples", "real");
+ append_optional(&sql, res, 0, RELSTATS_RELALLVISIBLE, "relallvisible", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELALLFROZEN, "relallfrozen", "integer");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Generate a pg_restore_attribute_stats command.
+ */
+static char *
+restore_attribute_stats_sql(PGresult *res, int row, const char *schemaname_l,
+ const char *relname_l, const AttrNumber attnum,
+ const int server_version_num)
+{
+ StringInfoData sql;
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s,\n"
+ "\t'attnum', %d::smallint,\n"
+ "\t'inherited', false::boolean",
+ server_version_num, schemaname_l, relname_l, attnum);
+
+ append_optional(&sql, res, row, ATTSTATS_NULL_FRAC, "null_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_AVG_WIDTH, "avg_width", "integer");
+ append_optional(&sql, res, row, ATTSTATS_N_DISTINCT, "n_distinct", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_VALS, "most_common_vals", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_FREQS, "most_common_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_HISTOGRAM_BOUNDS, "histogram_bounds", "text");
+ append_optional(&sql, res, row, ATTSTATS_CORRELATION, "correlation", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEMS, "most_common_elems", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEM_FREQS, "most_common_elem_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_ELEM_COUNT_HISTOGRAM, "elem_count_histogram", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_LENGTH_HISTOGRAM, "range_length_histogram", "text");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_EMPTY_FRAC, "range_empty_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_BOUNDS_HISTOGRAM, "range_bounds_histogram", "text");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static FdwImportStatsResult
+postgresImportStatistics(Relation relation)
+{
+
+ ForeignTable *table;
+ ForeignServer *server;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ bool fetch_stats = true;
+ bool remote_analyze = false;
+ int server_version_num;
+
+ const char *relation_sql;
+ const char *attribute_sql;
+ const char *schemaname;
+ const char *relname;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+
+ const char *schemaname_l;
+ const char *relname_l;
+
+ char *relimport_sql;
+
+ PGresult *res;
+ TupleDesc tupdesc;
+ const char *sql_params[2];
+ int sql_param_formats[2] = {0, 0};
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ fetch_stats = defGetBoolean(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ fetch_stats = defGetBoolean(def);
+ else if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ if (fetch_stats == false)
+ return FDW_IMPORT_STATS_DISABLED;
+
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+
+ relname = RelationGetRelationName(relation);
+
+ schemaname_l = quote_literal_cstr(schemaname);
+ relname_l = quote_literal_cstr(relname);
+
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+ sql_params[0] = remote_schemaname;
+ sql_params[1] = remote_relname;
+
+ if (server_version_num >= 180000)
+ relation_sql = relstats_query_18;
+ else if (server_version_num >= 140000)
+ relation_sql = relstats_query_14;
+ else
+ relation_sql = relstats_query_default;
+
+ if (server_version_num >= 170000)
+ attribute_sql = attstats_query_17;
+ else if (server_version_num >= 90200)
+ attribute_sql = attstats_query_9_2;
+ else if (server_version_num >= 90000)
+ attribute_sql = attstats_query_9_0;
+ else
+ attribute_sql = attstats_query_default;
+
+ /*
+ * pg_restore_attribute_stats
+ *
+ * We do this before relation stats because we may retry it if no stats were
+ * found.
+ */
+ if (!PQsendQueryParams(conn, attribute_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, attribute_sql);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ res = pgfdw_get_result(conn);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, res, conn, attribute_sql);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * If we got a query response of the right shape, but there were no rows,
+ * then the remote is just missing statistics
+ */
+ if (PQntuples(res) == 0)
+ {
+ StringInfoData buf;
+
+ PQclear(res);
+
+ /*
+ * If remote_analyze is not enabled, any failure to find statistics are
+ * considered temporary. This is not an error, but we should fall back
+ * to regular local analyzis if enabled.
+ */
+ if (!remote_analyze)
+ {
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_NOTFOUND;
+ }
+
+ /*
+ * Analyze the remote table and try again. If it's still empty, then that's
+ * an error indicating that we probably shouldn't do remote analysis going
+ * forward.
+ */
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s.%s",
+ quote_identifier(remote_schemaname),
+ quote_identifier(remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL || PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ pgfdw_report(NOTICE, res, conn, buf.data);
+ pfree(buf.data);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ PQclear(res);
+ pfree(buf.data);
+
+ /* retry attribute stats query */
+ if (!PQsendQueryParams(conn, attribute_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, attribute_sql);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+ res = pgfdw_get_result(conn);
+
+ /* getting nothing on the second try is a failure */
+ if (PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) == 0
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, res, conn, attribute_sql);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+ }
+
+ SPI_connect();
+
+ /*
+ * Walk all local table attributes looking for name matches in the result
+ * set and perform a pg_restore_attribute_stats() on each match.
+ *
+ * XXX: the result set is sorted by attname, so perhaps we could do a binary
+ * search of the result set. Alternately we could collect the local attributes
+ * in a list and sort that by remote name, which would allow us to iterate via
+ * a merge.
+ *
+ * XXX: what should be done if match_found = false?
+ */
+ tupdesc = RelationGetDescr(relation);
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+ bool match_found = false;
+
+ /* Ignore dropped columns. */
+ if (TupleDescAttr(tupdesc, i)->attisdropped)
+ continue;
+
+ /* Ignore generated columns, but maybe this should fail the import? */
+ if (TupleDescAttr(tupdesc, i)->attgenerated)
+ continue;
+
+ attnum = TupleDescAttr(tupdesc, i)->attnum;
+
+ /* default remote_colname is attname */
+ remote_colname = NameStr(TupleDescAttr(tupdesc, i)->attname);
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), i + 1);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ for (int j = 0; j < PQntuples(res); j++)
+ {
+ char *attimport_sql;
+
+ if (PQgetisnull(res, j, ATTSTATS_ATTNAME))
+ continue;
+
+ if (strcmp(PQgetvalue(res, j, ATTSTATS_ATTNAME), remote_colname) != 0)
+ continue;
+
+ match_found = true;
+ attimport_sql = restore_attribute_stats_sql(res, j, schemaname_l, relname_l, attnum, server_version_num);
+
+ if (SPI_execute(attimport_sql, false, 1) != SPI_OK_SELECT)
+ {
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics import failed %s", attimport_sql)));
+ SPI_finish();
+ ReleaseConnection(conn);
+ pfree(attimport_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ pfree(attimport_sql);
+ }
+
+ /* TODO: should this be an error? What action could we take to remediate? */
+ if (!match_found)
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics found for %s.%s but no columns matched",
+ quote_identifier(schemaname),
+ quote_identifier(relname))));
+ }
+ PQclear(res);
+
+ /*
+ * pg_restore_relation_stats
+ */
+ if (!PQsendQueryParams(conn, relation_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, relation_sql);
+ SPI_finish();
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ res = pgfdw_get_result(conn);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS)
+ {
+ /* unable to get relation stats, fall back on table sampling */
+ pgfdw_report(INFO, res, conn, attribute_sql);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ relimport_sql = restore_relation_stats_sql(res, schemaname_l, relname_l, server_version_num);
+
+ if (SPI_execute(relimport_sql, false, 0) != SPI_OK_SELECT)
+ {
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Relation statistics import failed %s", relimport_sql)));
+ SPI_finish();
+ ReleaseConnection(conn);
+ pfree(relimport_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ pfree(relimport_sql);
+
+ SPI_finish();
+
+ return FDW_IMPORT_STATS_OK;
+}
+
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 3b7da128519..cddc57bacc9 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -1278,7 +1278,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -1287,6 +1288,8 @@ SELECT ftx.x1, ft2.c2, ftx.x8 FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2
SELECT ftx.x1, ft2.c2, ftx FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2
WHERE ftx.x1 = ft2.c1 AND ftx.x1 = 1; -- ERROR
SELECT sum(c2), array_agg(c8) FROM ft1 GROUP BY c8; -- ERROR
+ANALYZE ft1; -- WARNING
+ALTER FOREIGN TABLE ft1 OPTIONS ( fetch_stats 'false' );
ANALYZE ft1; -- ERROR
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE user_enum;
@@ -4376,6 +4379,38 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table', remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
base-commit: 2d756ebbe857e3d395d18350bf232300ebd23981
--
2.51.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-10-19 00:32 Corey Huinker <corey.huinker@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2025-10-19 00:32 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: pgsql-hackers
On Fri, Sep 12, 2025 at 1:17 AM Corey Huinker <corey.huinker@gmail.com>
wrote:
> Rebased.
>
Rebased again.
Attachments:
v3-0001-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 37.5K) download
From f44b3223c1a15fd7213b2227669ff400f8c01efa Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 7 Aug 2025 23:58:38 -0400
Subject: [PATCH v3] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via two new options, fetch_stats and remote_analyze,
both are available at the server level and table level. If fetch_stats
is true, then the ANALYZE command will first attempt to fetch statistics
from the remote table and import those statistics locally.
If remote_analyze is true, and if the first attempt to fetch remote
statistics found no attribute statistics, then an attempt will be made
to ANALYZE the remote table before a second and final attempt to fetch
remote statistics.
If no statistics are found, then ANALYZE will fall back to the normal
behavior of sampling and local analysis.
This operation will only work on remote relations that can have stored
statistics: tables, partitioned tables, and materialized views. If the
remote relation is a view then remote fetching/analyzing is just wasted
effort and the user is better of setting fetch_stats to false for that
table.
The default for fetch_stats is true at both server and table level. The
default for remote_analyze is false at both the server and table level.
In both cases, setting a value at the table level will override the
corresponding server-level setting.
---
src/include/foreign/fdwapi.h | 12 +
src/backend/commands/analyze.c | 46 +-
doc/src/sgml/postgres-fdw.sgml | 35 +-
.../postgres_fdw/expected/postgres_fdw.out | 64 +-
contrib/postgres_fdw/option.c | 10 +
contrib/postgres_fdw/postgres_fdw.c | 546 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 37 +-
7 files changed, 746 insertions(+), 4 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index fcd7e7027f3..eb6284979fb 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -19,6 +19,15 @@
/* avoid including explain_state.h here */
typedef struct ExplainState ExplainState;
+/* result of ImportStatistics */
+typedef enum
+{
+ FDW_IMPORT_STATS_OK = 0, /* was able to import statistics */
+ FDW_IMPORT_STATS_DISABLED, /* import disabled for this table */
+ FDW_IMPORT_STATS_NOTFOUND, /* no remote attribute stats found */
+ FDW_IMPORT_STATS_FAILED /* remote query failure of some kind */
+} FdwImportStatsResult;
+
/*
* Callback function signatures --- see fdwhandler.sgml for more info.
@@ -157,6 +166,8 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef FdwImportStatsResult (*ImportStatistics_function) (Relation relation);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +266,7 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index c2e216563c6..616333d5574 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -196,13 +196,57 @@ analyze_rel(Oid relid, RangeVar *relation,
{
/*
* For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * supports statistics import and/or analysis.
*/
FdwRoutine *fdwroutine;
bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
+ if (fdwroutine->ImportStatistics != NULL)
+ {
+ FdwImportStatsResult res;
+
+ /*
+ * Fetching pre-existing remote stats is not guaranteed to be a quick
+ * operation.
+ *
+ * XXX: Should this be it's own fetch type? If not, then there might be
+ * confusion when a long stats-fetch fails, followed by a regular analyze,
+ * which would make it look like the table was analyzed twice.
+ */
+ pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
+ RelationGetRelid(onerel));
+
+ res = fdwroutine->ImportStatistics(onerel);
+
+ pgstat_progress_end_command();
+
+ /*
+ * If we were able to import statistics, then there is no need to collect
+ * samples for local analysis.
+ */
+ switch(res)
+ {
+ case FDW_IMPORT_STATS_OK:
+ relation_close(onerel, NoLock);
+ return;
+ break;
+ case FDW_IMPORT_STATS_DISABLED:
+ break;
+ case FDW_IMPORT_STATS_NOTFOUND:
+ ereport(INFO,
+ (errmsg("Found no remote statistics for \"%s\"",
+ RelationGetRelationName(onerel))));
+ break;
+ case FDW_IMPORT_STATS_FAILED:
+ default:
+ ereport(INFO,
+ (errmsg("Fetching remote statistics from \"%s\" failed",
+ RelationGetRelationName(onerel))));
+ }
+ }
+
if (fdwroutine->AnalyzeForeignTable != NULL)
ok = fdwroutine->AnalyzeForeignTable(onerel,
&acquirefunc,
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 781a01067f7..c395d1061d5 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,39 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will first attempt to fetch and import the existing relation and
+ attribute statistics from the remote table, and only attempt regular
+ data sampling if no statistics were availble. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines wheter an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ is only meaningful if the foreign table has
+ <literal>fetch_stats</literal> enabled at either the server or table
+ level.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 91bbd0d8c73..6e9a0acedae 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -628,6 +628,7 @@ INSERT INTO loct_empty
SELECT id, 'AAA' || to_char(id, 'FM000') FROM generate_series(1, 100) id;
DELETE FROM loct_empty;
ANALYZE ft_empty;
+INFO: Found no remote statistics for "ft_empty"
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_empty ORDER BY c1;
QUERY PLAN
-------------------------------------------------------------------------------
@@ -4551,7 +4552,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -4568,6 +4570,9 @@ CONTEXT: whole-row reference to foreign table "ftx"
SELECT sum(c2), array_agg(c8) FROM ft1 GROUP BY c8; -- ERROR
ERROR: invalid input syntax for type integer: "foo"
CONTEXT: processing expression at position 2 in select list
+ANALYZE ft1; -- WARNING
+WARNING: invalid input syntax for type integer: "foo"
+ALTER FOREIGN TABLE ft1 OPTIONS ( fetch_stats 'false' );
ANALYZE ft1; -- ERROR
ERROR: invalid input syntax for type integer: "foo"
CONTEXT: column "c8" of foreign table "ft1"
@@ -7102,6 +7107,7 @@ INSERT INTO loct2 VALUES (1002, 'bar');
CREATE FOREIGN TABLE remt2 (c1 int, c2 text) SERVER loopback OPTIONS (table_name 'loct2');
ANALYZE loct1;
ANALYZE remt2;
+INFO: Found no remote statistics for "remt2"
SET enable_mergejoin TO false;
SET enable_hashjoin TO false;
SET enable_material TO false;
@@ -8784,6 +8790,7 @@ alter foreign table foo2 options (use_remote_estimate 'true');
create index i_loct1_f1 on loct1(f1);
create index i_foo_f1 on foo(f1);
analyze foo;
+INFO: Found no remote statistics for "foo2"
analyze loct1;
-- inner join; expressions in the clauses appear in the equivalence class list
explain (verbose, costs off)
@@ -9013,7 +9020,9 @@ insert into remt1 values (2, 'bar');
insert into remt2 values (1, 'foo');
insert into remt2 values (2, 'bar');
analyze remt1;
+INFO: Found no remote statistics for "remt1"
analyze remt2;
+INFO: Found no remote statistics for "remt2"
explain (verbose, costs off)
update parent set b = parent.b || remt2.b from remt2 where parent.a = remt2.a returning *;
QUERY PLAN
@@ -10313,6 +10322,8 @@ CREATE FOREIGN TABLE ftprt1_p1 PARTITION OF fprt1 FOR VALUES FROM (0) TO (250)
CREATE FOREIGN TABLE ftprt1_p2 PARTITION OF fprt1 FOR VALUES FROM (250) TO (500)
SERVER loopback OPTIONS (TABLE_NAME 'fprt1_p2');
ANALYZE fprt1;
+INFO: Found no remote statistics for "ftprt1_p1"
+INFO: Found no remote statistics for "ftprt1_p2"
ANALYZE fprt1_p1;
ANALYZE fprt1_p2;
CREATE TABLE fprt2 (a int, b int, c varchar) PARTITION BY RANGE(b);
@@ -10328,6 +10339,8 @@ ALTER TABLE fprt2 ATTACH PARTITION ftprt2_p1 FOR VALUES FROM (0) TO (250);
CREATE FOREIGN TABLE ftprt2_p2 PARTITION OF fprt2 FOR VALUES FROM (250) TO (500)
SERVER loopback OPTIONS (table_name 'fprt2_p2', use_remote_estimate 'true');
ANALYZE fprt2;
+INFO: Found no remote statistics for "ftprt2_p1"
+INFO: Found no remote statistics for "ftprt2_p2"
ANALYZE fprt2_p1;
ANALYZE fprt2_p2;
-- inner join three tables
@@ -10515,9 +10528,15 @@ CREATE FOREIGN TABLE fpagg_tab_p1 PARTITION OF pagg_tab FOR VALUES FROM (0) TO (
CREATE FOREIGN TABLE fpagg_tab_p2 PARTITION OF pagg_tab FOR VALUES FROM (10) TO (20) SERVER loopback OPTIONS (table_name 'pagg_tab_p2');
CREATE FOREIGN TABLE fpagg_tab_p3 PARTITION OF pagg_tab FOR VALUES FROM (20) TO (30) SERVER loopback OPTIONS (table_name 'pagg_tab_p3');
ANALYZE pagg_tab;
+INFO: Found no remote statistics for "fpagg_tab_p1"
+INFO: Found no remote statistics for "fpagg_tab_p2"
+INFO: Found no remote statistics for "fpagg_tab_p3"
ANALYZE fpagg_tab_p1;
+INFO: Found no remote statistics for "fpagg_tab_p1"
ANALYZE fpagg_tab_p2;
+INFO: Found no remote statistics for "fpagg_tab_p2"
ANALYZE fpagg_tab_p3;
+INFO: Found no remote statistics for "fpagg_tab_p3"
-- When GROUP BY clause matches with PARTITION KEY.
-- Plan with partitionwise aggregates is disabled
SET enable_partitionwise_aggregate TO false;
@@ -11463,6 +11482,8 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
EXPLAIN (VERBOSE, COSTS OFF)
@@ -11569,6 +11590,9 @@ CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
+INFO: Found no remote statistics for "async_p3"
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
QUERY PLAN
@@ -11605,6 +11629,8 @@ DROP TABLE base_tbl3;
CREATE TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000);
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
QUERY PLAN
@@ -12660,6 +12686,42 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table', remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 04788b7e8b3..7f069373e82 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,8 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +280,14 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_size is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 456b267f70b..096cd4d0fdd 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -22,6 +22,8 @@
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -402,6 +404,7 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static FdwImportStatsResult postgresImportStatistics(Relation relation);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +549,114 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+
+/* relallfrozen introduced in v18 */
+static const char *relstats_query_18 =
+ "SELECT c.relpages, c.reltuples, c.relallvisible, c.relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* trust reltuples = 0 as of v14 */
+static const char *relstats_query_14 =
+ "SELECT c.relpages, c.reltuples, c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case.)
+ * This ambiguity allegedly can cause the planner to choose inefficient
+ * plans after restoring to v18 or newer. To deal with this, let's just
+ * set reltuples to -1 in that case.
+ */
+static const char *relstats_query_default =
+ "SELECT c.relpages, "
+ "CASE c.reltuples WHEN 0 THEN -1 ELSE c.reltuples END AS reltuples, "
+ "c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns {
+ RELSTATS_RELPAGES = 0,
+ RELSTATS_RELTUPLES,
+ RELSTATS_RELALLVISIBLE,
+ RELSTATS_RELALLFROZEN,
+ RELSTATS_NUM_FIELDS
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+static const char *attstats_query_default =
+ "SELECT s.attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns {
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS
+};
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +706,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5047,440 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Process optional argument.
+ *
+ * Cannot be the first argument in the SQL function call.
+ *
+ * It is safe to presume that argname and argtype are quote-safe.
+ *
+ * Argument values can potentially be quite large, so free the quoted string
+ * after use.
+ */
+static void
+append_optional(StringInfo str, PGresult *res, int row, int field,
+ const char *argname, const char *argtype)
+{
+ if (!PQgetisnull(res, row, field))
+ {
+ /* Argument values can be quite large, so free after use */
+ char *argval_l = quote_literal_cstr(PQgetvalue(res, row, field));
+
+ appendStringInfo(str, ",\n\t'%s', %s::%s", argname, argval_l, argtype);
+
+ pfree(argval_l);
+ }
+}
+
+
+/*
+ * Generate a pg_restore_relation_stats command.
+ */
+static char *
+restore_relation_stats_sql(PGresult *res, const char *schemaname_l,
+ const char *relname_l,
+ const int server_version_num)
+{
+ StringInfoData sql;
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s",
+ server_version_num, schemaname_l, relname_l);
+
+ append_optional(&sql, res, 0, RELSTATS_RELPAGES, "relpages", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELTUPLES, "reltuples", "real");
+ append_optional(&sql, res, 0, RELSTATS_RELALLVISIBLE, "relallvisible", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELALLFROZEN, "relallfrozen", "integer");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Generate a pg_restore_attribute_stats command.
+ */
+static char *
+restore_attribute_stats_sql(PGresult *res, int row, const char *schemaname_l,
+ const char *relname_l, const AttrNumber attnum,
+ const int server_version_num)
+{
+ StringInfoData sql;
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s,\n"
+ "\t'attnum', %d::smallint,\n"
+ "\t'inherited', false::boolean",
+ server_version_num, schemaname_l, relname_l, attnum);
+
+ append_optional(&sql, res, row, ATTSTATS_NULL_FRAC, "null_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_AVG_WIDTH, "avg_width", "integer");
+ append_optional(&sql, res, row, ATTSTATS_N_DISTINCT, "n_distinct", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_VALS, "most_common_vals", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_FREQS, "most_common_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_HISTOGRAM_BOUNDS, "histogram_bounds", "text");
+ append_optional(&sql, res, row, ATTSTATS_CORRELATION, "correlation", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEMS, "most_common_elems", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEM_FREQS, "most_common_elem_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_ELEM_COUNT_HISTOGRAM, "elem_count_histogram", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_LENGTH_HISTOGRAM, "range_length_histogram", "text");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_EMPTY_FRAC, "range_empty_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_BOUNDS_HISTOGRAM, "range_bounds_histogram", "text");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static FdwImportStatsResult
+postgresImportStatistics(Relation relation)
+{
+
+ ForeignTable *table;
+ ForeignServer *server;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ bool fetch_stats = true;
+ bool remote_analyze = false;
+ int server_version_num;
+
+ const char *relation_sql;
+ const char *attribute_sql;
+ const char *schemaname;
+ const char *relname;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+
+ const char *schemaname_l;
+ const char *relname_l;
+
+ char *relimport_sql;
+
+ PGresult *res;
+ TupleDesc tupdesc;
+ const char *sql_params[2];
+ int sql_param_formats[2] = {0, 0};
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ fetch_stats = defGetBoolean(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ fetch_stats = defGetBoolean(def);
+ else if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ if (fetch_stats == false)
+ return FDW_IMPORT_STATS_DISABLED;
+
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+
+ relname = RelationGetRelationName(relation);
+
+ schemaname_l = quote_literal_cstr(schemaname);
+ relname_l = quote_literal_cstr(relname);
+
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+ sql_params[0] = remote_schemaname;
+ sql_params[1] = remote_relname;
+
+ if (server_version_num >= 180000)
+ relation_sql = relstats_query_18;
+ else if (server_version_num >= 140000)
+ relation_sql = relstats_query_14;
+ else
+ relation_sql = relstats_query_default;
+
+ if (server_version_num >= 170000)
+ attribute_sql = attstats_query_17;
+ else if (server_version_num >= 90200)
+ attribute_sql = attstats_query_9_2;
+ else if (server_version_num >= 90000)
+ attribute_sql = attstats_query_9_0;
+ else
+ attribute_sql = attstats_query_default;
+
+ /*
+ * pg_restore_attribute_stats
+ *
+ * We do this before relation stats because we may retry it if no stats were
+ * found.
+ */
+ if (!PQsendQueryParams(conn, attribute_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, attribute_sql);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ res = pgfdw_get_result(conn);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, res, conn, attribute_sql);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * If we got a query response of the right shape, but there were no rows,
+ * then the remote is just missing statistics
+ */
+ if (PQntuples(res) == 0)
+ {
+ StringInfoData buf;
+
+ PQclear(res);
+
+ /*
+ * If remote_analyze is not enabled, any failure to find statistics are
+ * considered temporary. This is not an error, but we should fall back
+ * to regular local analyzis if enabled.
+ */
+ if (!remote_analyze)
+ {
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_NOTFOUND;
+ }
+
+ /*
+ * Analyze the remote table and try again. If it's still empty, then that's
+ * an error indicating that we probably shouldn't do remote analysis going
+ * forward.
+ */
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s.%s",
+ quote_identifier(remote_schemaname),
+ quote_identifier(remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL || PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ pgfdw_report(NOTICE, res, conn, buf.data);
+ pfree(buf.data);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ PQclear(res);
+ pfree(buf.data);
+
+ /* retry attribute stats query */
+ if (!PQsendQueryParams(conn, attribute_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, attribute_sql);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+ res = pgfdw_get_result(conn);
+
+ /* getting nothing on the second try is a failure */
+ if (PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) == 0
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, res, conn, attribute_sql);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+ }
+
+ SPI_connect();
+
+ /*
+ * Walk all local table attributes looking for name matches in the result
+ * set and perform a pg_restore_attribute_stats() on each match.
+ *
+ * XXX: the result set is sorted by attname, so perhaps we could do a binary
+ * search of the result set. Alternately we could collect the local attributes
+ * in a list and sort that by remote name, which would allow us to iterate via
+ * a merge.
+ *
+ * XXX: what should be done if match_found = false?
+ */
+ tupdesc = RelationGetDescr(relation);
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+ bool match_found = false;
+
+ /* Ignore dropped columns. */
+ if (TupleDescAttr(tupdesc, i)->attisdropped)
+ continue;
+
+ /* Ignore generated columns, but maybe this should fail the import? */
+ if (TupleDescAttr(tupdesc, i)->attgenerated)
+ continue;
+
+ attnum = TupleDescAttr(tupdesc, i)->attnum;
+
+ /* default remote_colname is attname */
+ remote_colname = NameStr(TupleDescAttr(tupdesc, i)->attname);
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), i + 1);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ for (int j = 0; j < PQntuples(res); j++)
+ {
+ char *attimport_sql;
+
+ if (PQgetisnull(res, j, ATTSTATS_ATTNAME))
+ continue;
+
+ if (strcmp(PQgetvalue(res, j, ATTSTATS_ATTNAME), remote_colname) != 0)
+ continue;
+
+ match_found = true;
+ attimport_sql = restore_attribute_stats_sql(res, j, schemaname_l, relname_l, attnum, server_version_num);
+
+ if (SPI_execute(attimport_sql, false, 1) != SPI_OK_SELECT)
+ {
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics import failed %s", attimport_sql)));
+ SPI_finish();
+ ReleaseConnection(conn);
+ pfree(attimport_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ pfree(attimport_sql);
+ }
+
+ /* TODO: should this be an error? What action could we take to remediate? */
+ if (!match_found)
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics found for %s.%s but no columns matched",
+ quote_identifier(schemaname),
+ quote_identifier(relname))));
+ }
+ PQclear(res);
+
+ /*
+ * pg_restore_relation_stats
+ */
+ if (!PQsendQueryParams(conn, relation_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, relation_sql);
+ SPI_finish();
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ res = pgfdw_get_result(conn);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS)
+ {
+ /* unable to get relation stats, fall back on table sampling */
+ pgfdw_report(INFO, res, conn, attribute_sql);
+ PQclear(res);
+ ReleaseConnection(conn);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ relimport_sql = restore_relation_stats_sql(res, schemaname_l, relname_l, server_version_num);
+
+ if (SPI_execute(relimport_sql, false, 0) != SPI_OK_SELECT)
+ {
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Relation statistics import failed %s", relimport_sql)));
+ SPI_finish();
+ ReleaseConnection(conn);
+ pfree(relimport_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ pfree(relimport_sql);
+
+ SPI_finish();
+
+ return FDW_IMPORT_STATS_OK;
+}
+
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 3b7da128519..cddc57bacc9 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -1278,7 +1278,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -1287,6 +1288,8 @@ SELECT ftx.x1, ft2.c2, ftx.x8 FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2
SELECT ftx.x1, ft2.c2, ftx FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2
WHERE ftx.x1 = ft2.c1 AND ftx.x1 = 1; -- ERROR
SELECT sum(c2), array_agg(c8) FROM ft1 GROUP BY c8; -- ERROR
+ANALYZE ft1; -- WARNING
+ALTER FOREIGN TABLE ft1 OPTIONS ( fetch_stats 'false' );
ANALYZE ft1; -- ERROR
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE user_enum;
@@ -4376,6 +4379,38 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table', remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
base-commit: 615ff828e1cb8eaa2a987d4390c5c9970fc1a3e6
--
2.51.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-10-20 06:45 Michael Paquier <michael@paquier.xyz>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 2 replies; 89+ messages in thread
From: Michael Paquier @ 2025-10-20 06:45 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers@postgresql.org, Etsuro Fujita <etsuro.fujita@gmail.com>
On Sat, Oct 18, 2025 at 08:32:24PM -0400, Corey Huinker wrote:
> Rebased again.
Hearing an opinion from Fujita-san would be interesting here, so I am
adding him in CC. I have been looking a little bit at this patch.
+ ImportStatistics_function ImportStatistics;
All FDW callbacks are documented in fdwhandler.sgml. This new one is
not.
I am a bit uncomfortable regarding the design you are using here,
where the ImportStatistics callback, if defined, takes priority over
the existing AnalyzeForeignTable, especially regarding the fact that
both callbacks attempt to retrieve the same data, except that the
existing callback has a different idea of the timing to use to
retrieve reltuples and relpages. The original callback
AnalyzeForeignTable retrieves immediately the total number of pages
via SQL, to feed ANALYZE. reltuples is then fed to ANALYZE from a
callback function that that's defined in AnalyzeForeignTable().
My point is: rather than trying to implement a second solution with a
new callback, shouldn't we try to rework the existing callback so as
it would fit better with what you are trying to do here: feed data
that ANALYZE would then be in charge of inserting? Relying on
pg_restore_relation_stats() for the job feels incorrect to me knowing
that ANALYZE is the code path in charge of updating the stats of a
relation. The new callback is a shortcut that bypasses what ANALYZE
does, so the problem, at least it seems to me, is that we want to
retrieve all the data in a single step, like your new callback, not in
two steps, something that only the existing callback allows. Hence,
wouldn't it be more natural to retrieve the total number of pages and
reltuples from one callback, meaning that for local relations we
should delay RelationGetNumberOfBlocks() inside the existing
"acquire_sample_rows" callback (renaming it would make sense)? This
requires some redesign of AnalyzeForeignTable and the internals of
analyze.c, but it would let FDW extensions know about the potential
efficiency gain.
There is also a performance concern to be made with the patch, but as
it's an ANALYZE path that may be acceptable: if we fail the first
callback, then we may call the second callback.
Fujita-san, what do you think?
--
Michael
Attachments:
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-10-20 08:07 Michael Paquier <michael@paquier.xyz>
parent: Michael Paquier <michael@paquier.xyz>
1 sibling, 0 replies; 89+ messages in thread
From: Michael Paquier @ 2025-10-20 08:07 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers@postgresql.org, Etsuro Fujita <etsuro.fujita@gmail.com>
On Mon, Oct 20, 2025 at 03:45:14PM +0900, Michael Paquier wrote:
> On Sat, Oct 18, 2025 at 08:32:24PM -0400, Corey Huinker wrote:
> > Rebased again.
>
> Hearing an opinion from Fujita-san would be interesting here, so I am
> adding him in CC. I have been looking a little bit at this patch.
By the way, as far as I can see this patch is still in the past commit
fest:
https://commitfest.postgresql.org/patch/5959/
You may want to move it if you are planning to continue working on
that.
--
Michael
Attachments:
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-11-03 05:26 Corey Huinker <corey.huinker@gmail.com>
parent: Michael Paquier <michael@paquier.xyz>
1 sibling, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2025-11-03 05:26 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers@postgresql.org, Etsuro Fujita <etsuro.fujita@gmail.com>
>
> I am a bit uncomfortable regarding the design you are using here,
> where the ImportStatistics callback, if defined, takes priority over
> the existing AnalyzeForeignTable, especially regarding the fact that
> both callbacks attempt to retrieve the same data, except that the
> existing callback has a different idea of the timing to use to
> retrieve reltuples and relpages. The original callback
> AnalyzeForeignTable retrieves immediately the total number of pages
> via SQL, to feed ANALYZE. reltuples is then fed to ANALYZE from a
> callback function that that's defined in AnalyzeForeignTable().
>
They don't try to retrieve the same data. AnalyzeForeignTable tries to
retrieve a table sample which it feeds into the normal ANALYZE process. If
that sample is going to be any good, it has to be a lot of rows, that
that's a lot of network traffic.
ImportStatistics just grabs the results that ANALYZE computed for the
remote table, using a far better sample than we'd want to pull across the
wire.
> My point is: rather than trying to implement a second solution with a
> new callback, shouldn't we try to rework the existing callback so as
> it would fit better with what you are trying to do here: feed data
> that ANALYZE would then be in charge of inserting?
To do that, we would have to somehow generate fake data locally from the
pg_stats data that we did pull over the wire, just to have ANALYZE compute
it back down to the data we already had.
> Relying on
> pg_restore_relation_stats() for the job feels incorrect to me knowing
> that ANALYZE is the code path in charge of updating the stats of a
> relation.
That sounds like an argument for expanding ANALYZE to have syntax that will
digest pre-computed rows, essentially taking over what
pg_restore_relation_stats and pg_restore_attribute_stats already do, and
that idea was dismissed fairly early on in development, though I wasn't
against it at the time.
As it is, those two functions were developed to match what ANALYZE does.
pg_restore_relation_stats even briefly had inplace updates because that's
what ANALYZE did.
> The new callback is a shortcut that bypasses what ANALYZE
> does, so the problem, at least it seems to me, is that we want to
> retrieve all the data in a single step, like your new callback, not in
> two steps, something that only the existing callback allows. Hence,
> wouldn't it be more natural to retrieve the total number of pages and
> reltuples from one callback, meaning that for local relations we
> should delay RelationGetNumberOfBlocks() inside the existing
> "acquire_sample_rows" callback (renaming it would make sense)? This
> requires some redesign of AnalyzeForeignTable and the internals of
> analyze.c, but it would let FDW extensions know about the potential
> efficiency gain.
>
I wanted to make minimal disruption to the existing callbacks, but that may
have been misguided.
One problem I do see, however, is that the queries for fetching relation
(pg_class) stats should never fail and always return one row, even if the
values returned are meaningless. It's the query against pg_stats that lets
us know if 1) the database on the other side is a real-enough postgres and
2) the remote table is itself analyzed. Only once we're happy that we have
good attribute stats should we bother with the relation stats. All of this
logic is specific to postgres, so it was confined to postgres_fdw. I don't
know that other FDWs would be that much different, but minimizing the
generic impact was a goal.
I'll look at this again, but I'm not sure I'm going to come up with much
different.
> There is also a performance concern to be made with the patch, but as
> it's an ANALYZE path that may be acceptable: if we fail the first
> callback, then we may call the second callback.
>
I think the big win is the network traffic savings.
>
> Fujita-san, what do you think?
Very interested to know as well.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-11-21 18:35 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2025-11-21 18:35 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
Hi Corey,
This is an important feature. Thanks for working on it.
On Mon, Nov 3, 2025 at 2:26 PM Corey Huinker <corey.huinker@gmail.com> wrote:
>> My point is: rather than trying to implement a second solution with a
>> new callback, shouldn't we try to rework the existing callback so as
>> it would fit better with what you are trying to do here: feed data
>> that ANALYZE would then be in charge of inserting?
> To do that, we would have to somehow generate fake data locally from the pg_stats data that we did pull over the wire, just to have ANALYZE compute it back down to the data we already had.
>> Relying on
>> pg_restore_relation_stats() for the job feels incorrect to me knowing
>> that ANALYZE is the code path in charge of updating the stats of a
>> relation.
> That sounds like an argument for expanding ANALYZE to have syntax that will digest pre-computed rows, essentially taking over what pg_restore_relation_stats and pg_restore_attribute_stats already do, and that idea was dismissed fairly early on in development, though I wasn't against it at the time.
>
> As it is, those two functions were developed to match what ANALYZE does. pg_restore_relation_stats even briefly had inplace updates because that's what ANALYZE did.
To me it seems like a good idea to rely on pg_restore_relation_stats
and pg_restore_attribute_stats, rather than doing some rework on
analyze.c; IMO I don't think it's a good idea to do such a thing for
something rather special like this.
>> The new callback is a shortcut that bypasses what ANALYZE
>> does, so the problem, at least it seems to me, is that we want to
>> retrieve all the data in a single step, like your new callback, not in
>> two steps, something that only the existing callback allows. Hence,
>> wouldn't it be more natural to retrieve the total number of pages and
>> reltuples from one callback, meaning that for local relations we
>> should delay RelationGetNumberOfBlocks() inside the existing
>> "acquire_sample_rows" callback (renaming it would make sense)? This
>> requires some redesign of AnalyzeForeignTable and the internals of
>> analyze.c, but it would let FDW extensions know about the potential
>> efficiency gain.
> I wanted to make minimal disruption to the existing callbacks, but that may have been misguided.
+1 for the minimal disruption.
Other initial comments:
The commit message says:
This is managed via two new options, fetch_stats and remote_analyze,
both are available at the server level and table level. If fetch_stats
is true, then the ANALYZE command will first attempt to fetch statistics
from the remote table and import those statistics locally.
If remote_analyze is true, and if the first attempt to fetch remote
statistics found no attribute statistics, then an attempt will be made
to ANALYZE the remote table before a second and final attempt to fetch
remote statistics.
If no statistics are found, then ANALYZE will fall back to the normal
behavior of sampling and local analysis.
I think the first step assumes that the remote stats are up-to-date;
if they aren't, it would cause a regression. (If the remote relation
is a plain table, they are likely to be up-to-date, but for example,
if it is a foreign table, it's possible that they are stale.) So how
about making it the user's responsibility to make them up-to-date? If
doing so, we wouldn't need to do the second and third steps anymore,
making the patch simple.
On the other hand:
This operation will only work on remote relations that can have stored
statistics: tables, partitioned tables, and materialized views. If the
remote relation is a view then remote fetching/analyzing is just wasted
effort and the user is better of setting fetch_stats to false for that
table.
I'm not sure the waste effort is acceptable; IMO, if the remote table
is a view, I think that the system should detect that in some way, and
then just do the normal ANALYZE processing.
That's it for now.
My apologies for the delayed response.
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-11-21 21:31 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 2 replies; 89+ messages in thread
From: Corey Huinker @ 2025-11-21 21:31 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
>
> Other initial comments:
>
> The commit message says:
>
> This is managed via two new options, fetch_stats and remote_analyze,
> both are available at the server level and table level. If fetch_stats
> is true, then the ANALYZE command will first attempt to fetch
> statistics
> from the remote table and import those statistics locally.
>
> If remote_analyze is true, and if the first attempt to fetch remote
> statistics found no attribute statistics, then an attempt will be made
> to ANALYZE the remote table before a second and final attempt to fetch
> remote statistics.
>
> If no statistics are found, then ANALYZE will fall back to the normal
> behavior of sampling and local analysis.
>
> I think the first step assumes that the remote stats are up-to-date;
> if they aren't, it would cause a regression. (If the remote relation
> is a plain table, they are likely to be up-to-date, but for example,
> if it is a foreign table, it's possible that they are stale.) So how
> about making it the user's responsibility to make them up-to-date? If
> doing so, we wouldn't need to do the second and third steps anymore,
> making the patch simple.
>
Obviously there is no way to know the quality/freshness of remote stats if
they are found.
The analyze option was borne of feedback from other postgres hackers while
brainstorming on what this option might look like. I don't think we *need*
this extra option for the feature to be a success, but it's relative
simplicity did make me want to put it out there to see who else liked it.
>
> On the other hand:
>
> This operation will only work on remote relations that can have stored
> statistics: tables, partitioned tables, and materialized views. If the
> remote relation is a view then remote fetching/analyzing is just wasted
> effort and the user is better of setting fetch_stats to false for that
> table.
>
> I'm not sure the waste effort is acceptable; IMO, if the remote table
> is a view, I think that the system should detect that in some way, and
> then just do the normal ANALYZE processing.
>
The stats fetch query is pretty light, but I can see fetching the relkind
along with the relstats, and making decisions on whether to continue from
there, only applying the relstats after attrstats have been successfully
applied.
> That's it for now.
>
I'll see what I can do to make that work.
> My apologies for the delayed response.
>
Valuable responses are worth waiting for.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-11-23 07:27 Corey Huinker <corey.huinker@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 2 replies; 89+ messages in thread
From: Corey Huinker @ 2025-11-23 07:27 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
>
>
>
>> My apologies for the delayed response.
>>
>
> Valuable responses are worth waiting for.
>
I've reorganized some things a bit, mostly to make resource cleanup
simpler.
Attachments:
v4-0001-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 41.2K) download
From c387c379f4a8ba83073fd3e8d697368fe3250aa4 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 7 Aug 2025 23:58:38 -0400
Subject: [PATCH v4] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via two new options, fetch_stats and remote_analyze,
both are available at the server level and table level. If fetch_stats
is true, then the ANALYZE command will first attempt to fetch statistics
from the remote table and import those statistics locally.
If remote_analyze is true, and if the first attempt to fetch remote
statistics found no attribute statistics, then an attempt will be made
to ANALYZE the remote table before a second and final attempt to fetch
remote statistics.
If no statistics are found, then ANALYZE will fall back to the normal
behavior of sampling and local analysis.
This operation will only work on remote relations that can have stored
statistics: tables, partitioned tables, and materialized views. If the
remote relation is a view then remote fetching/analyzing is just wasted
effort and the user is better of setting fetch_stats to false for that
table.
The default for fetch_stats is true at both server and table level. The
default for remote_analyze is false at both the server and table level.
In both cases, setting a value at the table level will override the
corresponding server-level setting.
---
src/include/foreign/fdwapi.h | 12 +
src/backend/commands/analyze.c | 45 +-
doc/src/sgml/postgres-fdw.sgml | 35 +-
.../postgres_fdw/expected/postgres_fdw.out | 64 +-
contrib/postgres_fdw/option.c | 10 +
contrib/postgres_fdw/postgres_fdw.c | 665 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 37 +-
7 files changed, 864 insertions(+), 4 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index fcd7e7027f3..eb6284979fb 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -19,6 +19,15 @@
/* avoid including explain_state.h here */
typedef struct ExplainState ExplainState;
+/* result of ImportStatistics */
+typedef enum
+{
+ FDW_IMPORT_STATS_OK = 0, /* was able to import statistics */
+ FDW_IMPORT_STATS_DISABLED, /* import disabled for this table */
+ FDW_IMPORT_STATS_NOTFOUND, /* no remote attribute stats found */
+ FDW_IMPORT_STATS_FAILED /* remote query failure of some kind */
+} FdwImportStatsResult;
+
/*
* Callback function signatures --- see fdwhandler.sgml for more info.
@@ -157,6 +166,8 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef FdwImportStatsResult (*ImportStatistics_function) (Relation relation);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +266,7 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 25089fae3e0..464a3e4b3b0 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -196,13 +196,56 @@ analyze_rel(Oid relid, RangeVar *relation,
{
/*
* For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * supports statistics import and/or analysis.
*/
FdwRoutine *fdwroutine;
bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
+ if (fdwroutine->ImportStatistics != NULL)
+ {
+ FdwImportStatsResult res;
+
+ /*
+ * Fetching pre-existing remote stats is not guaranteed to be a quick
+ * operation.
+ *
+ * XXX: Should this be it's own fetch type? If not, then there might be
+ * confusion when a long stats-fetch fails, followed by a regular analyze,
+ * which would make it look like the table was analyzed twice.
+ */
+ pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
+ RelationGetRelid(onerel));
+
+ res = fdwroutine->ImportStatistics(onerel);
+
+ pgstat_progress_end_command();
+
+ /*
+ * If we were able to import statistics, then there is no need to collect
+ * samples for local analysis.
+ */
+ switch(res)
+ {
+ case FDW_IMPORT_STATS_OK:
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ case FDW_IMPORT_STATS_DISABLED:
+ break;
+ case FDW_IMPORT_STATS_NOTFOUND:
+ ereport(INFO,
+ errmsg("Found no remote statistics for \"%s\"",
+ RelationGetRelationName(onerel)));
+ break;
+ case FDW_IMPORT_STATS_FAILED:
+ default:
+ ereport(INFO,
+ errmsg("Fetching remote statistics from \"%s\" failed",
+ RelationGetRelationName(onerel)));
+ }
+ }
+
if (fdwroutine->AnalyzeForeignTable != NULL)
ok = fdwroutine->AnalyzeForeignTable(onerel,
&acquirefunc,
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 9b032fbf675..656897d89e0 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,39 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will first attempt to fetch and import the existing relation and
+ attribute statistics from the remote table, and only attempt regular
+ data sampling if no statistics were availble. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines wheter an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ is only meaningful if the foreign table has
+ <literal>fetch_stats</literal> enabled at either the server or table
+ level.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index cd28126049d..825d4b89590 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -628,6 +628,7 @@ INSERT INTO loct_empty
SELECT id, 'AAA' || to_char(id, 'FM000') FROM generate_series(1, 100) id;
DELETE FROM loct_empty;
ANALYZE ft_empty;
+INFO: Found no remote statistics for "ft_empty"
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_empty ORDER BY c1;
QUERY PLAN
-------------------------------------------------------------------------------
@@ -4551,7 +4552,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -4568,6 +4570,9 @@ CONTEXT: whole-row reference to foreign table "ftx"
SELECT sum(c2), array_agg(c8) FROM ft1 GROUP BY c8; -- ERROR
ERROR: invalid input syntax for type integer: "foo"
CONTEXT: processing expression at position 2 in select list
+ANALYZE ft1; -- WARNING
+WARNING: invalid input syntax for type integer: "foo"
+ALTER FOREIGN TABLE ft1 OPTIONS ( fetch_stats 'false' );
ANALYZE ft1; -- ERROR
ERROR: invalid input syntax for type integer: "foo"
CONTEXT: column "c8" of foreign table "ft1"
@@ -7102,6 +7107,7 @@ INSERT INTO loct2 VALUES (1002, 'bar');
CREATE FOREIGN TABLE remt2 (c1 int, c2 text) SERVER loopback OPTIONS (table_name 'loct2');
ANALYZE loct1;
ANALYZE remt2;
+INFO: Found no remote statistics for "remt2"
SET enable_mergejoin TO false;
SET enable_hashjoin TO false;
SET enable_material TO false;
@@ -8784,6 +8790,7 @@ alter foreign table foo2 options (use_remote_estimate 'true');
create index i_loct1_f1 on loct1(f1);
create index i_foo_f1 on foo(f1);
analyze foo;
+INFO: Found no remote statistics for "foo2"
analyze loct1;
-- inner join; expressions in the clauses appear in the equivalence class list
explain (verbose, costs off)
@@ -9013,7 +9020,9 @@ insert into remt1 values (2, 'bar');
insert into remt2 values (1, 'foo');
insert into remt2 values (2, 'bar');
analyze remt1;
+INFO: Found no remote statistics for "remt1"
analyze remt2;
+INFO: Found no remote statistics for "remt2"
explain (verbose, costs off)
update parent set b = parent.b || remt2.b from remt2 where parent.a = remt2.a returning *;
QUERY PLAN
@@ -10313,6 +10322,8 @@ CREATE FOREIGN TABLE ftprt1_p1 PARTITION OF fprt1 FOR VALUES FROM (0) TO (250)
CREATE FOREIGN TABLE ftprt1_p2 PARTITION OF fprt1 FOR VALUES FROM (250) TO (500)
SERVER loopback OPTIONS (TABLE_NAME 'fprt1_p2');
ANALYZE fprt1;
+INFO: Found no remote statistics for "ftprt1_p1"
+INFO: Found no remote statistics for "ftprt1_p2"
ANALYZE fprt1_p1;
ANALYZE fprt1_p2;
CREATE TABLE fprt2 (a int, b int, c varchar) PARTITION BY RANGE(b);
@@ -10328,6 +10339,8 @@ ALTER TABLE fprt2 ATTACH PARTITION ftprt2_p1 FOR VALUES FROM (0) TO (250);
CREATE FOREIGN TABLE ftprt2_p2 PARTITION OF fprt2 FOR VALUES FROM (250) TO (500)
SERVER loopback OPTIONS (table_name 'fprt2_p2', use_remote_estimate 'true');
ANALYZE fprt2;
+INFO: Found no remote statistics for "ftprt2_p1"
+INFO: Found no remote statistics for "ftprt2_p2"
ANALYZE fprt2_p1;
ANALYZE fprt2_p2;
-- inner join three tables
@@ -10515,9 +10528,15 @@ CREATE FOREIGN TABLE fpagg_tab_p1 PARTITION OF pagg_tab FOR VALUES FROM (0) TO (
CREATE FOREIGN TABLE fpagg_tab_p2 PARTITION OF pagg_tab FOR VALUES FROM (10) TO (20) SERVER loopback OPTIONS (table_name 'pagg_tab_p2');
CREATE FOREIGN TABLE fpagg_tab_p3 PARTITION OF pagg_tab FOR VALUES FROM (20) TO (30) SERVER loopback OPTIONS (table_name 'pagg_tab_p3');
ANALYZE pagg_tab;
+INFO: Found no remote statistics for "fpagg_tab_p1"
+INFO: Found no remote statistics for "fpagg_tab_p2"
+INFO: Found no remote statistics for "fpagg_tab_p3"
ANALYZE fpagg_tab_p1;
+INFO: Found no remote statistics for "fpagg_tab_p1"
ANALYZE fpagg_tab_p2;
+INFO: Found no remote statistics for "fpagg_tab_p2"
ANALYZE fpagg_tab_p3;
+INFO: Found no remote statistics for "fpagg_tab_p3"
-- When GROUP BY clause matches with PARTITION KEY.
-- Plan with partitionwise aggregates is disabled
SET enable_partitionwise_aggregate TO false;
@@ -11463,6 +11482,8 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
EXPLAIN (VERBOSE, COSTS OFF)
@@ -11569,6 +11590,9 @@ CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
+INFO: Found no remote statistics for "async_p3"
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
QUERY PLAN
@@ -11610,6 +11634,8 @@ DROP TABLE base_tbl3;
CREATE TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000);
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
QUERY PLAN
@@ -12665,6 +12691,42 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table', remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 04788b7e8b3..7f069373e82 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,8 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +280,14 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_size is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 06b52c65300..6f732d1e588 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -22,6 +22,8 @@
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -317,6 +319,13 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
/*
* SQL functions
*/
@@ -402,6 +411,7 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static FdwImportStatsResult postgresImportStatistics(Relation relation);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +556,115 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+
+/* relallfrozen introduced in v18 */
+static const char *relstats_query_18 =
+ "SELECT c.relkind, c.relpages, c.reltuples, c.relallvisible, c.relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* trust reltuples = 0 as of v14 */
+static const char *relstats_query_14 =
+ "SELECT c.relkind, c.relpages, c.reltuples, c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case.)
+ * This ambiguity allegedly can cause the planner to choose inefficient
+ * plans after restoring to v18 or newer. To deal with this, let's just
+ * set reltuples to -1 in that case.
+ */
+static const char *relstats_query_default =
+ "SELECT c.relkind, c.relpages, "
+ "CASE c.reltuples WHEN 0 THEN -1 ELSE c.reltuples END AS reltuples, "
+ "c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns {
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_RELALLVISIBLE,
+ RELSTATS_RELALLFROZEN,
+ RELSTATS_NUM_FIELDS
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+static const char *attstats_query_default =
+ "SELECT s.attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns {
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS
+};
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +714,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5055,551 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Process optional argument.
+ *
+ * Cannot be the first argument in the SQL function call.
+ *
+ * It is safe to presume that argname and argtype are quote-safe.
+ *
+ * Argument values can potentially be quite large, so free the quoted string
+ * after use.
+ */
+static void
+append_optional(StringInfo str, PGresult *res, int row, int field,
+ const char *argname, const char *argtype)
+{
+ if (!PQgetisnull(res, row, field))
+ {
+ /* Argument values can be quite large, so free after use */
+ char *argval_l = quote_literal_cstr(PQgetvalue(res, row, field));
+
+ appendStringInfo(str, ",\n\t'%s', %s::%s", argname, argval_l, argtype);
+
+ pfree(argval_l);
+ }
+}
+
+
+/*
+ * Generate a pg_restore_relation_stats command.
+ */
+static char *
+restore_relation_stats_sql(PGresult *res, const char *schemaname,
+ const char *relname, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s",
+ server_version_num, schemaname_l, relname_l);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, 0, RELSTATS_RELPAGES, "relpages", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELTUPLES, "reltuples", "real");
+ append_optional(&sql, res, 0, RELSTATS_RELALLVISIBLE, "relallvisible", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELALLFROZEN, "relallfrozen", "integer");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Generate a pg_restore_attribute_stats command.
+ */
+static char *
+restore_attribute_stats_sql(PGresult *res, int row,
+ const char *schemaname, const char *relname,
+ const AttrNumber attnum, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s,\n"
+ "\t'attnum', %d::smallint,\n"
+ "\t'inherited', false::boolean",
+ server_version_num, schemaname_l, relname_l, attnum);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, row, ATTSTATS_NULL_FRAC, "null_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_AVG_WIDTH, "avg_width", "integer");
+ append_optional(&sql, res, row, ATTSTATS_N_DISTINCT, "n_distinct", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_VALS, "most_common_vals", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_FREQS, "most_common_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_HISTOGRAM_BOUNDS, "histogram_bounds", "text");
+ append_optional(&sql, res, row, ATTSTATS_CORRELATION, "correlation", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEMS, "most_common_elems", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEM_FREQS, "most_common_elem_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_ELEM_COUNT_HISTOGRAM, "elem_count_histogram", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_LENGTH_HISTOGRAM, "range_length_histogram", "text");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_EMPTY_FRAC, "range_empty_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_BOUNDS_HISTOGRAM, "range_bounds_histogram", "text");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+static FdwImportStatsResult
+import_fetched_statistics(Relation relation, int server_version_num,
+ const char *schemaname, const char *relname,
+ RemoteStatsResults *remstats)
+{
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int spirc;
+ char *relimport_sql;
+
+ /*
+ * Walk all local table attributes looking for name matches in the result
+ * set and perform a pg_restore_attribute_stats() on each match.
+ *
+ * XXX: the result set is sorted by attname, so perhaps we could do a binary
+ * search of the result set. Alternately we could collect the local attributes
+ * in a list and sort that by remote name, which would allow us to iterate via
+ * a merge.
+ *
+ * XXX: what should be done if match_found = false?
+ */
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+ bool match_found = false;
+
+ /* Ignore dropped columns. */
+ if (TupleDescAttr(tupdesc, i)->attisdropped)
+ continue;
+
+ /* Ignore generated columns, but maybe this should fail the import? */
+ if (TupleDescAttr(tupdesc, i)->attgenerated)
+ continue;
+
+ attnum = TupleDescAttr(tupdesc, i)->attnum;
+
+ /* default remote_colname is attname */
+ remote_colname = NameStr(TupleDescAttr(tupdesc, i)->attname);
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), i + 1);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ for (int j = 0; j < PQntuples(remstats->att); j++)
+ {
+ char *attimport_sql;
+ PGresult *res = remstats->att;
+
+ /* Skip results where we don't have no attribute name to compare */
+ if (PQgetisnull(res, j, ATTSTATS_ATTNAME))
+ continue;
+
+ /* Keep skipping name non-matches */
+ if (strcmp(PQgetvalue(res, j, ATTSTATS_ATTNAME), remote_colname) != 0)
+ continue;
+
+ match_found = true;
+ attimport_sql = restore_attribute_stats_sql(res, j, schemaname,
+ relname, attnum, server_version_num);
+
+ spirc = SPI_execute(attimport_sql, false, 1);
+ pfree(attimport_sql);
+
+ if (spirc != SPI_OK_SELECT)
+ {
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics import failed %s", attimport_sql)));
+ return FDW_IMPORT_STATS_FAILED;
+ }
+ }
+
+ /* TODO: should this be an error? What action could we take to remediate? */
+ if (!match_found)
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics found for %s.%s but no columns matched",
+ quote_identifier(schemaname),
+ quote_identifier(relname))));
+ }
+
+ relimport_sql = restore_relation_stats_sql(remstats->rel, schemaname, relname,
+ server_version_num);
+
+ spirc = SPI_execute(relimport_sql, false, 1);
+
+ if (spirc != SPI_OK_SELECT)
+ {
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Relation statistics import failed %s", relimport_sql)));
+ return FDW_IMPORT_STATS_FAILED;
+ }
+ pfree(relimport_sql);
+
+ return FDW_IMPORT_STATS_OK;
+}
+
+/*
+ * Analyze a remote table.
+ */
+static bool
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+ bool success = false;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s.%s",
+ quote_identifier(remote_schemaname),
+ quote_identifier(remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res != NULL)
+ {
+ if (PQresultStatus(res) == PGRES_COMMAND_OK)
+ success = true;
+ else
+ pgfdw_report(NOTICE, res, conn, buf.data);
+
+ PQclear(res);
+ }
+ else
+ ereport(INFO,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Unable to ANALYZE remote table %s.%s.",
+ quote_identifier(remote_schemaname),
+ quote_identifier(remote_relname)));
+
+ pfree(buf.data);
+ return success;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static FdwImportStatsResult
+fetch_remote_statistics(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ bool remote_analyze, RemoteStatsResults *remstats)
+{
+ const char *sql_params[2] = { remote_schemaname, remote_relname };
+ int sql_param_formats[2] = {0, 0};
+
+ const char *relation_sql;
+ const char *attribute_sql;
+
+ char relkind;
+
+ if (server_version_num >= 180000)
+ relation_sql = relstats_query_18;
+ else if (server_version_num >= 140000)
+ relation_sql = relstats_query_14;
+ else
+ relation_sql = relstats_query_default;
+
+ if (server_version_num >= 170000)
+ attribute_sql = attstats_query_17;
+ else if (server_version_num >= 90200)
+ attribute_sql = attstats_query_9_2;
+ else if (server_version_num >= 90000)
+ attribute_sql = attstats_query_9_0;
+ else
+ attribute_sql = attstats_query_default;
+
+ /*
+ * Fetch basic relation stats.
+ */
+ if (!PQsendQueryParams(conn, relation_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, relation_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ remstats->rel = pgfdw_get_result(conn);
+
+ if (remstats->rel == NULL
+ || PQresultStatus(remstats->rel) != PGRES_TUPLES_OK
+ || PQntuples(remstats->rel) != 1
+ || PQnfields(remstats->rel) != RELSTATS_NUM_FIELDS
+ || PQgetisnull(remstats->rel, 0, RELSTATS_RELKIND))
+ {
+ /* unable to get relation stats, fall back on table sampling */
+ pgfdw_report(INFO, remstats->rel, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously can't
+ * support a foreign table.
+ */
+ relkind = *PQgetvalue(remstats->rel, 0, RELSTATS_RELKIND);
+
+ switch(relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ ereport(INFO,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Remote table %s.%s does not support statistics.",
+ quote_identifier(remote_schemaname),
+ quote_identifier(remote_relname)),
+ errdetail("Remote relation if of relkind \"%c\"", relkind));
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /* See if it actually has any attribute stats. */
+ if (!PQsendQueryParams(conn, attribute_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ remstats->att = pgfdw_get_result(conn);
+ if (remstats->att == NULL
+ || PQresultStatus(remstats->att) != PGRES_TUPLES_OK
+ || PQnfields(remstats->att) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, remstats->att, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * If we got attribute statistics results, then we are done with fetching.
+ */
+ if (PQntuples(remstats->att) > 0)
+ return FDW_IMPORT_STATS_OK;
+
+ /*
+ * If remote_analyze is not enabled, then a lack of fetched stats is viewed
+ * as a temporary problem that may be solved later when the remote server
+ * analyzes the table.
+ */
+ if (!remote_analyze)
+ return FDW_IMPORT_STATS_NOTFOUND;
+
+ /*
+ * Clear off any existing fetched statistics.
+ */
+ PQclear(remstats->att);
+ PQclear(remstats->rel);
+ remstats->att = NULL;
+ remstats->rel = NULL;
+
+ /*
+ * Analyze the remote table.
+ *
+ * If it's still empty afterward, then that's an error indicating that
+ * remote_analyze should probably be disabled.
+ */
+ if (!analyze_remote_table(conn, remote_schemaname, remote_relname))
+ return FDW_IMPORT_STATS_FAILED;
+
+ /*
+ * Re-fetch attribute stats query. If there still are no attribute stats then
+ * it's an error.
+ */
+ if (!PQsendQueryParams(conn, attribute_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ remstats->att = pgfdw_get_result(conn);
+
+ /* Getting nothing on the second try is a failure */
+ if (remstats->att == NULL
+ || PQresultStatus(remstats->att) != PGRES_TUPLES_OK
+ || PQntuples(remstats->att) == 0
+ || PQnfields(remstats->att) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, remstats->att, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Re-fetch basic relation stats, as they have been updated.
+ */
+ if (!PQsendQueryParams(conn, relation_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, relation_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ remstats->rel = pgfdw_get_result(conn);
+
+ if (remstats->rel == NULL
+ || PQresultStatus(remstats->rel) != PGRES_TUPLES_OK
+ || PQntuples(remstats->rel) != 1
+ || PQnfields(remstats->rel) != RELSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, remstats->rel, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ return FDW_IMPORT_STATS_OK;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static FdwImportStatsResult
+postgresImportStatistics(Relation relation)
+{
+
+ ForeignTable *table;
+ ForeignServer *server;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ bool fetch_stats = true;
+ bool remote_analyze = false;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+
+ FdwImportStatsResult fisr = FDW_IMPORT_STATS_OK;
+
+ RemoteStatsResults remstats = { .rel = NULL, .att = NULL };
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ fetch_stats = defGetBoolean(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ fetch_stats = defGetBoolean(def);
+ else if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ if (!fetch_stats)
+ return FDW_IMPORT_STATS_DISABLED;
+
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+
+ relname = RelationGetRelationName(relation);
+
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ fisr = fetch_remote_statistics(conn, server_version_num,
+ remote_schemaname, remote_relname,
+ remote_analyze, &remstats);
+
+ ReleaseConnection(conn);
+
+ /* If we have successfully fetched stats, then try to import them */
+ if (fisr == FDW_IMPORT_STATS_OK)
+ {
+ SPI_connect();
+ fisr = import_fetched_statistics(relation, server_version_num,
+ schemaname, relname, &remstats);
+ SPI_finish();
+ }
+
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+
+ return fisr;
+}
+
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 9a8f9e28135..09a98c860f1 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -1278,7 +1278,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -1287,6 +1288,8 @@ SELECT ftx.x1, ft2.c2, ftx.x8 FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2
SELECT ftx.x1, ft2.c2, ftx FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2
WHERE ftx.x1 = ft2.c1 AND ftx.x1 = 1; -- ERROR
SELECT sum(c2), array_agg(c8) FROM ft1 GROUP BY c8; -- ERROR
+ANALYZE ft1; -- WARNING
+ALTER FOREIGN TABLE ft1 OPTIONS ( fetch_stats 'false' );
ANALYZE ft1; -- ERROR
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE user_enum;
@@ -4379,6 +4382,38 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table', remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
base-commit: 7d9043aee803bf9bf3307ce5f45f3464ea288cb1
--
2.51.1
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-11-24 09:25 Chao Li <li.evan.chao@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 0 replies; 89+ messages in thread
From: Chao Li @ 2025-11-24 09:25 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
> On Nov 23, 2025, at 15:27, Corey Huinker <corey.huinker@gmail.com> wrote:
>
> My apologies for the delayed response.
>
> Valuable responses are worth waiting for.
>
> I've reorganized some things a bit, mostly to make resource cleanup simpler.
> <v4-0001-Add-remote-statistics-fetching-to-postgres_fdw.patch>
Few comments:
1 - commit message
```
effort and the user is better of setting fetch_stats to false for that
```
I guess “of” should be “off”
2 - postgres-fdw.sgml
```
+ server, determines wheter an <command>ANALYZE</command> on a foreign
```
Typo: wheter => whether
3 - postgres-fdw.sgml
```
+ data sampling if no statistics were availble. This option is only
```
Typo: availble => available
4 - option.c
```
+ /* fetch_size is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
```
In the comment, I guess fetch_size should be fetch_stats.
5 - analyze.c
```
+ * XXX: Should this be it's own fetch type? If not, then there might be
```
Typo: “it’s own” => “its own”
6 - analyze.c
```
+ case FDW_IMPORT_STATS_NOTFOUND:
+ ereport(INFO,
+ errmsg("Found no remote statistics for \"%s\"",
+ RelationGetRelationName(onerel)));
```
`Found no remote statistics for \"%s\””` could be rephrased as `""No remote statistics found for foreign table \"%s\””`, sounds better wording in server log.
Also, I wonder if this message at INFO level is too noisy?
7 - postgres_fdw.c
```
+ default:
+ ereport(INFO,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Remote table %s.%s does not support statistics.",
+ quote_identifier(remote_schemaname),
+ quote_identifier(remote_relname)),
+ errdetail("Remote relation if of relkind \"%c\"", relkind));
```
I think “if of” should be “is of”.
8 - postgres_fdw.c
```
+ errmsg("Attribute statistics found for %s.%s but no columns matched",
+ quote_identifier(schemaname),
+ quote_identifier(relname))));
```
Instead of using "%s.%s” and calling quote_identifier() twice, there is a simple function to use: quote_qualified_identifier(schemaname, relname).
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-11-27 12:46 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2025-11-27 12:46 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
On Sat, Nov 22, 2025 at 6:31 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>> Other initial comments:
>>
>> The commit message says:
>>
>> This is managed via two new options, fetch_stats and remote_analyze,
>> both are available at the server level and table level. If fetch_stats
>> is true, then the ANALYZE command will first attempt to fetch statistics
>> from the remote table and import those statistics locally.
>>
>> If remote_analyze is true, and if the first attempt to fetch remote
>> statistics found no attribute statistics, then an attempt will be made
>> to ANALYZE the remote table before a second and final attempt to fetch
>> remote statistics.
>>
>> If no statistics are found, then ANALYZE will fall back to the normal
>> behavior of sampling and local analysis.
>>
>> I think the first step assumes that the remote stats are up-to-date;
>> if they aren't, it would cause a regression. (If the remote relation
>> is a plain table, they are likely to be up-to-date, but for example,
>> if it is a foreign table, it's possible that they are stale.) So how
>> about making it the user's responsibility to make them up-to-date? If
>> doing so, we wouldn't need to do the second and third steps anymore,
>> making the patch simple.
> Obviously there is no way to know the quality/freshness of remote stats if they are found.
>
> The analyze option was borne of feedback from other postgres hackers while brainstorming on what this option might look like. I don't think we *need* this extra option for the feature to be a success, but it's relative simplicity did make me want to put it out there to see who else liked it.
Actually, I have some concerns about the ANALYZE and fall-back
options. As for the former, if the remote user didn't have the
MAINTAIN privilege on the remote table, remote ANALYZE would be just a
waste effort. As for the latter, imagine the situation where a user
ANALYZEs a foreign table whose remote table is significantly large.
When the previous attempts fail, the user might want to re-try to
import remote stats after ANALYZEing the remote table in the remote
side in some way, rather than postgres_fdw automatically falling back
to the normal lengthy processing. I think just throwing an error if
the first attempt fails would make the system not only simple but
reliable while providing some flexibility to users.
>> On the other hand:
>>
>> This operation will only work on remote relations that can have stored
>> statistics: tables, partitioned tables, and materialized views. If the
>> remote relation is a view then remote fetching/analyzing is just wasted
>> effort and the user is better of setting fetch_stats to false for that
>> table.
>>
>> I'm not sure the waste effort is acceptable; IMO, if the remote table
>> is a view, I think that the system should detect that in some way, and
>> then just do the normal ANALYZE processing.
>
>
> The stats fetch query is pretty light, but I can see fetching the relkind along with the relstats, and making decisions on whether to continue from there, only applying the relstats after attrstats have been successfully applied.
Good idea! I would vote for throwing an error if the relkind is view,
making the user set fetch_stats to false for the foreign table.
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-11-27 12:48 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2025-11-27 12:48 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
On Sun, Nov 23, 2025 at 4:28 PM Corey Huinker <corey.huinker@gmail.com> wrote:
> I've reorganized some things a bit, mostly to make resource cleanup simpler.
Thanks for updating the patch! I will look into it.
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-12-11 21:59 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 2 replies; 89+ messages in thread
From: Corey Huinker @ 2025-12-11 21:59 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
On Thu, Nov 27, 2025 at 7:48 AM Etsuro Fujita <etsuro.fujita@gmail.com>
wrote:
> On Sun, Nov 23, 2025 at 4:28 PM Corey Huinker <corey.huinker@gmail.com>
> wrote:
> > I've reorganized some things a bit, mostly to make resource cleanup
> simpler.
>
> Thanks for updating the patch! I will look into it.
>
> Best regards,
> Etsuro Fujita
>
Rebase, no changes.
Attachments:
v5-0001-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 41.2K) download
From f500a5af60e3ae842f1ec485a7341218acb648fe Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 7 Aug 2025 23:58:38 -0400
Subject: [PATCH v5] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via two new options, fetch_stats and remote_analyze,
both are available at the server level and table level. If fetch_stats
is true, then the ANALYZE command will first attempt to fetch statistics
from the remote table and import those statistics locally.
If remote_analyze is true, and if the first attempt to fetch remote
statistics found no attribute statistics, then an attempt will be made
to ANALYZE the remote table before a second and final attempt to fetch
remote statistics.
If no statistics are found, then ANALYZE will fall back to the normal
behavior of sampling and local analysis.
This operation will only work on remote relations that can have stored
statistics: tables, partitioned tables, and materialized views. If the
remote relation is a view then remote fetching/analyzing is just wasted
effort and the user is better of setting fetch_stats to false for that
table.
The default for fetch_stats is true at both server and table level. The
default for remote_analyze is false at both the server and table level.
In both cases, setting a value at the table level will override the
corresponding server-level setting.
---
src/include/foreign/fdwapi.h | 12 +
src/backend/commands/analyze.c | 45 +-
doc/src/sgml/postgres-fdw.sgml | 35 +-
.../postgres_fdw/expected/postgres_fdw.out | 64 +-
contrib/postgres_fdw/option.c | 10 +
contrib/postgres_fdw/postgres_fdw.c | 665 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 37 +-
7 files changed, 864 insertions(+), 4 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index fcd7e7027f3..eb6284979fb 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -19,6 +19,15 @@
/* avoid including explain_state.h here */
typedef struct ExplainState ExplainState;
+/* result of ImportStatistics */
+typedef enum
+{
+ FDW_IMPORT_STATS_OK = 0, /* was able to import statistics */
+ FDW_IMPORT_STATS_DISABLED, /* import disabled for this table */
+ FDW_IMPORT_STATS_NOTFOUND, /* no remote attribute stats found */
+ FDW_IMPORT_STATS_FAILED /* remote query failure of some kind */
+} FdwImportStatsResult;
+
/*
* Callback function signatures --- see fdwhandler.sgml for more info.
@@ -157,6 +166,8 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef FdwImportStatsResult (*ImportStatistics_function) (Relation relation);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +266,7 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 5e2a7a8234e..bbaebc9d710 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -196,13 +196,56 @@ analyze_rel(Oid relid, RangeVar *relation,
{
/*
* For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * supports statistics import and/or analysis.
*/
FdwRoutine *fdwroutine;
bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
+ if (fdwroutine->ImportStatistics != NULL)
+ {
+ FdwImportStatsResult res;
+
+ /*
+ * Fetching pre-existing remote stats is not guaranteed to be a quick
+ * operation.
+ *
+ * XXX: Should this be it's own fetch type? If not, then there might be
+ * confusion when a long stats-fetch fails, followed by a regular analyze,
+ * which would make it look like the table was analyzed twice.
+ */
+ pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
+ RelationGetRelid(onerel));
+
+ res = fdwroutine->ImportStatistics(onerel);
+
+ pgstat_progress_end_command();
+
+ /*
+ * If we were able to import statistics, then there is no need to collect
+ * samples for local analysis.
+ */
+ switch(res)
+ {
+ case FDW_IMPORT_STATS_OK:
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ case FDW_IMPORT_STATS_DISABLED:
+ break;
+ case FDW_IMPORT_STATS_NOTFOUND:
+ ereport(INFO,
+ errmsg("Found no remote statistics for \"%s\"",
+ RelationGetRelationName(onerel)));
+ break;
+ case FDW_IMPORT_STATS_FAILED:
+ default:
+ ereport(INFO,
+ errmsg("Fetching remote statistics from \"%s\" failed",
+ RelationGetRelationName(onerel)));
+ }
+ }
+
if (fdwroutine->AnalyzeForeignTable != NULL)
ok = fdwroutine->AnalyzeForeignTable(onerel,
&acquirefunc,
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 9b032fbf675..656897d89e0 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,39 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will first attempt to fetch and import the existing relation and
+ attribute statistics from the remote table, and only attempt regular
+ data sampling if no statistics were availble. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines wheter an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ is only meaningful if the foreign table has
+ <literal>fetch_stats</literal> enabled at either the server or table
+ level.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 48e3185b227..642ec27f2ac 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -628,6 +628,7 @@ INSERT INTO loct_empty
SELECT id, 'AAA' || to_char(id, 'FM000') FROM generate_series(1, 100) id;
DELETE FROM loct_empty;
ANALYZE ft_empty;
+INFO: Found no remote statistics for "ft_empty"
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_empty ORDER BY c1;
QUERY PLAN
-------------------------------------------------------------------------------
@@ -4551,7 +4552,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -4568,6 +4570,9 @@ CONTEXT: whole-row reference to foreign table "ftx"
SELECT sum(c2), array_agg(c8) FROM ft1 GROUP BY c8; -- ERROR
ERROR: invalid input syntax for type integer: "foo"
CONTEXT: processing expression at position 2 in select list
+ANALYZE ft1; -- WARNING
+WARNING: invalid input syntax for type integer: "foo"
+ALTER FOREIGN TABLE ft1 OPTIONS ( fetch_stats 'false' );
ANALYZE ft1; -- ERROR
ERROR: invalid input syntax for type integer: "foo"
CONTEXT: column "c8" of foreign table "ft1"
@@ -7102,6 +7107,7 @@ INSERT INTO loct2 VALUES (1002, 'bar');
CREATE FOREIGN TABLE remt2 (c1 int, c2 text) SERVER loopback OPTIONS (table_name 'loct2');
ANALYZE loct1;
ANALYZE remt2;
+INFO: Found no remote statistics for "remt2"
SET enable_mergejoin TO false;
SET enable_hashjoin TO false;
SET enable_material TO false;
@@ -8784,6 +8790,7 @@ alter foreign table foo2 options (use_remote_estimate 'true');
create index i_loct1_f1 on loct1(f1);
create index i_foo_f1 on foo(f1);
analyze foo;
+INFO: Found no remote statistics for "foo2"
analyze loct1;
-- inner join; expressions in the clauses appear in the equivalence class list
explain (verbose, costs off)
@@ -9013,7 +9020,9 @@ insert into remt1 values (2, 'bar');
insert into remt2 values (1, 'foo');
insert into remt2 values (2, 'bar');
analyze remt1;
+INFO: Found no remote statistics for "remt1"
analyze remt2;
+INFO: Found no remote statistics for "remt2"
explain (verbose, costs off)
update parent set b = parent.b || remt2.b from remt2 where parent.a = remt2.a returning *;
QUERY PLAN
@@ -10313,6 +10322,8 @@ CREATE FOREIGN TABLE ftprt1_p1 PARTITION OF fprt1 FOR VALUES FROM (0) TO (250)
CREATE FOREIGN TABLE ftprt1_p2 PARTITION OF fprt1 FOR VALUES FROM (250) TO (500)
SERVER loopback OPTIONS (TABLE_NAME 'fprt1_p2');
ANALYZE fprt1;
+INFO: Found no remote statistics for "ftprt1_p1"
+INFO: Found no remote statistics for "ftprt1_p2"
ANALYZE fprt1_p1;
ANALYZE fprt1_p2;
CREATE TABLE fprt2 (a int, b int, c varchar) PARTITION BY RANGE(b);
@@ -10328,6 +10339,8 @@ ALTER TABLE fprt2 ATTACH PARTITION ftprt2_p1 FOR VALUES FROM (0) TO (250);
CREATE FOREIGN TABLE ftprt2_p2 PARTITION OF fprt2 FOR VALUES FROM (250) TO (500)
SERVER loopback OPTIONS (table_name 'fprt2_p2', use_remote_estimate 'true');
ANALYZE fprt2;
+INFO: Found no remote statistics for "ftprt2_p1"
+INFO: Found no remote statistics for "ftprt2_p2"
ANALYZE fprt2_p1;
ANALYZE fprt2_p2;
-- inner join three tables
@@ -10515,9 +10528,15 @@ CREATE FOREIGN TABLE fpagg_tab_p1 PARTITION OF pagg_tab FOR VALUES FROM (0) TO (
CREATE FOREIGN TABLE fpagg_tab_p2 PARTITION OF pagg_tab FOR VALUES FROM (10) TO (20) SERVER loopback OPTIONS (table_name 'pagg_tab_p2');
CREATE FOREIGN TABLE fpagg_tab_p3 PARTITION OF pagg_tab FOR VALUES FROM (20) TO (30) SERVER loopback OPTIONS (table_name 'pagg_tab_p3');
ANALYZE pagg_tab;
+INFO: Found no remote statistics for "fpagg_tab_p1"
+INFO: Found no remote statistics for "fpagg_tab_p2"
+INFO: Found no remote statistics for "fpagg_tab_p3"
ANALYZE fpagg_tab_p1;
+INFO: Found no remote statistics for "fpagg_tab_p1"
ANALYZE fpagg_tab_p2;
+INFO: Found no remote statistics for "fpagg_tab_p2"
ANALYZE fpagg_tab_p3;
+INFO: Found no remote statistics for "fpagg_tab_p3"
-- When GROUP BY clause matches with PARTITION KEY.
-- Plan with partitionwise aggregates is disabled
SET enable_partitionwise_aggregate TO false;
@@ -11463,6 +11482,8 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
EXPLAIN (VERBOSE, COSTS OFF)
@@ -11569,6 +11590,9 @@ CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
+INFO: Found no remote statistics for "async_p3"
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
QUERY PLAN
@@ -11610,6 +11634,8 @@ DROP TABLE base_tbl3;
CREATE TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000);
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
ANALYZE async_pt;
+INFO: Found no remote statistics for "async_p1"
+INFO: Found no remote statistics for "async_p2"
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
QUERY PLAN
@@ -12665,6 +12691,42 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table', remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 04788b7e8b3..7f069373e82 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,8 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +280,14 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_size is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 5e178c21b39..334e4bf0f4e 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -22,6 +22,8 @@
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -317,6 +319,13 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
/*
* SQL functions
*/
@@ -402,6 +411,7 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static FdwImportStatsResult postgresImportStatistics(Relation relation);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +556,115 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+
+/* relallfrozen introduced in v18 */
+static const char *relstats_query_18 =
+ "SELECT c.relkind, c.relpages, c.reltuples, c.relallvisible, c.relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* trust reltuples = 0 as of v14 */
+static const char *relstats_query_14 =
+ "SELECT c.relkind, c.relpages, c.reltuples, c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case.)
+ * This ambiguity allegedly can cause the planner to choose inefficient
+ * plans after restoring to v18 or newer. To deal with this, let's just
+ * set reltuples to -1 in that case.
+ */
+static const char *relstats_query_default =
+ "SELECT c.relkind, c.relpages, "
+ "CASE c.reltuples WHEN 0 THEN -1 ELSE c.reltuples END AS reltuples, "
+ "c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns {
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_RELALLVISIBLE,
+ RELSTATS_RELALLFROZEN,
+ RELSTATS_NUM_FIELDS
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+static const char *attstats_query_default =
+ "SELECT s.attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns {
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS
+};
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +714,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5055,551 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Process optional argument.
+ *
+ * Cannot be the first argument in the SQL function call.
+ *
+ * It is safe to presume that argname and argtype are quote-safe.
+ *
+ * Argument values can potentially be quite large, so free the quoted string
+ * after use.
+ */
+static void
+append_optional(StringInfo str, PGresult *res, int row, int field,
+ const char *argname, const char *argtype)
+{
+ if (!PQgetisnull(res, row, field))
+ {
+ /* Argument values can be quite large, so free after use */
+ char *argval_l = quote_literal_cstr(PQgetvalue(res, row, field));
+
+ appendStringInfo(str, ",\n\t'%s', %s::%s", argname, argval_l, argtype);
+
+ pfree(argval_l);
+ }
+}
+
+
+/*
+ * Generate a pg_restore_relation_stats command.
+ */
+static char *
+restore_relation_stats_sql(PGresult *res, const char *schemaname,
+ const char *relname, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s",
+ server_version_num, schemaname_l, relname_l);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, 0, RELSTATS_RELPAGES, "relpages", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELTUPLES, "reltuples", "real");
+ append_optional(&sql, res, 0, RELSTATS_RELALLVISIBLE, "relallvisible", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELALLFROZEN, "relallfrozen", "integer");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Generate a pg_restore_attribute_stats command.
+ */
+static char *
+restore_attribute_stats_sql(PGresult *res, int row,
+ const char *schemaname, const char *relname,
+ const AttrNumber attnum, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s,\n"
+ "\t'attnum', %d::smallint,\n"
+ "\t'inherited', false::boolean",
+ server_version_num, schemaname_l, relname_l, attnum);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, row, ATTSTATS_NULL_FRAC, "null_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_AVG_WIDTH, "avg_width", "integer");
+ append_optional(&sql, res, row, ATTSTATS_N_DISTINCT, "n_distinct", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_VALS, "most_common_vals", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_FREQS, "most_common_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_HISTOGRAM_BOUNDS, "histogram_bounds", "text");
+ append_optional(&sql, res, row, ATTSTATS_CORRELATION, "correlation", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEMS, "most_common_elems", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEM_FREQS, "most_common_elem_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_ELEM_COUNT_HISTOGRAM, "elem_count_histogram", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_LENGTH_HISTOGRAM, "range_length_histogram", "text");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_EMPTY_FRAC, "range_empty_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_BOUNDS_HISTOGRAM, "range_bounds_histogram", "text");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+static FdwImportStatsResult
+import_fetched_statistics(Relation relation, int server_version_num,
+ const char *schemaname, const char *relname,
+ RemoteStatsResults *remstats)
+{
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int spirc;
+ char *relimport_sql;
+
+ /*
+ * Walk all local table attributes looking for name matches in the result
+ * set and perform a pg_restore_attribute_stats() on each match.
+ *
+ * XXX: the result set is sorted by attname, so perhaps we could do a binary
+ * search of the result set. Alternately we could collect the local attributes
+ * in a list and sort that by remote name, which would allow us to iterate via
+ * a merge.
+ *
+ * XXX: what should be done if match_found = false?
+ */
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+ bool match_found = false;
+
+ /* Ignore dropped columns. */
+ if (TupleDescAttr(tupdesc, i)->attisdropped)
+ continue;
+
+ /* Ignore generated columns, but maybe this should fail the import? */
+ if (TupleDescAttr(tupdesc, i)->attgenerated)
+ continue;
+
+ attnum = TupleDescAttr(tupdesc, i)->attnum;
+
+ /* default remote_colname is attname */
+ remote_colname = NameStr(TupleDescAttr(tupdesc, i)->attname);
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), i + 1);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ for (int j = 0; j < PQntuples(remstats->att); j++)
+ {
+ char *attimport_sql;
+ PGresult *res = remstats->att;
+
+ /* Skip results where we don't have no attribute name to compare */
+ if (PQgetisnull(res, j, ATTSTATS_ATTNAME))
+ continue;
+
+ /* Keep skipping name non-matches */
+ if (strcmp(PQgetvalue(res, j, ATTSTATS_ATTNAME), remote_colname) != 0)
+ continue;
+
+ match_found = true;
+ attimport_sql = restore_attribute_stats_sql(res, j, schemaname,
+ relname, attnum, server_version_num);
+
+ spirc = SPI_execute(attimport_sql, false, 1);
+ pfree(attimport_sql);
+
+ if (spirc != SPI_OK_SELECT)
+ {
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics import failed %s", attimport_sql)));
+ return FDW_IMPORT_STATS_FAILED;
+ }
+ }
+
+ /* TODO: should this be an error? What action could we take to remediate? */
+ if (!match_found)
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics found for %s.%s but no columns matched",
+ quote_identifier(schemaname),
+ quote_identifier(relname))));
+ }
+
+ relimport_sql = restore_relation_stats_sql(remstats->rel, schemaname, relname,
+ server_version_num);
+
+ spirc = SPI_execute(relimport_sql, false, 1);
+
+ if (spirc != SPI_OK_SELECT)
+ {
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ ereport(INFO,
+ (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Relation statistics import failed %s", relimport_sql)));
+ return FDW_IMPORT_STATS_FAILED;
+ }
+ pfree(relimport_sql);
+
+ return FDW_IMPORT_STATS_OK;
+}
+
+/*
+ * Analyze a remote table.
+ */
+static bool
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+ bool success = false;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s.%s",
+ quote_identifier(remote_schemaname),
+ quote_identifier(remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res != NULL)
+ {
+ if (PQresultStatus(res) == PGRES_COMMAND_OK)
+ success = true;
+ else
+ pgfdw_report(NOTICE, res, conn, buf.data);
+
+ PQclear(res);
+ }
+ else
+ ereport(INFO,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Unable to ANALYZE remote table %s.%s.",
+ quote_identifier(remote_schemaname),
+ quote_identifier(remote_relname)));
+
+ pfree(buf.data);
+ return success;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static FdwImportStatsResult
+fetch_remote_statistics(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ bool remote_analyze, RemoteStatsResults *remstats)
+{
+ const char *sql_params[2] = { remote_schemaname, remote_relname };
+ int sql_param_formats[2] = {0, 0};
+
+ const char *relation_sql;
+ const char *attribute_sql;
+
+ char relkind;
+
+ if (server_version_num >= 180000)
+ relation_sql = relstats_query_18;
+ else if (server_version_num >= 140000)
+ relation_sql = relstats_query_14;
+ else
+ relation_sql = relstats_query_default;
+
+ if (server_version_num >= 170000)
+ attribute_sql = attstats_query_17;
+ else if (server_version_num >= 90200)
+ attribute_sql = attstats_query_9_2;
+ else if (server_version_num >= 90000)
+ attribute_sql = attstats_query_9_0;
+ else
+ attribute_sql = attstats_query_default;
+
+ /*
+ * Fetch basic relation stats.
+ */
+ if (!PQsendQueryParams(conn, relation_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, relation_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ remstats->rel = pgfdw_get_result(conn);
+
+ if (remstats->rel == NULL
+ || PQresultStatus(remstats->rel) != PGRES_TUPLES_OK
+ || PQntuples(remstats->rel) != 1
+ || PQnfields(remstats->rel) != RELSTATS_NUM_FIELDS
+ || PQgetisnull(remstats->rel, 0, RELSTATS_RELKIND))
+ {
+ /* unable to get relation stats, fall back on table sampling */
+ pgfdw_report(INFO, remstats->rel, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously can't
+ * support a foreign table.
+ */
+ relkind = *PQgetvalue(remstats->rel, 0, RELSTATS_RELKIND);
+
+ switch(relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ ereport(INFO,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Remote table %s.%s does not support statistics.",
+ quote_identifier(remote_schemaname),
+ quote_identifier(remote_relname)),
+ errdetail("Remote relation if of relkind \"%c\"", relkind));
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /* See if it actually has any attribute stats. */
+ if (!PQsendQueryParams(conn, attribute_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ remstats->att = pgfdw_get_result(conn);
+ if (remstats->att == NULL
+ || PQresultStatus(remstats->att) != PGRES_TUPLES_OK
+ || PQnfields(remstats->att) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, remstats->att, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * If we got attribute statistics results, then we are done with fetching.
+ */
+ if (PQntuples(remstats->att) > 0)
+ return FDW_IMPORT_STATS_OK;
+
+ /*
+ * If remote_analyze is not enabled, then a lack of fetched stats is viewed
+ * as a temporary problem that may be solved later when the remote server
+ * analyzes the table.
+ */
+ if (!remote_analyze)
+ return FDW_IMPORT_STATS_NOTFOUND;
+
+ /*
+ * Clear off any existing fetched statistics.
+ */
+ PQclear(remstats->att);
+ PQclear(remstats->rel);
+ remstats->att = NULL;
+ remstats->rel = NULL;
+
+ /*
+ * Analyze the remote table.
+ *
+ * If it's still empty afterward, then that's an error indicating that
+ * remote_analyze should probably be disabled.
+ */
+ if (!analyze_remote_table(conn, remote_schemaname, remote_relname))
+ return FDW_IMPORT_STATS_FAILED;
+
+ /*
+ * Re-fetch attribute stats query. If there still are no attribute stats then
+ * it's an error.
+ */
+ if (!PQsendQueryParams(conn, attribute_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ remstats->att = pgfdw_get_result(conn);
+
+ /* Getting nothing on the second try is a failure */
+ if (remstats->att == NULL
+ || PQresultStatus(remstats->att) != PGRES_TUPLES_OK
+ || PQntuples(remstats->att) == 0
+ || PQnfields(remstats->att) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, remstats->att, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Re-fetch basic relation stats, as they have been updated.
+ */
+ if (!PQsendQueryParams(conn, relation_sql, 2, NULL, sql_params, NULL,
+ sql_param_formats, 0))
+ {
+ pgfdw_report(INFO, NULL, conn, relation_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ /*
+ * Get the result, and check for success.
+ * If the query failed or the result set is of the wrong shape, then
+ * fail the import and fall back to local analysis.
+ */
+ remstats->rel = pgfdw_get_result(conn);
+
+ if (remstats->rel == NULL
+ || PQresultStatus(remstats->rel) != PGRES_TUPLES_OK
+ || PQntuples(remstats->rel) != 1
+ || PQnfields(remstats->rel) != RELSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(INFO, remstats->rel, conn, attribute_sql);
+ return FDW_IMPORT_STATS_FAILED;
+ }
+
+ return FDW_IMPORT_STATS_OK;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static FdwImportStatsResult
+postgresImportStatistics(Relation relation)
+{
+
+ ForeignTable *table;
+ ForeignServer *server;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ bool fetch_stats = true;
+ bool remote_analyze = false;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+
+ FdwImportStatsResult fisr = FDW_IMPORT_STATS_OK;
+
+ RemoteStatsResults remstats = { .rel = NULL, .att = NULL };
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ fetch_stats = defGetBoolean(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ fetch_stats = defGetBoolean(def);
+ else if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ if (!fetch_stats)
+ return FDW_IMPORT_STATS_DISABLED;
+
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+
+ relname = RelationGetRelationName(relation);
+
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ fisr = fetch_remote_statistics(conn, server_version_num,
+ remote_schemaname, remote_relname,
+ remote_analyze, &remstats);
+
+ ReleaseConnection(conn);
+
+ /* If we have successfully fetched stats, then try to import them */
+ if (fisr == FDW_IMPORT_STATS_OK)
+ {
+ SPI_connect();
+ fisr = import_fetched_statistics(relation, server_version_num,
+ schemaname, relname, &remstats);
+ SPI_finish();
+ }
+
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+
+ return fisr;
+}
+
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 9a8f9e28135..09a98c860f1 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -1278,7 +1278,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -1287,6 +1288,8 @@ SELECT ftx.x1, ft2.c2, ftx.x8 FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2
SELECT ftx.x1, ft2.c2, ftx FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2
WHERE ftx.x1 = ft2.c1 AND ftx.x1 = 1; -- ERROR
SELECT sum(c2), array_agg(c8) FROM ft1 GROUP BY c8; -- ERROR
+ANALYZE ft1; -- WARNING
+ALTER FOREIGN TABLE ft1 OPTIONS ( fetch_stats 'false' );
ANALYZE ft1; -- ERROR
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE user_enum;
@@ -4379,6 +4382,38 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table', remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
base-commit: b65f1ad9b12767dbd45d9588ce8ed2e593dbddbf
--
2.52.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-12-12 06:11 Chao Li <li.evan.chao@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Chao Li @ 2025-12-12 06:11 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
> On Dec 12, 2025, at 05:59, Corey Huinker <corey.huinker@gmail.com> wrote:
>
> On Thu, Nov 27, 2025 at 7:48 AM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
> On Sun, Nov 23, 2025 at 4:28 PM Corey Huinker <corey.huinker@gmail.com> wrote:
> > I've reorganized some things a bit, mostly to make resource cleanup simpler.
>
> Thanks for updating the patch! I will look into it.
>
> Best regards,
> Etsuro Fujita
>
> Rebase, no changes.
> <v5-0001-Add-remote-statistics-fetching-to-postgres_fdw.patch>
A kind reminder, I don’t see my comments are addressed:
https://postgr.es/m/F9C73EF2-F977-46E4-9F61-B6CF72BF1A69@gmail.com
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-12-12 13:45 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 0 replies; 89+ messages in thread
From: Etsuro Fujita @ 2025-12-12 13:45 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
On Thu, Nov 27, 2025 at 9:46 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
> On Sat, Nov 22, 2025 at 6:31 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> >> Other initial comments:
> >>
> >> The commit message says:
> >>
> >> This is managed via two new options, fetch_stats and remote_analyze,
> >> both are available at the server level and table level. If fetch_stats
> >> is true, then the ANALYZE command will first attempt to fetch statistics
> >> from the remote table and import those statistics locally.
> >>
> >> If remote_analyze is true, and if the first attempt to fetch remote
> >> statistics found no attribute statistics, then an attempt will be made
> >> to ANALYZE the remote table before a second and final attempt to fetch
> >> remote statistics.
> >>
> >> If no statistics are found, then ANALYZE will fall back to the normal
> >> behavior of sampling and local analysis.
> >>
> >> I think the first step assumes that the remote stats are up-to-date;
> >> if they aren't, it would cause a regression. (If the remote relation
> >> is a plain table, they are likely to be up-to-date, but for example,
> >> if it is a foreign table, it's possible that they are stale.) So how
> >> about making it the user's responsibility to make them up-to-date? If
> >> doing so, we wouldn't need to do the second and third steps anymore,
> >> making the patch simple.
>
> > Obviously there is no way to know the quality/freshness of remote stats if they are found.
> >
> > The analyze option was borne of feedback from other postgres hackers while brainstorming on what this option might look like. I don't think we *need* this extra option for the feature to be a success, but it's relative simplicity did make me want to put it out there to see who else liked it.
>
> Actually, I have some concerns about the ANALYZE and fall-back
> options. As for the former, if the remote user didn't have the
> MAINTAIN privilege on the remote table, remote ANALYZE would be just a
> waste effort. As for the latter, imagine the situation where a user
> ANALYZEs a foreign table whose remote table is significantly large.
> When the previous attempts fail, the user might want to re-try to
> import remote stats after ANALYZEing the remote table in the remote
> side in some way, rather than postgres_fdw automatically falling back
> to the normal lengthy processing. I think just throwing an error if
> the first attempt fails would make the system not only simple but
> reliable while providing some flexibility to users.
I think I was narrow-minded here; as for the ANALYZE option, if the
remote user has the privilege, it would work well, so +1 for it, but I
don't think it's a must-have option, so I'd vote for making it a
separate patch. As for the fall-back behavior, however, sorry, I
still think it reduces flexibility.
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-12-12 14:04 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2025-12-12 14:04 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
On Fri, Dec 12, 2025 at 6:59 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> Rebase, no changes.
Thanks for rebasing! I reviewed the changes made to the core:
@@ -196,13 +196,56 @@ analyze_rel(Oid relid, RangeVar *relation,
{
/*
* For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * supports statistics import and/or analysis.
*/
FdwRoutine *fdwroutine;
bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
+ if (fdwroutine->ImportStatistics != NULL)
+ {
+ FdwImportStatsResult res;
+
+ /*
+ * Fetching pre-existing remote stats is not guaranteed to
be a quick
+ * operation.
+ *
+ * XXX: Should this be it's own fetch type? If not, then
there might be
+ * confusion when a long stats-fetch fails, followed by a
regular analyze,
+ * which would make it look like the table was analyzed twice.
+ */
+ pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
+ RelationGetRelid(onerel));
+
+ res = fdwroutine->ImportStatistics(onerel);
+
+ pgstat_progress_end_command();
+
+ /*
+ * If we were able to import statistics, then there is no
need to collect
+ * samples for local analysis.
+ */
+ switch(res)
+ {
+ case FDW_IMPORT_STATS_OK:
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ case FDW_IMPORT_STATS_DISABLED:
+ break;
+ case FDW_IMPORT_STATS_NOTFOUND:
+ ereport(INFO,
+ errmsg("Found no remote statistics for \"%s\"",
+ RelationGetRelationName(onerel)));
+ break;
+ case FDW_IMPORT_STATS_FAILED:
+ default:
+ ereport(INFO,
+ errmsg("Fetching remote statistics from
\"%s\" failed",
+ RelationGetRelationName(onerel)));
+ }
+ }
Returning in the FDW_IMPORT_STATS_OK case isn't 100% correct; if the
foreign table is an inheritance parent, we would fail to do inherited
stats.
IIUC, the FDW needs to do two things within the ImportStatistics
callback function: check the importability, and if ok, do the work. I
think that would make the API complicated. To avoid that, how about
1) splitting the callback function into the two functions shown below
and then 2) rewriting the above to something like the attached? The
attached addresses the returning issue mentioned above as well.
bool
StatisticsAreImportable(Relation relation)
Checks the importability, and if ok, returns true, in which case the
following callback function is called. In the postgres_fdw case, we
could implement this to check if the fetch_stats flag for the foreign
table is set to true, and if so, return true.
void
ImportStatistics(Relation relation, List *va_cols, int elevel)
Imports the stats for the foreign table from the foreign server. As
mentioned in previous emails, I don't think it's a good idea to fall
back to the normal processing when the attempt to import the stats
fails, in which case I think we should just throw an error (or
warning) so that the user can re-try to import the stats after fixing
the foreign side in some way. So I re-defined this as a void
function. Note that this re-definition removes the concern mentioned
in the comment starting with "XXX:". In the postgres_fdw case, as
mentioned in a previous email, I think it would be good to implement
this so that it checks whether the remote table is a view or not when
importing the relation stats from the remote server, and if so, just
throws an error (or warning), making the user reset the fetch_stats
flag.
I added two arguments to the callback function: va_cols, for
supporting the column list in the ANALYZE command, and elevel, for
proper logging. I'm not sure if VaccumParams should be added as well.
That's it for now. I'll continue to review the patch.
Best regards,
Etsuro Fujita
Attachments:
FDW-API-for-importing-stats.patch (application/octet-stream, 3.7K) download
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 5e2a7a8234e..ec0ccf15362 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -113,6 +113,8 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool import_stats = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -195,26 +197,32 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
-
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ import_stats = true;
+ else
{
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
+ RelationGetRelationName(onerel))));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
}
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
@@ -248,9 +256,18 @@ analyze_rel(Oid relid, RangeVar *relation,
/*
* Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * tables, which don't contain any rows. For foreign tables, if they
+ * support importing statistics, do that instead of the non-recursive
+ * ANALYZE.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+ else if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index fcd7e7027f3..c4453f306fa 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef void (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +261,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-12-12 19:03 Corey Huinker <corey.huinker@gmail.com>
parent: Chao Li <li.evan.chao@gmail.com>
0 siblings, 0 replies; 89+ messages in thread
From: Corey Huinker @ 2025-12-12 19:03 UTC (permalink / raw)
To: Chao Li <li.evan.chao@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
>
>
> A kind reminder, I don’t see my comments are addressed:
>
>
My apologies. Will get into the next rev.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-12-12 19:45 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2025-12-12 19:45 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
CCing Jonathan Katz and Nathan Bossart as they had been sounding boards for
me when I started designing this feature.
> Returning in the FDW_IMPORT_STATS_OK case isn't 100% correct; if the
> foreign table is an inheritance parent, we would fail to do inherited
> stats.
>
Perhaps I'm not understanding completely, but I believe what we're doing
now should be ok.
The local table of type 'f' can be a member of a partition, but can't be a
partition itself, so whatever stats we get for it, we're storing them as
inh = false.
On the remote side, the table could be an inheritance parent, in which case
we ONLY want the inh=true stats, but we will still store them locally as
inh = false.
The DISTINCT ON(a.attname)....ORDER BY a.attname, s.inherited DESC part of
the query ensures that we get inh=true stats if they're there in preference
to the inh=false steps.
I will grant you that in an old-style inheritance (i.e. not formal
partitions) situation we'd probably want some weighted mix of the inherited
and non-inherited stats, but 1) very few people use old-style inheritance
anymore, 2) few of those export tables via a FDW, and 3) there's no way to
do that weighting so we should fall back to sampling anyway.
None of this takes away from your suggestions down below.
> IIUC, the FDW needs to do two things within the ImportStatistics
> callback function: check the importability, and if ok, do the work. I
> think that would make the API complicated. To avoid that, how about
> 1) splitting the callback function into the two functions shown below
> and then 2) rewriting the above to something like the attached? The
> attached addresses the returning issue mentioned above as well.
>
> bool
> StatisticsAreImportable(Relation relation)
>
> Checks the importability, and if ok, returns true, in which case the
> following callback function is called. In the postgres_fdw case, we
> could implement this to check if the fetch_stats flag for the foreign
> table is set to true, and if so, return true.
>
+1
> void
> ImportStatistics(Relation relation, List *va_cols, int elevel)
>
> Imports the stats for the foreign table from the foreign server. As
> mentioned in previous emails, I don't think it's a good idea to fall
> back to the normal processing when the attempt to import the stats
> fails, in which case I think we should just throw an error (or
> warning) so that the user can re-try to import the stats after fixing
> the foreign side in some way. So I re-defined this as a void
> function. Note that this re-definition removes the concern mentioned
> in the comment starting with "XXX:". In the postgres_fdw case, as
> mentioned in a previous email, I think it would be good to implement
> this so that it checks whether the remote table is a view or not when
> importing the relation stats from the remote server, and if so, just
> throws an error (or warning), making the user reset the fetch_stats
> flag.
>
I think I'm ok with this design as the decision, as it still leaves open
the fdw-specific options of how to handle initially finding no remote stats.
I can still see a situation where a local table expects the remote table to
eventually have proper statistics on it, but until that happens it will
fall back to table samples. This design decision means that either the user
lives without any statistics for a while, or alters the foreign table
options and hopefully remembers to set them back. While I understand the
desire to first implement something very simple, I think that adding the
durability that fallback allows for will be harder to implement if we don't
build it in from the start. I'm interested to hear with Nathan and/or
Jonathan have to say about that.
> I added two arguments to the callback function: va_cols, for
> supporting the column list in the ANALYZE command, and elevel, for
> proper logging. I'm not sure if VaccumParams should be added as well.
>
Good catch, I forgot about that one.
Going to think some more on this before I work incorporating your
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-12-13 19:12 Corey Huinker <corey.huinker@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2025-12-13 19:12 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Fri, Dec 12, 2025 at 2:45 PM Corey Huinker <corey.huinker@gmail.com>
wrote:
> CCing Jonathan Katz and Nathan Bossart as they had been sounding boards
> for me when I started designing this feature.
>
>
>> Returning in the FDW_IMPORT_STATS_OK case isn't 100% correct; if the
>> foreign table is an inheritance parent, we would fail to do inherited
>> stats.
>>
>
> Perhaps I'm not understanding completely, but I believe what we're doing
> now should be ok.
>
> The local table of type 'f' can be a member of a partition, but can't be a
> partition itself, so whatever stats we get for it, we're storing them as
> inh = false.
>
> On the remote side, the table could be an inheritance parent, in which
> case we ONLY want the inh=true stats, but we will still store them locally
> as inh = false.
>
> The DISTINCT ON(a.attname)....ORDER BY a.attname, s.inherited DESC part of
> the query ensures that we get inh=true stats if they're there in preference
> to the inh=false steps.
>
> I will grant you that in an old-style inheritance (i.e. not formal
> partitions) situation we'd probably want some weighted mix of the inherited
> and non-inherited stats, but 1) very few people use old-style inheritance
> anymore, 2) few of those export tables via a FDW, and 3) there's no way to
> do that weighting so we should fall back to sampling anyway.
>
> None of this takes away from your suggestions down below.
>
>
>> IIUC, the FDW needs to do two things within the ImportStatistics
>> callback function: check the importability, and if ok, do the work. I
>> think that would make the API complicated. To avoid that, how about
>> 1) splitting the callback function into the two functions shown below
>> and then 2) rewriting the above to something like the attached? The
>> attached addresses the returning issue mentioned above as well.
>>
>> bool
>> StatisticsAreImportable(Relation relation)
>>
>> Checks the importability, and if ok, returns true, in which case the
>> following callback function is called. In the postgres_fdw case, we
>> could implement this to check if the fetch_stats flag for the foreign
>> table is set to true, and if so, return true.
>>
>
> +1
>
>
>> void
>> ImportStatistics(Relation relation, List *va_cols, int elevel)
>>
>> Imports the stats for the foreign table from the foreign server. As
>> mentioned in previous emails, I don't think it's a good idea to fall
>> back to the normal processing when the attempt to import the stats
>> fails, in which case I think we should just throw an error (or
>> warning) so that the user can re-try to import the stats after fixing
>> the foreign side in some way. So I re-defined this as a void
>> function. Note that this re-definition removes the concern mentioned
>> in the comment starting with "XXX:". In the postgres_fdw case, as
>> mentioned in a previous email, I think it would be good to implement
>> this so that it checks whether the remote table is a view or not when
>> importing the relation stats from the remote server, and if so, just
>> throws an error (or warning), making the user reset the fetch_stats
>> flag.
>>
>
> I think I'm ok with this design as the decision, as it still leaves open
> the fdw-specific options of how to handle initially finding no remote stats.
>
> I can still see a situation where a local table expects the remote table
> to eventually have proper statistics on it, but until that happens it will
> fall back to table samples. This design decision means that either the user
> lives without any statistics for a while, or alters the foreign table
> options and hopefully remembers to set them back. While I understand the
> desire to first implement something very simple, I think that adding the
> durability that fallback allows for will be harder to implement if we don't
> build it in from the start. I'm interested to hear with Nathan and/or
> Jonathan have to say about that.
>
>
>> I added two arguments to the callback function: va_cols, for
>> supporting the column list in the ANALYZE command, and elevel, for
>> proper logging. I'm not sure if VaccumParams should be added as well.
>>
>
> Good catch, I forgot about that one.
>
> Going to think some more on this before I work incorporating your
>
Heh, the word "changes" got cut off.
Anyway, here's v6 incorporating both threads of feedback.
Attachments:
v6-0001-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 38.8K) download
From 571d6cb899fe0bb480c4848ea62707f357b94848 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 7 Aug 2025 23:58:38 -0400
Subject: [PATCH v6] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via two new options, fetch_stats and remote_analyze,
both are available at the server level and table level. If fetch_stats
is true, then the ANALYZE command will first attempt to fetch statistics
from the remote table and import those statistics locally.
If remote_analyze is true, and if the first attempt to fetch remote
statistics found no attribute statistics, then an attempt will be made
to ANALYZE the remote table before a second and final attempt to fetch
remote statistics.
If the attempts to fetch statistics result in no rows returned or none
of the rows returned matching the columns in the local table, then the
ANALYZE will raise an error.
This operation will only work on remote relations that can have stored
statistics: tables, partitioned tables, and materialized views. If the
remote relation is a view then remote fetching/analyzing is just wasted
effort and the user is better off setting fetch_stats to false for that
table.
The default for fetch_stats is true at both server and table level. The
default for remote_analyze is false at both the server and table level.
In both cases, setting a value at the table level will override the
corresponding server-level setting.
---
src/include/foreign/fdwapi.h | 9 +-
src/backend/commands/analyze.c | 44 +-
doc/src/sgml/postgres-fdw.sgml | 35 +-
.../postgres_fdw/expected/postgres_fdw.out | 52 +-
contrib/postgres_fdw/option.c | 10 +
contrib/postgres_fdw/postgres_fdw.c | 671 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 46 +-
7 files changed, 857 insertions(+), 10 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index fcd7e7027f3..255e18584e3 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -19,7 +19,6 @@
/* avoid including explain_state.h here */
typedef struct ExplainState ExplainState;
-
/*
* Callback function signatures --- see fdwhandler.sgml for more info.
*/
@@ -157,6 +156,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef void (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +260,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 5e2a7a8234e..a59e7805da9 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -113,6 +113,8 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool import_stats = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -194,15 +196,36 @@ analyze_rel(Oid relid, RangeVar *relation,
}
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
+ bool ok = false;
+
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ import_stats = true;
+ else
+ {
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
+ }
+
if (fdwroutine->AnalyzeForeignTable != NULL)
ok = fdwroutine->AnalyzeForeignTable(onerel,
&acquirefunc,
@@ -248,9 +271,18 @@ analyze_rel(Oid relid, RangeVar *relation,
/*
* Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * tables, which don't contain any rows. For foreign tables, if they
+ * support importing statistics, do that instead of the non-recursive
+ * ANALYZE.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+ else if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 9b032fbf675..5439ce9eb09 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,39 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will first attempt to fetch and import the existing relation and
+ attribute statistics from the remote table, and only attempt regular
+ data sampling if no statistics were available. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ is only meaningful if the foreign table has
+ <literal>fetch_stats</literal> enabled at either the server or table
+ level.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 48e3185b227..cac1a73adf0 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4551,7 +4552,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11462,6 +11464,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p2
+ANALYZE async_pt;
+ERROR: Failed to import statistics from remote table public.base_tbl2, no statistics found.
+-- Turn off fetch_stats at the table level.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11568,6 +11575,11 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+ERROR: Failed to import statistics from remote table public.base_tbl3, no statistics found.
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
@@ -12665,6 +12677,44 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 04788b7e8b3..5030279a8a7 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,8 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +280,14 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 5e178c21b39..ede811a212a 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -22,6 +22,8 @@
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -317,6 +319,13 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
/*
* SQL functions
*/
@@ -402,6 +411,10 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresStatisticsAreImportable(Relation relation);
+static void postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +559,115 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+
+/* relallfrozen introduced in v18 */
+static const char *relstats_query_18 =
+ "SELECT c.relkind, c.relpages, c.reltuples, c.relallvisible, c.relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* trust reltuples = 0 as of v14 */
+static const char *relstats_query_14 =
+ "SELECT c.relkind, c.relpages, c.reltuples, c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case.)
+ * This ambiguity allegedly can cause the planner to choose inefficient
+ * plans after restoring to v18 or newer. To deal with this, let's just
+ * set reltuples to -1 in that case.
+ */
+static const char *relstats_query_default =
+ "SELECT c.relkind, c.relpages, "
+ "CASE c.reltuples WHEN 0 THEN -1 ELSE c.reltuples END AS reltuples, "
+ "c.relallvisible, NULL AS relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns {
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_RELALLVISIBLE,
+ RELSTATS_RELALLFROZEN,
+ RELSTATS_NUM_FIELDS
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
+
+static const char *attstats_query_default =
+ "SELECT s.attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns {
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS
+};
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +717,8 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->StatisticsAreImportable = postgresStatisticsAreImportable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5059,553 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Process optional argument.
+ *
+ * Cannot be the first argument in the SQL function call.
+ *
+ * It is safe to presume that argname and argtype are quote-safe.
+ *
+ * Argument values can potentially be quite large, so free the quoted string
+ * after use.
+ */
+static void
+append_optional(StringInfo str, PGresult *res, int row, int field,
+ const char *argname, const char *argtype)
+{
+ if (!PQgetisnull(res, row, field))
+ {
+ /* Argument values can be quite large, so free after use */
+ char *argval_l = quote_literal_cstr(PQgetvalue(res, row, field));
+
+ appendStringInfo(str, ",\n\t'%s', %s::%s", argname, argval_l, argtype);
+
+ pfree(argval_l);
+ }
+}
+
+
+/*
+ * Generate a pg_restore_relation_stats command.
+ */
+static char *
+restore_relation_stats_sql(PGresult *res, const char *schemaname,
+ const char *relname, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s",
+ server_version_num, schemaname_l, relname_l);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, 0, RELSTATS_RELPAGES, "relpages", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELTUPLES, "reltuples", "real");
+ append_optional(&sql, res, 0, RELSTATS_RELALLVISIBLE, "relallvisible", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELALLFROZEN, "relallfrozen", "integer");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Generate a pg_restore_attribute_stats command.
+ */
+static char *
+restore_attribute_stats_sql(PGresult *res, int row,
+ const char *schemaname, const char *relname,
+ const AttrNumber attnum, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s,\n"
+ "\t'attnum', %d::smallint,\n"
+ "\t'inherited', false::boolean",
+ server_version_num, schemaname_l, relname_l, attnum);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, row, ATTSTATS_NULL_FRAC, "null_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_AVG_WIDTH, "avg_width", "integer");
+ append_optional(&sql, res, row, ATTSTATS_N_DISTINCT, "n_distinct", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_VALS, "most_common_vals", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_FREQS, "most_common_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_HISTOGRAM_BOUNDS, "histogram_bounds", "text");
+ append_optional(&sql, res, row, ATTSTATS_CORRELATION, "correlation", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEMS, "most_common_elems", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEM_FREQS, "most_common_elem_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_ELEM_COUNT_HISTOGRAM, "elem_count_histogram", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_LENGTH_HISTOGRAM, "range_length_histogram", "text");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_EMPTY_FRAC, "range_empty_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_BOUNDS_HISTOGRAM, "range_bounds_histogram", "text");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+static void
+import_fetched_statistics(Relation relation, int server_version_num,
+ const char *schemaname, const char *relname,
+ List *va_cols, RemoteStatsResults *remstats)
+{
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int spirc;
+ char *relimport_sql;
+
+ SPI_connect();
+
+ /*
+ * Walk all local table attributes looking for name matches in the result
+ * set and perform a pg_restore_attribute_stats() on each match.
+ *
+ * XXX: the result set is sorted by attname, so perhaps we could do a binary
+ * search of the result set. Alternately we could collect the local attributes
+ * in a list and sort that by remote name, which would allow us to iterate via
+ * a merge.
+ */
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *attname;
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+ bool match_found = false;
+
+ /* Ignore dropped columns. */
+ if (TupleDescAttr(tupdesc, i)->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (TupleDescAttr(tupdesc, i)->attgenerated)
+ continue;
+
+ attname = NameStr(TupleDescAttr(tupdesc, i)->attname);
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ attnum = TupleDescAttr(tupdesc, i)->attnum;
+
+ /* If column_name is not specified, go with attname. */
+ remote_colname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), i + 1);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ for (int j = 0; j < PQntuples(remstats->att); j++)
+ {
+ char *attimport_sql;
+ PGresult *res = remstats->att;
+
+ /* Skip results where we don't have no attribute name to compare */
+ if (PQgetisnull(res, j, ATTSTATS_ATTNAME))
+ continue;
+
+ /* Keep skipping name non-matches */
+ if (strcmp(PQgetvalue(res, j, ATTSTATS_ATTNAME), remote_colname) != 0)
+ continue;
+
+ match_found = true;
+ attimport_sql = restore_attribute_stats_sql(res, j, schemaname,
+ relname, attnum, server_version_num);
+
+ spirc = SPI_execute(attimport_sql, false, 1);
+ pfree(attimport_sql);
+
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ if (spirc != SPI_OK_SELECT)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics import failed %s", attimport_sql));
+ }
+
+ if (!match_found)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics were found for %s but no attriubte names matched.",
+ quote_qualified_identifier(schemaname, relname)));
+ }
+
+ relimport_sql = restore_relation_stats_sql(remstats->rel, schemaname, relname,
+ server_version_num);
+
+ spirc = SPI_execute(relimport_sql, false, 1);
+
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ if (spirc != SPI_OK_SELECT)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Relation statistics import failed: %s.", relimport_sql));
+
+ pfree(relimport_sql);
+ SPI_finish();
+}
+
+/*
+ * Analyze a remote table.
+ */
+static void
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s",
+ quote_qualified_identifier(remote_schemaname, remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL ||
+ PQresultStatus(res) != PGRES_COMMAND_OK)
+ pgfdw_report_error(res, conn, buf.data);
+
+ PQclear(res);
+ pfree(buf.data);
+}
+
+/*
+ * Attempt to fetch remote stats.
+ *
+ * Attribute and relation queries have the same parameters.
+ */
+static PGresult *
+fetch_remote_stats(PGconn *conn, const char *sql, const char **params,
+ const int *formats)
+{
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL,
+ formats, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ return pgfdw_get_result(conn);
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ * Verify that the result is of the proper shape.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn, const char *sql, const char **params,
+ const int *formats)
+{
+ PGresult *res = fetch_remote_stats(conn, sql, params, formats);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS
+ || PQgetisnull(res, 0, RELSTATS_RELKIND))
+ pgfdw_report_error(res, conn, sql);
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ * Verify that the result is of the proper shape.
+ * Note that we do not verify the row count.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn, const char *sql, const char **params,
+ const int *formats)
+{
+ PGresult *res = fetch_remote_stats(conn, sql, params, formats);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ pgfdw_report_error(res, conn, sql);
+
+ return res;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static void
+fetch_remote_statistics(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ bool remote_analyze, RemoteStatsResults *remstats)
+{
+ const char *sql_params[2] = { remote_schemaname, remote_relname };
+ int sql_param_formats[2] = {0, 0};
+
+ const char *relation_sql;
+ const char *attribute_sql;
+
+ char relkind;
+
+ if (server_version_num >= 180000)
+ relation_sql = relstats_query_18;
+ else if (server_version_num >= 140000)
+ relation_sql = relstats_query_14;
+ else
+ relation_sql = relstats_query_default;
+
+ if (server_version_num >= 170000)
+ attribute_sql = attstats_query_17;
+ else if (server_version_num >= 90200)
+ attribute_sql = attstats_query_9_2;
+ else if (server_version_num >= 90000)
+ attribute_sql = attstats_query_9_0;
+ else
+ attribute_sql = attstats_query_default;
+
+ remstats->rel = fetch_relstats(conn, relation_sql,
+ sql_params, sql_param_formats);
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously can't
+ * support a foreign table.
+ */
+ relkind = *PQgetvalue(remstats->rel, 0, RELSTATS_RELKIND);
+
+ switch(relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Remote table %s does not support statistics.",
+ quote_qualified_identifier(remote_schemaname, remote_relname)));
+ return;
+ }
+
+ /* See if it actually has any attribute stats. */
+ remstats->att = fetch_attstats(conn, attribute_sql,
+ sql_params, sql_param_formats);
+
+ /* If we got attribute statistics results, then we are done with fetching. */
+ if (PQntuples(remstats->att) > 0)
+ return;
+
+ /*
+ * Clear off any existing fetched statistics, if any. If the analyze works
+ * then they we want to fetch the new ones.
+ */
+ PQclear(remstats->att);
+ PQclear(remstats->rel);
+ remstats->att = NULL;
+ remstats->rel = NULL;
+
+ /*
+ * If remote_analyze is enabled, then we will try to analyze the table and
+ * then try again.
+ */
+ if (remote_analyze)
+ analyze_remote_table(conn, remote_schemaname, remote_relname);
+ else
+ ereport(ERROR,
+ errcode(ERRCODE_NO_DATA_FOUND),
+ errmsg("Failed to import statistics from remote table %s, "
+ "no statistics found.",
+ quote_qualified_identifier(remote_schemaname, remote_relname)));
+
+ /*
+ * Remote ANALYZE complete, so re-fetch attribute stats query.
+ */
+ remstats->att = fetch_attstats(conn, attribute_sql,
+ sql_params, sql_param_formats);
+
+ /* Getting nothing on the second try is a failure */
+ if (PQntuples(remstats->att) == 0)
+ pgfdw_report_error(remstats->att, conn, attribute_sql);
+
+ /* Re-fetch basic relation stats, as they have been updated. */
+ remstats->rel = fetch_relstats(conn, relation_sql,
+ sql_params, sql_param_formats);
+}
+
+static bool
+postgresStatisticsAreImportable(Relation relation)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ ListCell *lc;
+ bool fetch_stats = true;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ return fetch_stats;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static void
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+
+ ForeignTable *table;
+ ForeignServer *server;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ bool remote_analyze = false;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+
+ RemoteStatsResults remstats = { .rel = NULL, .att = NULL };
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ /*
+ * Assume the relation/schema names are the same as the local name unless
+ * the options tell us otherwise.
+ */
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ fetch_remote_statistics(conn, server_version_num,
+ remote_schemaname, remote_relname,
+ remote_analyze, &remstats);
+
+ ReleaseConnection(conn);
+
+ Assert(remstats.rel != NULL);
+ Assert(remstats.att != NULL);
+ import_fetched_statistics(relation, server_version_num,
+ schemaname, relname,
+ va_cols, &remstats);
+
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+}
+
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 9a8f9e28135..7a1787d7d79 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1278,7 +1279,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3895,6 +3897,10 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the table level.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3932,6 +3938,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
@@ -4379,6 +4389,40 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
base-commit: 315342ffedf6b81f629c42e87bfaedbcc7211646
--
2.52.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-12-14 18:40 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 2 replies; 89+ messages in thread
From: Etsuro Fujita @ 2025-12-14 18:40 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Sun, Dec 14, 2025 at 4:12 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> On Fri, Dec 12, 2025 at 2:45 PM Corey Huinker <corey.huinker@gmail.com> wrote:
>> CCing Jonathan Katz and Nathan Bossart as they had been sounding boards for me when I started designing this feature.
>>> Returning in the FDW_IMPORT_STATS_OK case isn't 100% correct; if the
>>> foreign table is an inheritance parent, we would fail to do inherited
>>> stats.
>> Perhaps I'm not understanding completely, but I believe what we're doing now should be ok.
>>
>> The local table of type 'f' can be a member of a partition, but can't be a partition itself, so whatever stats we get for it, we're storing them as inh = false.
>>
>> On the remote side, the table could be an inheritance parent, in which case we ONLY want the inh=true stats, but we will still store them locally as inh = false.
>>
>> The DISTINCT ON(a.attname)....ORDER BY a.attname, s.inherited DESC part of the query ensures that we get inh=true stats if they're there in preference to the inh=false steps.
>>
>> I will grant you that in an old-style inheritance (i.e. not formal partitions) situation we'd probably want some weighted mix of the inherited and non-inherited stats, but 1) very few people use old-style inheritance anymore, 2) few of those export tables via a FDW, and 3) there's no way to do that weighting so we should fall back to sampling anyway.
Ah, I mean the case where the foreign table is an inheritance parent
on the *local* side. In that case, the return would cause us to skip
the recursive ANALYZE (i.e., do_analyze_rel() with inh=true), leading
to no inherited stats. I agree that the case is minor, but I don't
think that that's acceptable.
>>> void
>>> ImportStatistics(Relation relation, List *va_cols, int elevel)
>>>
>>> Imports the stats for the foreign table from the foreign server. As
>>> mentioned in previous emails, I don't think it's a good idea to fall
>>> back to the normal processing when the attempt to import the stats
>>> fails, in which case I think we should just throw an error (or
>>> warning) so that the user can re-try to import the stats after fixing
>>> the foreign side in some way. So I re-defined this as a void
>>> function. Note that this re-definition removes the concern mentioned
>>> in the comment starting with "XXX:". In the postgres_fdw case, as
>>> mentioned in a previous email, I think it would be good to implement
>>> this so that it checks whether the remote table is a view or not when
>>> importing the relation stats from the remote server, and if so, just
>>> throws an error (or warning), making the user reset the fetch_stats
>>> flag.
>> I think I'm ok with this design as the decision, as it still leaves open the fdw-specific options of how to handle initially finding no remote stats.
>>
>> I can still see a situation where a local table expects the remote table to eventually have proper statistics on it, but until that happens it will fall back to table samples. This design decision means that either the user lives without any statistics for a while, or alters the foreign table options and hopefully remembers to set them back. While I understand the desire to first implement something very simple, I think that adding the durability that fallback allows for will be harder to implement if we don't build it in from the start. I'm interested to hear with Nathan and/or Jonathan have to say about that.
My concern about the fall-back behavior is that it reduces flexibility
in some cases, as mentioned upthread. Maybe that could be addressed
by making the behavior an option, but my another (bigger) concern is
that considering that it's the user's responsibility to make remote
stats up-to-date when he/she uses this feature, the "no remote stats
found" result would be his/her fault; it might not be worth
complicating the code for something like that.
Anyway, I too would like to hear the opinions of them (or anyone else).
> Anyway, here's v6 incorporating both threads of feedback.
Thanks for updating the patch! I will review the postgres_fdw changes next.
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-12-14 20:01 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2025-12-14 20:01 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> Ah, I mean the case where the foreign table is an inheritance parent
> on the *local* side. In that case, the return would cause us to skip
> the recursive ANALYZE (i.e., do_analyze_rel() with inh=true), leading
> to no inherited stats. I agree that the case is minor, but I don't
> think that that's acceptable.
>
When such a corner case occurs (stats import configured to true, but table
is an inheritance parent), should we raise an error, or raise a warning and
return false on the CanImportStats() call? I guess the answer may depend on
the feedback we get.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2025-12-15 10:01 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 0 replies; 89+ messages in thread
From: Etsuro Fujita @ 2025-12-15 10:01 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Mon, Dec 15, 2025 at 5:01 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>> Ah, I mean the case where the foreign table is an inheritance parent
>> on the *local* side. In that case, the return would cause us to skip
>> the recursive ANALYZE (i.e., do_analyze_rel() with inh=true), leading
>> to no inherited stats. I agree that the case is minor, but I don't
>> think that that's acceptable.
> When such a corner case occurs (stats import configured to true, but table is an inheritance parent), should we raise an error, or raise a warning and return false on the CanImportStats() call? I guess the answer may depend on the feedback we get.
As mentioned upthread, the FDW API that I proposed addresses this
issue; even in such a case it allows the FDW to import stats, instead
of doing the normal non-recursive ANALYZE, and then do the recursive
ANALYZE, for the inherited stats.
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-03 10:06 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-01-03 10:06 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Mon, Dec 15, 2025 at 3:40 AM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
> On Sun, Dec 14, 2025 at 4:12 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> > Anyway, here's v6 incorporating both threads of feedback.
>
> I will review the postgres_fdw changes next.
I spent some time reviewing the changes.
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will first attempt to fetch and import the existing relation and
+ attribute statistics from the remote table, and only attempt regular
+ data sampling if no statistics were available. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
This version of the patch wouldn't fall back to the normal ANALYZE
processing anymore, so this documentation should be updated as such.
Also, as I think it's the user's responsibility to ensure the existing
statistics are up-to-date, as I said before, I think we should add a
note about that here. Also, as some users wouldn't be able to ensure
it, I'm wondering if the default should be false.
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ is only meaningful if the foreign table has
+ <literal>fetch_stats</literal> enabled at either the server or table
+ level.
If the user wasn't able to ensure the statistics are up-to-date, I
think he/she might want to do remote ANALYZE *before* fetching the
statistics, not after trying to do so. So I think we could instead
provide this option as such. What do you think about that? Anyway,
I'd vote for leaving this for another patch, as I think it's a
nice-to-have option rather than a must-have one, as I said before.
ISTM that the code is well organized overall. Here are a few comments:
+static const char *relstats_query_18 =
+ "SELECT c.relkind, c.relpages, c.reltuples, c.relallvisible,
c.relallfrozen "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
We don't use relallvisible and relallfrozen for foreign tables (note
that do_analyze_rel() calls vac_update_relstats() with relallvisible=0
and relallfrozen=0 for them). Do we really need to retrieve (and
restore) them?
+static const char *attstats_query_17 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "ORDER BY s.attname, s.inherited DESC";
I think we should retrieve the attribute statistics for only the
referenced columns of the remote table, not all the columns of it, to
reduce the data transfer and the cost of matching local/remote
attributes in import_fetched_statistics().
In fetch_remote_statistics()
+ if (server_version_num >= 180000)
+ relation_sql = relstats_query_18;
+ else if (server_version_num >= 140000)
+ relation_sql = relstats_query_14;
+ else
+ relation_sql = relstats_query_default;
I think that having the definition for each of relstats_query_18,
relstats_query_14 and relstats_query_default makes the code redundant
and the maintenance hard. To avoid that, how about building the
relation_sql query dynamically as done for the query to fetch all
table data from the remote server in postgresImportForeignSchema().
Same for the attribute_sql query.
That's all I have for now. I will continue to review the changes.
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-04 02:56 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-01-04 02:56 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
>
> This version of the patch wouldn't fall back to the normal ANALYZE
> processing anymore, so this documentation should be updated as such.
> Also, as I think it's the user's responsibility to ensure the existing
> statistics are up-to-date, as I said before, I think we should add a
> note about that here. Also, as some users wouldn't be able to ensure
> it, I'm wondering if the default should be false.
>
I agree, if there is no fallback, then the default should be false. When I
was initially brainstorming this patch, Nathan Bossart had suggested making
it the default because 1) that would be an automatic benefit to users and
2) the cost for attempting to import stats was small in comparison to a
table stample, so it was worth the attempt. I still want users to get that
automatic benefit, but if there is no fallback to sampling then the default
only makes sense as false.
> If the user wasn't able to ensure the statistics are up-to-date, I
> think he/she might want to do remote ANALYZE *before* fetching the
> statistics, not after trying to do so. So I think we could instead
> provide this option as such. What do you think about that? Anyway,
> I'd vote for leaving this for another patch, as I think it's a
> nice-to-have option rather than a must-have one, as I said before.
>
I hadn't thought of that one. I think it has some merit, but I think we'd
want the try-after case as well. So the settings would be: "off" (never
remote analyze, default), "on" (always analyze before fetching), and
"retry" (analyze if no stats were found). This feature feeds into the same
thinking that the default setting did, which was to make this feature just
do what is usually the smart thing, and do it automatically. Building it in
pieces might be easier to get committed, but it takes away the dream of
seamless automatic improvement, and establishes defaults that can't be
changed in future versions. That dream was probably unrealistic, but I
wanted to try.
>
> ISTM that the code is well organized overall. Here are a few comments:
>
Thanks!
>
> We don't use relallvisible and relallfrozen for foreign tables (note
> that do_analyze_rel() calls vac_update_relstats() with relallvisible=0
> and relallfrozen=0 for them). Do we really need to retrieve (and
> restore) them?
>
No, and as you stated, we wouldn't want to. The query was lifted verbatim
from pg_dump, with a vague hope of moving the queries to a common library
that both pg_dump and postgres_fdw could draw upon. But that no longer
makes sense, so I'll fix.
> +static const char *attstats_query_17 =
> + "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
> + "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
> + "s.histogram_bounds, s.correlation, s.most_common_elems, "
> + "s.most_common_elem_freqs, s.elem_count_histogram, "
> + "s.range_length_histogram, s.range_empty_frac,
> s.range_bounds_histogram "
> + "FROM pg_catalog.pg_stats AS s "
> + "WHERE s.schemaname = $1 AND s.tablename = $2 "
> + "ORDER BY s.attname, s.inherited DESC";
>
> I think we should retrieve the attribute statistics for only the
> referenced columns of the remote table, not all the columns of it, to
> reduce the data transfer and the cost of matching local/remote
> attributes in import_fetched_statistics().
>
I thought about this, and decided that we wanted to 1) avoid per-column
round trips and 2) keep the remote queries simple. It's not such a big deal
to add "AND s.attname = ANY($3)" and construct a '{att1,att2,"ATt3"}'
string, as we already do in pg_dump in a few places.
>
> In fetch_remote_statistics()
>
> + if (server_version_num >= 180000)
> + relation_sql = relstats_query_18;
> + else if (server_version_num >= 140000)
> + relation_sql = relstats_query_14;
> + else
> + relation_sql = relstats_query_default;
>
> I think that having the definition for each of relstats_query_18,
> relstats_query_14 and relstats_query_default makes the code redundant
> and the maintenance hard. To avoid that, how about building the
> relation_sql query dynamically as done for the query to fetch all
> table data from the remote server in postgresImportForeignSchema().
> Same for the attribute_sql query.
>
It may be a moot point. If we're not fetching relallfrozen, then the 14 &
18 cases are now the same, and since the pre-14 case concerns
differentiating between analyzed and unanalyzed tables, we would just map
that to 0 IF we kept those stats, but we almost never would because an
unanalyzed remote table would not have the attribute stats necessary to
qualify as a good remote fetch. So we're down to just one static query.
>
> That's all I have for now. I will continue to review the changes.
>
Much appreciated.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-06 11:58 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 2 replies; 89+ messages in thread
From: Etsuro Fujita @ 2026-01-06 11:58 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Sun, Jan 4, 2026 at 11:56 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>> This version of the patch wouldn't fall back to the normal ANALYZE
>> processing anymore, so this documentation should be updated as such.
>> Also, as I think it's the user's responsibility to ensure the existing
>> statistics are up-to-date, as I said before, I think we should add a
>> note about that here. Also, as some users wouldn't be able to ensure
>> it, I'm wondering if the default should be false.
> I agree, if there is no fallback, then the default should be false. When I was initially brainstorming this patch, Nathan Bossart had suggested making it the default because 1) that would be an automatic benefit to users and 2) the cost for attempting to import stats was small in comparison to a table stample, so it was worth the attempt. I still want users to get that automatic benefit, but if there is no fallback to sampling then the default only makes sense as false.
I think that the FDW API that I proposed could actually allow us to
fall back to sampling, by modifying StatisticsAreImportable so that it
also checks if 1) there are statistics on the remote server and 2) the
data is fresh enough, and if so, returns true; otherwise, returns
false; in the latter case we could fall back to sampling. And if we
modified it as such, I think we could change the default to true.
(Checking #2 is necessary to avoid importing stale data, which would
degrade plan quality.)
>> If the user wasn't able to ensure the statistics are up-to-date, I
>> think he/she might want to do remote ANALYZE *before* fetching the
>> statistics, not after trying to do so. So I think we could instead
>> provide this option as such. What do you think about that? Anyway,
>> I'd vote for leaving this for another patch, as I think it's a
>> nice-to-have option rather than a must-have one, as I said before.
> I hadn't thought of that one. I think it has some merit, but I think we'd want the try-after case as well. So the settings would be: "off" (never remote analyze, default), "on" (always analyze before fetching), and "retry" (analyze if no stats were found). This feature feeds into the same thinking that the default setting did, which was to make this feature just do what is usually the smart thing, and do it automatically. Building it in pieces might be easier to get committed, but it takes away the dream of seamless automatic improvement, and establishes defaults that can't be changed in future versions. That dream was probably unrealistic, but I wanted to try.
Remote ANALYZE would be an interesting idea, but to get the automatic
improvement, I think we should first work on the issue I mentioned
above. So I still think we should leave this for future work.
From a different perspective, even without the automatic improvement
including remote ANALYZE, I think this feature is useful for many
users.
>> +static const char *attstats_query_17 =
>> + "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
>> + "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
>> + "s.histogram_bounds, s.correlation, s.most_common_elems, "
>> + "s.most_common_elem_freqs, s.elem_count_histogram, "
>> + "s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
>> + "FROM pg_catalog.pg_stats AS s "
>> + "WHERE s.schemaname = $1 AND s.tablename = $2 "
>> + "ORDER BY s.attname, s.inherited DESC";
>>
>> I think we should retrieve the attribute statistics for only the
>> referenced columns of the remote table, not all the columns of it, to
>> reduce the data transfer and the cost of matching local/remote
>> attributes in import_fetched_statistics().
> I thought about this, and decided that we wanted to 1) avoid per-column round trips and 2) keep the remote queries simple. It's not such a big deal to add "AND s.attname = ANY($3)" and construct a '{att1,att2,"ATt3"}' string, as we already do in pg_dump in a few places.
Yeah, I was also thinking of modifying the query as you proposed.
>> In fetch_remote_statistics()
>>
>> + if (server_version_num >= 180000)
>> + relation_sql = relstats_query_18;
>> + else if (server_version_num >= 140000)
>> + relation_sql = relstats_query_14;
>> + else
>> + relation_sql = relstats_query_default;
>>
>> I think that having the definition for each of relstats_query_18,
>> relstats_query_14 and relstats_query_default makes the code redundant
>> and the maintenance hard. To avoid that, how about building the
>> relation_sql query dynamically as done for the query to fetch all
>> table data from the remote server in postgresImportForeignSchema().
>> Same for the attribute_sql query.
> It may be a moot point. If we're not fetching relallfrozen, then the 14 & 18 cases are now the same, and since the pre-14 case concerns differentiating between analyzed and unanalyzed tables, we would just map that to 0 IF we kept those stats, but we almost never would because an unanalyzed remote table would not have the attribute stats necessary to qualify as a good remote fetch. So we're down to just one static query.
You are right. As the relation_sql query is only used in
fetch_remote_statistics(), shouldn't the query be defined within that
function?
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-06 14:12 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-01-06 14:12 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
>
> I think that the FDW API that I proposed could actually allow us to
> fall back to sampling, by modifying StatisticsAreImportable so that it
> also checks if 1) there are statistics on the remote server and 2) the
> data is fresh enough, and if so, returns true; otherwise, returns
> false; in the latter case we could fall back to sampling. And if we
> modified it as such, I think we could change the default to true.
> (Checking #2 is necessary to avoid importing stale data, which would
> degrade plan quality.)
>
So while I haven't checked for "freshness" of the statistics, I have added
checks that ensure that every asked-for column in the local table with
attstattarget != 0 will be send in the column filter, and we:
1. Find remote stats for all the columns that made our list
2. Do not get any stats over the wire with no matching target column.
3. Sort the list of expected remote column names, which means the list
matching is effectively a merge, so O(N) vs O(N^2). This is done with a
name+attnum structure, but it could just as easily have been done with a
local_name+remote_name, as pg_restore_attribute_stats() will take either
attnum or attname as a parameter.
Aside from a pre-emptive ANALYZE, how would you propose we check for and/or
measure "freshness" of the remote statistics?
> Remote ANALYZE would be an interesting idea, but to get the automatic
> improvement, I think we should first work on the issue I mentioned
> above. So I still think we should leave this for future work.
>
> From a different perspective, even without the automatic improvement
> including remote ANALYZE, I think this feature is useful for many
> users.
>
I'm still hoping to hear from Nathan on this subject.
> >> I think we should retrieve the attribute statistics for only the
> >> referenced columns of the remote table, not all the columns of it, to
> >> reduce the data transfer and the cost of matching local/remote
> >> attributes in import_fetched_statistics().
>
> > I thought about this, and decided that we wanted to 1) avoid per-column
> round trips and 2) keep the remote queries simple. It's not such a big deal
> to add "AND s.attname = ANY($3)" and construct a '{att1,att2,"ATt3"}'
> string, as we already do in pg_dump in a few places.
>
> Yeah, I was also thinking of modifying the query as you proposed.
>
That is done in the patch attached.
> > It may be a moot point. If we're not fetching relallfrozen, then the 14
> & 18 cases are now the same, and since the pre-14 case concerns
> differentiating between analyzed and unanalyzed tables, we would just map
> that to 0 IF we kept those stats, but we almost never would because an
> unanalyzed remote table would not have the attribute stats necessary to
> qualify as a good remote fetch. So we're down to just one static query.
>
> You are right. As the relation_sql query is only used in
> fetch_remote_statistics(), shouldn't the query be defined within that
> function?
>
Oddly enough, I already moved it inside of fetch_remote_statistics() in the
newest patch.
I wasn't planning on posting this patch until we had heard back from
Nathan, but since I'd already been working on a few of the items you
mentioned in your last email, I thought I'd show you that work in
progress. Some issues like the documentation haven't been updated, so it's
more of a work in progress, but it does pass the tests.
Summary of key points of this v7 WIP:
* Reduced columns on relstats query, query moved inside calling function.
* Per-column filters on attstats queries, filtering on destination
attstattarget != 0.
* Verification that all filtered-for columns have stats, and that all stats
in the result set have a matching target column.
* Expected column list is now sorted by remote-side attname, allowing a
merge join of the two lists.
* No changes to the documentation, but I know they are needed.
Attachments:
v7-0001-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 41.5K) download
From ac5f0e95b8796947c7c2f637f1ea82a4d918e5d9 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 7 Aug 2025 23:58:38 -0400
Subject: [PATCH v7] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via two new options, fetch_stats and remote_analyze,
both are available at the server level and table level. If fetch_stats
is true, then the ANALYZE command will first attempt to fetch statistics
from the remote table and import those statistics locally.
If remote_analyze is true, and if the first attempt to fetch remote
statistics found no attribute statistics, then an attempt will be made
to ANALYZE the remote table before a second and final attempt to fetch
remote statistics.
If the attempts to fetch statistics result in no rows returned or none
of the rows returned matching the columns in the local table, then the
ANALYZE will raise an error.
This operation will only work on remote relations that can have stored
statistics: tables, partitioned tables, and materialized views. If the
remote relation is a view then remote fetching/analyzing is just wasted
effort and the user is better off setting fetch_stats to false for that
table.
The default for fetch_stats is true at both server and table level. The
default for remote_analyze is false at both the server and table level.
In both cases, setting a value at the table level will override the
corresponding server-level setting.
---
src/include/foreign/fdwapi.h | 9 +-
src/backend/commands/analyze.c | 44 +-
doc/src/sgml/postgres-fdw.sgml | 35 +-
.../postgres_fdw/expected/postgres_fdw.out | 52 +-
contrib/postgres_fdw/option.c | 10 +
contrib/postgres_fdw/postgres_fdw.c | 782 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 46 +-
7 files changed, 968 insertions(+), 10 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..e54d441125a 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -19,7 +19,6 @@
/* avoid including explain_state.h here */
typedef struct ExplainState ExplainState;
-
/*
* Callback function signatures --- see fdwhandler.sgml for more info.
*/
@@ -157,6 +156,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef void (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +260,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index a483424152c..9f633774b5f 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -113,6 +113,8 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool import_stats = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -194,15 +196,36 @@ analyze_rel(Oid relid, RangeVar *relation,
}
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
+ bool ok = false;
+
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ import_stats = true;
+ else
+ {
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
+ }
+
if (fdwroutine->AnalyzeForeignTable != NULL)
ok = fdwroutine->AnalyzeForeignTable(onerel,
&acquirefunc,
@@ -248,9 +271,18 @@ analyze_rel(Oid relid, RangeVar *relation,
/*
* Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * tables, which don't contain any rows. For foreign tables, if they
+ * support importing statistics, do that instead of the non-recursive
+ * ANALYZE.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+ else if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 9b032fbf675..5439ce9eb09 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,39 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will first attempt to fetch and import the existing relation and
+ attribute statistics from the remote table, and only attempt regular
+ data sampling if no statistics were available. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ is only meaningful if the foreign table has
+ <literal>fetch_stats</literal> enabled at either the server or table
+ level.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 6066510c7c0..1f7ebeda82c 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4551,7 +4552,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11462,6 +11464,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p2
+ANALYZE async_pt;
+ERROR: Failed to import statistics from remote table public.base_tbl2, no statistics found.
+-- Turn off fetch_stats at the table level.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11568,6 +11575,11 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+ERROR: Failed to import statistics from remote table public.base_tbl3, no statistics found.
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
@@ -12665,6 +12677,44 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..2941ecbfb87 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,8 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +280,14 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 3572689e33b..9ea6aa2ed59 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -22,6 +22,8 @@
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -48,6 +50,7 @@
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
+#include "utils/syscache.h"
PG_MODULE_MAGIC_EXT(
.name = "postgres_fdw",
@@ -317,6 +320,20 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ char remote_attname[NAMEDATALEN];
+ AttrNumber local_attnum;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -402,6 +419,10 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresStatisticsAreImportable(Relation relation);
+static void postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +567,86 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns {
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_NUM_FIELDS
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname, s.inherited DESC";
+
+static const char *attstats_query_default =
+ "SELECT s.attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns {
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS
+};
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +696,8 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->StatisticsAreImportable = postgresStatisticsAreImportable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5038,685 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Process optional argument.
+ *
+ * Cannot be the first argument in the SQL function call.
+ *
+ * It is safe to presume that argname and argtype are quote-safe.
+ *
+ * Argument values can potentially be quite large, so free the quoted string
+ * after use.
+ */
+static void
+append_optional(StringInfo str, PGresult *res, int row, int field,
+ const char *argname, const char *argtype)
+{
+ if (!PQgetisnull(res, row, field))
+ {
+ /* Argument values can be quite large, so free after use */
+ char *argval_l = quote_literal_cstr(PQgetvalue(res, row, field));
+
+ appendStringInfo(str, ",\n\t'%s', %s::%s", argname, argval_l, argtype);
+
+ pfree(argval_l);
+ }
+}
+
+
+/*
+ * Generate a pg_restore_relation_stats command.
+ */
+static char *
+restore_relation_stats_sql(PGresult *res, const char *schemaname,
+ const char *relname, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s",
+ server_version_num, schemaname_l, relname_l);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, 0, RELSTATS_RELPAGES, "relpages", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELTUPLES, "reltuples", "real");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Generate a pg_restore_attribute_stats command.
+ */
+static char *
+restore_attribute_stats_sql(PGresult *res, int row,
+ const char *schemaname, const char *relname,
+ const AttrNumber attnum, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s,\n"
+ "\t'attnum', %d::smallint,\n"
+ "\t'inherited', false::boolean",
+ server_version_num, schemaname_l, relname_l, attnum);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, row, ATTSTATS_NULL_FRAC, "null_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_AVG_WIDTH, "avg_width", "integer");
+ append_optional(&sql, res, row, ATTSTATS_N_DISTINCT, "n_distinct", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_VALS, "most_common_vals", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_FREQS, "most_common_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_HISTOGRAM_BOUNDS, "histogram_bounds", "text");
+ append_optional(&sql, res, row, ATTSTATS_CORRELATION, "correlation", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEMS, "most_common_elems", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEM_FREQS, "most_common_elem_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_ELEM_COUNT_HISTOGRAM, "elem_count_histogram", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_LENGTH_HISTOGRAM, "range_length_histogram", "text");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_EMPTY_FRAC, "range_empty_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_BOUNDS_HISTOGRAM, "range_bounds_histogram", "text");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static void
+import_fetched_statistics(const char *schemaname, const char *relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping *remattrmap,
+ RemoteStatsResults *remstats)
+{
+ PGresult *res = remstats->att;
+ int spirc;
+ char *relimport_sql;
+ int mapidx = 0;
+
+ Assert(natts > 0);
+
+ SPI_connect();
+
+ /*
+ * Match result set rows to local attnums.
+ *
+ * Every row of the result should be an attribute that we specificially
+ * filtered for, so every row should have at least one match in the
+ * RemoteAttributeMapping, which is also ordered by attname, so we only
+ * need to walk that array once.
+ *
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ for (int i = 0; i < PQntuples(remstats->att); i++)
+ {
+ char *remote_attname;
+ char *attimport_sql;
+ bool match_found = false;
+ int cmp = 0;
+
+ if (PQgetisnull(res, i, ATTSTATS_ATTNAME))
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Remote statistics returned a row with NULL attribute name"));
+
+ remote_attname = PQgetvalue(res, i, ATTSTATS_ATTNAME);
+
+ /*
+ * Handle a series of matching elements in the mapping.
+ *
+ * We exit this loop in the following ways:
+ *
+ * 1. Having found at least match and exhausting the list. We're done.
+ * 2. Having found at least match and ending on a <, advance.
+ * 3. Having found at least match and ending on a >, bad sort.
+ * 4. No match, list exhausted.
+ * 5. No match, <.
+ * 6. No match, >.
+ *
+ */
+ for (; mapidx < natts; mapidx++)
+ {
+ cmp = strcmp(remote_attname, remattrmap[mapidx].remote_attname);
+
+ /* Stop scanning on the first non-match */
+ if (cmp != 0)
+ break;
+
+ match_found = true;
+
+ attimport_sql = restore_attribute_stats_sql(res, i,
+ schemaname, relname,
+ remattrmap[mapidx].local_attnum,
+ server_version_num);
+
+ spirc = SPI_execute(attimport_sql, false, 1);
+ pfree(attimport_sql);
+
+ /*
+ * It takes a lot to make a restore command fail outright, so any
+ * actual failure is a sign that the statistics are seriously
+ * malformed, and we should give up on importing stats for this
+ * table.
+ */
+ if (spirc != SPI_OK_SELECT)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics import failed %s",
+ attimport_sql));
+ }
+
+ /* We found a match, move onto the next result. */
+ if (match_found)
+ continue;
+
+ /*
+ * If no match and we ended on a <, then the mapidx will never find a
+ * match, so stop now and let the cleanup report the error.
+ */
+ if (cmp > 0)
+ break;
+
+ /*
+ * Otherwise this result found no matching mapidx, which should only
+ * happen if the results are out of sort or the wrong query was
+ * executed.
+ */
+ if (cmp < 0)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+ }
+
+ /* Look for a mapidx with no possible matching result */
+ if (mapidx < natts)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+
+ /*
+ * Import relation stats.
+ */
+ relimport_sql = restore_relation_stats_sql(remstats->rel, schemaname,
+ relname, server_version_num);
+
+ spirc = SPI_execute(relimport_sql, false, 1);
+
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ if (spirc != SPI_OK_SELECT)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Relation statistics import failed: %s.",
+ relimport_sql));
+
+ pfree(relimport_sql);
+ SPI_finish();
+}
+
+/*
+ * Analyze a remote table.
+ */
+static void
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s",
+ quote_qualified_identifier(remote_schemaname, remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL ||
+ PQresultStatus(res) != PGRES_COMMAND_OK)
+ pgfdw_report_error(res, conn, buf.data);
+
+ PQclear(res);
+ pfree(buf.data);
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ * Verify that the result is of the proper shape.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname)
+{
+ const char *params[2] = { remote_schemaname, remote_relname };
+
+ /*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case).
+ *
+ * We can ignore this change, because if the remote table wasn't analyzed,
+ * then it would have no attribute stats, and thus we wouldn't have stats that
+ * we would try to import. So we can take the reltuples value as-is.
+ */
+ const char *sql = "SELECT c.relkind, c.relpages, c.reltuples "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n "
+ "ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+ PGresult *res;
+
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS
+ || PQgetisnull(res, 0, RELSTATS_RELKIND))
+ pgfdw_report_error(res, conn, sql);
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ * Verify that the result is of the proper shape.
+ * Note that we do not verify the row count.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list, bool is_retry)
+{
+ const char *params[3] = { remote_schemaname, remote_relname, column_list };
+ int version = PQserverVersion(conn);
+ const char *sql;
+ PGresult *res;
+
+ if (version >= 170000)
+ sql = attstats_query_17;
+ else if (version >= 90200)
+ sql = attstats_query_9_2;
+ else if (version >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ pgfdw_report_error(res, conn, sql);
+
+ /* Getting nothing on the second try is a failure */
+ if (is_retry && PQntuples(res) == 0)
+ pgfdw_report_error(res, conn, sql);
+
+ return res;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static void
+fetch_remote_statistics(PGconn *conn,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping *remattrmap,
+ bool remote_analyze, RemoteStatsResults *remstats)
+{
+ StringInfoData column_list;
+
+ char relkind;
+
+ remstats->rel = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously can't
+ * support a foreign table.
+ */
+ relkind = *PQgetvalue(remstats->rel, 0, RELSTATS_RELKIND);
+
+ switch(relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Remote table %s does not support statistics.",
+ quote_qualified_identifier(remote_schemaname,
+ remote_relname)));
+ return;
+ }
+
+ initStringInfo(&column_list);
+ appendStringInfoChar(&column_list, '{');
+ for (int i = 0; i < natts; i++)
+ {
+ if (i > 0)
+ appendStringInfoChar(&column_list, ',');
+ appendStringInfoString(&column_list,
+ quote_identifier(remattrmap[i].remote_attname));
+ }
+ appendStringInfoChar(&column_list, '}');
+
+ /* See if it actually has any attribute stats. */
+ remstats->att = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list.data, false);
+
+ /*
+ * If we got attribute statistics results, then we are done with fetching.
+ */
+ if (PQntuples(remstats->att) > 0)
+ return;
+
+ /*
+ * Clear off any existing fetched statistics, if any. If the analyze works
+ * then they we want to fetch the new ones.
+ */
+ PQclear(remstats->att);
+ PQclear(remstats->rel);
+ remstats->att = NULL;
+ remstats->rel = NULL;
+
+ /*
+ * If remote_analyze is enabled, then we will try to analyze the table and
+ * then try again.
+ */
+ if (remote_analyze)
+ analyze_remote_table(conn, remote_schemaname, remote_relname);
+ else
+ ereport(ERROR,
+ errcode(ERRCODE_NO_DATA_FOUND),
+ errmsg("Failed to import statistics from remote table %s, "
+ "no statistics found.",
+ quote_qualified_identifier(remote_schemaname,
+ remote_relname)));
+
+ /*
+ * Remote ANALYZE complete, so re-fetch attribute stats query.
+ */
+ remstats->att = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list.data, true);
+
+ /* Re-fetch basic relation stats, as they have been updated. */
+ remstats->rel = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ pfree(column_list.data);
+}
+
+static bool
+postgresStatisticsAreImportable(Relation relation)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ ListCell *lc;
+ bool fetch_stats = true;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ return fetch_stats;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static void
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+
+ ForeignTable *table;
+ ForeignServer *server;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ bool remote_analyze = false;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int natts = 0;
+
+ RemoteAttributeMapping *remattrmap;
+
+ RemoteStatsResults remstats = { .rel = NULL, .att = NULL };
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ /*
+ * Assume the relation/schema names are the same as the local name unless
+ * the options tell us otherwise.
+ */
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ /*
+ * Build attnum/remote-attname list.
+ *
+ */
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *attname;
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+ HeapTuple atttuple;
+ bool isnull;
+ Datum dat;
+ int attstattarget;
+
+ /* Ignore dropped columns. */
+ if (TupleDescAttr(tupdesc, i)->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (TupleDescAttr(tupdesc, i)->attgenerated)
+ continue;
+
+ attname = NameStr(TupleDescAttr(tupdesc, i)->attname);
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ attnum = TupleDescAttr(tupdesc, i)->attnum;
+
+ /* Ignore if attstatarget is 0 */
+ atttuple = SearchSysCache2(ATTNUM,
+ ObjectIdGetDatum(RelationGetRelid(relation)),
+ Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, RelationGetRelid(relation));
+ dat = SysCacheGetAttr(ATTNUM, atttuple,
+ Anum_pg_attribute_attstattarget, &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+ if (attstattarget == 0)
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_colname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].remote_attname, remote_colname, NAMEDATALEN);
+ natts++;
+ }
+
+ /* Sort mapping by remote attribute name */
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ fetch_remote_statistics(conn, remote_schemaname, remote_relname,
+ server_version_num, natts, remattrmap,
+ remote_analyze, &remstats);
+
+ ReleaseConnection(conn);
+
+ Assert(remstats.rel != NULL);
+ Assert(remstats.att != NULL);
+ import_fetched_statistics(schemaname, relname, server_version_num, natts,
+ remattrmap, &remstats);
+
+ pfree(remattrmap);
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+}
+
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 4f7ab2ed0ac..c527a1fbb15 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1286,7 +1287,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3903,6 +3905,10 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the table level.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3940,6 +3946,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
@@ -4387,6 +4397,40 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
base-commit: 0547aeae0fd6f6d03dd7499c84145ad9e3aa51b9
--
2.52.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-06 21:38 Matheus Alcantara <matheusssilv97@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Matheus Alcantara @ 2026-01-06 21:38 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
Hi, thanks for working on this. Generally I think that this is a good
idea to avoid fetching rows from a foreign table to compute statistics
that may already be available on the foreign server.
I started reviewing the v7 patch and here are my initial comments. I
still want to do another round of review and run some more tests.
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ import_stats = true;
+ else
+ {
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
+ }
+
if (fdwroutine->AnalyzeForeignTable != NULL)
ok = fdwroutine->AnalyzeForeignTable(onerel,
&acquirefunc,
&relpages);
if (!ok)
{
ereport(WARNING,
(errmsg("skipping \"%s\" --- cannot analyze this foreign table",
RelationGetRelationName(onerel))));
relation_close(onerel, ShareUpdateExclusiveLock);
return;
}
It seems that we have the same code within the else branch after the if/else
check, is this correct?
---
+ * Every row of the result should be an attribute that we specificially
s/specificially/specifically
---
+ if (TupleDescAttr(tupdesc, i)->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (TupleDescAttr(tupdesc, i)->attgenerated)
+ continue;
+
+ attname = NameStr(TupleDescAttr(tupdesc, i)->attname);
Wouldn't be better to call TupleDescAttr a single time and save the value?
Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
/* Ignore dropped columns. */
if (attr->attisdropped)
continue;
...
--
Matheus Alcantara
EDB: https://www.enterprisedb.com
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-07 02:18 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Matheus Alcantara <matheusssilv97@gmail.com>
0 siblings, 0 replies; 89+ messages in thread
From: Etsuro Fujita @ 2026-01-07 02:18 UTC (permalink / raw)
To: Matheus Alcantara <matheusssilv97@gmail.com>; +Cc: Corey Huinker <corey.huinker@gmail.com>; Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
Hi Matheus,
On Wed, Jan 7, 2026 at 6:38 AM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:
> + if (fdwroutine->ImportStatistics != NULL &&
> + fdwroutine->StatisticsAreImportable != NULL &&
> + fdwroutine->StatisticsAreImportable(onerel))
> + import_stats = true;
> + else
> + {
> + if (fdwroutine->AnalyzeForeignTable != NULL)
> + ok = fdwroutine->AnalyzeForeignTable(onerel,
> + &acquirefunc,
> + &relpages);
> +
> + if (!ok)
> + {
> + ereport(WARNING,
> + errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
> + RelationGetRelationName(onerel)));
> + relation_close(onerel, ShareUpdateExclusiveLock);
> + return;
> + }
> + }
> +
> if (fdwroutine->AnalyzeForeignTable != NULL)
> ok = fdwroutine->AnalyzeForeignTable(onerel,
> &acquirefunc,
> &relpages);
>
> if (!ok)
> {
> ereport(WARNING,
> (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
> RelationGetRelationName(onerel))));
> relation_close(onerel, ShareUpdateExclusiveLock);
> return;
> }
>
> It seems that we have the same code within the else branch after the if/else
> check, is this correct?
No. This should be something like the attached in [1]. (I didn't
look at the core changes in v6...)
Thanks!
Best regards,
Etsuro Fujita
[1] https://www.postgresql.org/message-id/CAPmGK17Dfjy_zLH1yjPqybpSueHWP7Gy_xBZXA2NpRso1qya7A%40mail.gma...
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-07 06:04 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
1 sibling, 3 replies; 89+ messages in thread
From: Corey Huinker @ 2026-01-07 06:04 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> > I agree, if there is no fallback, then the default should be false. When
> I was initially brainstorming this patch, Nathan Bossart had suggested
> making it the default because 1) that would be an automatic benefit to
> users and 2) the cost for attempting to import stats was small in
> comparison to a table stample, so it was worth the attempt. I still want
> users to get that automatic benefit, but if there is no fallback to
> sampling then the default only makes sense as false.
>
> I think that the FDW API that I proposed could actually allow us to
> fall back to sampling, by modifying StatisticsAreImportable so that it
> also checks if 1) there are statistics on the remote server and 2) the
> data is fresh enough, and if so, returns true; otherwise, returns
> false; in the latter case we could fall back to sampling. And if we
> modified it as such, I think we could change the default to true.
> (Checking #2 is necessary to avoid importing stale data, which would
> degrade plan quality.)
I've given this some more thought.
First, we'd have to add the va_cols param to StatisticsAreImportable, which
isn't itself terrible.
Then, we'd have to determine that there are stats available for every
mapped column (filtered by va_cols, if any). But the only way to do that is
to query the pg_stats view on the remote end, and if we have done that,
then we've already fetched the stats. Yes, we could avoid selecting the
actual statistical values, and that would save some network bandwidth at
the cost of having to do the query again with stats. So I don't really see
the savings.
Also, the pg_stats view is our security-barrier black box into statistics,
and it gives no insight into how recently those stats were acquired. We
could poke pg_stat_all_tables, assuming we can even query it, and then make
a value judgement on the value of (CURRENT_TIMESTAMP -
GREATEST(last_analyze, last_autoanalyze), but that value is highly
subjective.
I suppose we could move all of the statistics fetching
into StatisticsAreImportable, And carry those values forward if they are
satisfactory. That would leave ImportStatistics() with little to do other
than form up the calls to pg_restore_*_stats(), but those could still fail,
and at that point we'd have no way to fall back to sampling and analysis.
I really want to make sampling fallback possible.
Anyway, here's v8, incorporating the documentation feedback and Matheus's
notes.
Attachments:
v8-0001-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 42.1K) download
From 57733548ed2e06b10f18f5299dae3e58aa453e67 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 7 Aug 2025 23:58:38 -0400
Subject: [PATCH v8] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via two new options, fetch_stats and remote_analyze,
both are available at the server level and table level. If fetch_stats
is true, then the ANALYZE command will attempt to fetch statistics
from the remote table and import those statistics locally.
If remote_analyze is true, and if the first attempt to fetch remote
statistics found no attribute statistics, then an attempt will be made
to ANALYZE the remote table before a second and final attempt to fetch
remote statistics.
If the attempts to fetch statistics result in some analyzed columns
missing imported statistics, then the ANALYZE will raise an error.
This operation will only work on remote relations that can have stored
statistics: tables, partitioned tables, and materialized views. If the
remote relation is a view then remote fetching/analyzing is just wasted
effort and the user is better off setting fetch_stats to false for that
table.
The default for fetch_stats is, for now, true at both server and table
level. The default for remote_analyze is false at both the server
and table level. In both cases, setting a value at the table level
will override the corresponding server-level setting.
---
src/include/foreign/fdwapi.h | 9 +-
src/backend/commands/analyze.c | 52 +-
doc/src/sgml/postgres-fdw.sgml | 38 +-
.../postgres_fdw/expected/postgres_fdw.out | 52 +-
contrib/postgres_fdw/option.c | 10 +
contrib/postgres_fdw/postgres_fdw.c | 797 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 46 +-
7 files changed, 983 insertions(+), 21 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..e54d441125a 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -19,7 +19,6 @@
/* avoid including explain_state.h here */
typedef struct ExplainState ExplainState;
-
/*
* Callback function signatures --- see fdwhandler.sgml for more info.
*/
@@ -157,6 +156,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef void (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +260,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index a483424152c..e69288968fc 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -113,6 +113,8 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool import_stats = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -195,26 +197,33 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ import_stats = true;
+ else
{
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
}
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
@@ -248,9 +257,18 @@ analyze_rel(Oid relid, RangeVar *relation,
/*
* Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * tables, which don't contain any rows. For foreign tables, if they
+ * support importing statistics, do that instead of the non-recursive
+ * ANALYZE.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+ else if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 9b032fbf675..05928835355 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,42 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</relation> and
+ <function>pg_restore_attribute_stats</relation>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ is only meaningful if the foreign table has
+ <literal>fetch_stats</literal> enabled at either the server or table
+ level.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 6066510c7c0..1f7ebeda82c 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4551,7 +4552,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11462,6 +11464,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p2
+ANALYZE async_pt;
+ERROR: Failed to import statistics from remote table public.base_tbl2, no statistics found.
+-- Turn off fetch_stats at the table level.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11568,6 +11575,11 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+ERROR: Failed to import statistics from remote table public.base_tbl3, no statistics found.
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
@@ -12665,6 +12677,44 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..2941ecbfb87 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,8 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +280,14 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 3572689e33b..e69cb421523 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -22,6 +22,8 @@
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -48,6 +50,7 @@
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
+#include "utils/syscache.h"
PG_MODULE_MAGIC_EXT(
.name = "postgres_fdw",
@@ -317,6 +320,20 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ char remote_attname[NAMEDATALEN];
+ AttrNumber local_attnum;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -402,6 +419,10 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresStatisticsAreImportable(Relation relation);
+static void postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +567,86 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns {
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_NUM_FIELDS
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname, s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+ "SELECT DISTINCT ON (s.attname) attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname, s.inherited DESC";
+
+static const char *attstats_query_default =
+ "SELECT s.attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns {
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS
+};
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +696,8 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->StatisticsAreImportable = postgresStatisticsAreImportable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5038,700 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Process optional argument.
+ *
+ * Cannot be the first argument in the SQL function call.
+ *
+ * It is safe to presume that argname and argtype are quote-safe.
+ *
+ * Argument values can potentially be quite large, so free the quoted string
+ * after use.
+ */
+static void
+append_optional(StringInfo str, PGresult *res, int row, int field,
+ const char *argname, const char *argtype)
+{
+ if (!PQgetisnull(res, row, field))
+ {
+ /* Argument values can be quite large, so free after use */
+ char *argval_l = quote_literal_cstr(PQgetvalue(res, row, field));
+
+ appendStringInfo(str, ",\n\t'%s', %s::%s", argname, argval_l, argtype);
+
+ pfree(argval_l);
+ }
+}
+
+
+/*
+ * Generate a pg_restore_relation_stats command.
+ */
+static char *
+restore_relation_stats_sql(PGresult *res, const char *schemaname,
+ const char *relname, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s",
+ server_version_num, schemaname_l, relname_l);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, 0, RELSTATS_RELPAGES, "relpages", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELTUPLES, "reltuples", "real");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Generate a pg_restore_attribute_stats command.
+ */
+static char *
+restore_attribute_stats_sql(PGresult *res, int row,
+ const char *schemaname, const char *relname,
+ const AttrNumber attnum, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s,\n"
+ "\t'attnum', %d::smallint,\n"
+ "\t'inherited', false::boolean",
+ server_version_num, schemaname_l, relname_l, attnum);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, row, ATTSTATS_NULL_FRAC, "null_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_AVG_WIDTH, "avg_width", "integer");
+ append_optional(&sql, res, row, ATTSTATS_N_DISTINCT, "n_distinct", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_VALS, "most_common_vals", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_FREQS, "most_common_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_HISTOGRAM_BOUNDS, "histogram_bounds", "text");
+ append_optional(&sql, res, row, ATTSTATS_CORRELATION, "correlation", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEMS, "most_common_elems", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEM_FREQS, "most_common_elem_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_ELEM_COUNT_HISTOGRAM, "elem_count_histogram", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_LENGTH_HISTOGRAM, "range_length_histogram", "text");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_EMPTY_FRAC, "range_empty_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_BOUNDS_HISTOGRAM, "range_bounds_histogram", "text");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static void
+import_fetched_statistics(const char *schemaname, const char *relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping *remattrmap,
+ RemoteStatsResults *remstats)
+{
+ PGresult *res = remstats->att;
+ int spirc;
+ char *relimport_sql;
+ int mapidx = 0;
+
+ Assert(natts > 0);
+
+ SPI_connect();
+
+ /*
+ * Match result set rows to local attnums.
+ *
+ * Every row of the result should be an attribute that we specifically
+ * filtered for, so every row should have at least one match in the
+ * RemoteAttributeMapping, which is also ordered by attname, so we only
+ * need to walk that array once.
+ *
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ for (int i = 0; i < PQntuples(remstats->att); i++)
+ {
+ char *remote_attname;
+ char *attimport_sql;
+ bool match_found = false;
+ int cmp = 0;
+
+ if (PQgetisnull(res, i, ATTSTATS_ATTNAME))
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Remote statistics returned a row with NULL attribute name"));
+
+ remote_attname = PQgetvalue(res, i, ATTSTATS_ATTNAME);
+
+ /*
+ * Handle a series of matching elements in the mapping.
+ *
+ * We exit this loop in the following ways:
+ *
+ * 1. Having found at least match and exhausting the list. We're done.
+ * 2. Having found at least match and ending on a <, advance.
+ * 3. Having found at least match and ending on a >, bad sort.
+ * 4. No match, list exhausted.
+ * 5. No match, <.
+ * 6. No match, >.
+ *
+ */
+ for (; mapidx < natts; mapidx++)
+ {
+ cmp = strcmp(remote_attname, remattrmap[mapidx].remote_attname);
+
+ /* Stop scanning on the first non-match */
+ if (cmp != 0)
+ break;
+
+ match_found = true;
+
+ attimport_sql = restore_attribute_stats_sql(res, i,
+ schemaname, relname,
+ remattrmap[mapidx].local_attnum,
+ server_version_num);
+
+ spirc = SPI_execute(attimport_sql, false, 1);
+ pfree(attimport_sql);
+
+ /*
+ * It takes a lot to make a restore command fail outright, so any
+ * actual failure is a sign that the statistics are seriously
+ * malformed, and we should give up on importing stats for this
+ * table.
+ */
+ if (spirc != SPI_OK_SELECT)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics import failed %s",
+ attimport_sql));
+ }
+
+ /* We found a match, move onto the next result. */
+ if (match_found)
+ continue;
+
+ /*
+ * If no match and we ended on a <, then the mapidx will never find a
+ * match, so stop now and let the cleanup report the error.
+ */
+ if (cmp > 0)
+ break;
+
+ /*
+ * Otherwise this result found no matching mapidx, which should only
+ * happen if the results are out of sort or the wrong query was
+ * executed.
+ */
+ if (cmp < 0)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+ }
+
+ /* Look for a mapidx with no possible matching result */
+ if (mapidx < natts)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+
+ /*
+ * Import relation stats.
+ */
+ relimport_sql = restore_relation_stats_sql(remstats->rel, schemaname,
+ relname, server_version_num);
+
+ spirc = SPI_execute(relimport_sql, false, 1);
+
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ if (spirc != SPI_OK_SELECT)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Relation statistics import failed: %s.",
+ relimport_sql));
+
+ pfree(relimport_sql);
+ SPI_finish();
+}
+
+/*
+ * Analyze a remote table.
+ */
+static void
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s",
+ quote_qualified_identifier(remote_schemaname, remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL ||
+ PQresultStatus(res) != PGRES_COMMAND_OK)
+ pgfdw_report_error(res, conn, buf.data);
+
+ PQclear(res);
+ pfree(buf.data);
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ * Verify that the result is of the proper shape.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname)
+{
+ const char *params[2] = { remote_schemaname, remote_relname };
+
+ /*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case).
+ *
+ * We can ignore this change, because if the remote table wasn't analyzed,
+ * then it would have no attribute stats, and thus we wouldn't have stats that
+ * we would try to import. So we can take the reltuples value as-is.
+ */
+ const char *sql = "SELECT c.relkind, c.relpages, c.reltuples "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n "
+ "ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+ PGresult *res;
+
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS
+ || PQgetisnull(res, 0, RELSTATS_RELKIND))
+ pgfdw_report_error(res, conn, sql);
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ * Verify that the result is of the proper shape.
+ * Note that we do not verify the row count.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list, bool is_retry)
+{
+ const char *params[3] = { remote_schemaname, remote_relname, column_list };
+ int version = PQserverVersion(conn);
+ const char *sql;
+ PGresult *res;
+
+ if (version >= 170000)
+ sql = attstats_query_17;
+ else if (version >= 90200)
+ sql = attstats_query_9_2;
+ else if (version >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ pgfdw_report_error(res, conn, sql);
+
+ /* Getting nothing on the second try is a failure */
+ if (is_retry && PQntuples(res) == 0)
+ pgfdw_report_error(res, conn, sql);
+
+ return res;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static void
+fetch_remote_statistics(PGconn *conn,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping *remattrmap,
+ bool remote_analyze, RemoteStatsResults *remstats)
+{
+ StringInfoData column_list;
+
+ char relkind;
+
+ remstats->rel = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously can't
+ * support a foreign table.
+ */
+ relkind = *PQgetvalue(remstats->rel, 0, RELSTATS_RELKIND);
+
+ switch(relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Remote table %s does not support statistics.",
+ quote_qualified_identifier(remote_schemaname,
+ remote_relname)));
+ return;
+ }
+
+ initStringInfo(&column_list);
+ appendStringInfoChar(&column_list, '{');
+ for (int i = 0; i < natts; i++)
+ {
+ if (i > 0)
+ appendStringInfoChar(&column_list, ',');
+ appendStringInfoString(&column_list,
+ quote_identifier(remattrmap[i].remote_attname));
+ }
+ appendStringInfoChar(&column_list, '}');
+
+ /* See if it actually has any attribute stats. */
+ remstats->att = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list.data, false);
+
+ /*
+ * If we got attribute statistics results, then we are done with fetching.
+ */
+ if (PQntuples(remstats->att) > 0)
+ return;
+
+ /*
+ * Clear off any existing fetched statistics, if any. If the analyze works
+ * then they we want to fetch the new ones.
+ */
+ PQclear(remstats->att);
+ PQclear(remstats->rel);
+ remstats->att = NULL;
+ remstats->rel = NULL;
+
+ /*
+ * If remote_analyze is enabled, then we will try to analyze the table and
+ * then try again.
+ */
+ if (remote_analyze)
+ analyze_remote_table(conn, remote_schemaname, remote_relname);
+ else
+ ereport(ERROR,
+ errcode(ERRCODE_NO_DATA_FOUND),
+ errmsg("Failed to import statistics from remote table %s, "
+ "no statistics found.",
+ quote_qualified_identifier(remote_schemaname,
+ remote_relname)));
+
+ /*
+ * Remote ANALYZE complete, so re-fetch attribute stats query.
+ */
+ remstats->att = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list.data, true);
+
+ /* Re-fetch basic relation stats, as they have been updated. */
+ remstats->rel = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ pfree(column_list.data);
+}
+
+static bool
+postgresStatisticsAreImportable(Relation relation)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ ListCell *lc;
+ bool fetch_stats = true;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ return fetch_stats;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Fetch attstattarget from a pg_attribute tuple.
+ */
+static int16
+get_attstattarget(Relation relation, AttrNumber attnum)
+{
+ HeapTuple atttuple;
+ bool isnull;
+ Datum dat;
+ int16 attstattarget;
+ Oid relid = RelationGetRelid(relation);
+
+ atttuple = SearchSysCache2(ATTNUM,
+ ObjectIdGetDatum(relid),
+ Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, relid);
+ dat = SysCacheGetAttr(ATTNUM, atttuple,
+ Anum_pg_attribute_attstattarget,
+ &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ return attstattarget;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static void
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+
+ ForeignTable *table;
+ ForeignServer *server;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ bool remote_analyze = false;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int natts = 0;
+
+ RemoteAttributeMapping *remattrmap;
+
+ RemoteStatsResults remstats = { .rel = NULL, .att = NULL };
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ /*
+ * Assume the relation/schema names are the same as the local name unless
+ * the options tell us otherwise.
+ */
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ /*
+ * Build attnum/remote-attname list.
+ *
+ */
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *attname;
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+
+ /* Ignore dropped columns. */
+ if (attr->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (attr->attgenerated)
+ continue;
+
+ attname = NameStr(attr->attname);
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ attnum = attr->attnum;
+
+ /* Ignore if attstatarget is 0 */
+ if (get_attstattarget(relation,attnum) == 0)
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_colname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].remote_attname, remote_colname, NAMEDATALEN);
+ natts++;
+ }
+
+ /* Sort mapping by remote attribute name */
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ fetch_remote_statistics(conn, remote_schemaname, remote_relname,
+ server_version_num, natts, remattrmap,
+ remote_analyze, &remstats);
+
+ ReleaseConnection(conn);
+
+ Assert(remstats.rel != NULL);
+ Assert(remstats.att != NULL);
+ import_fetched_statistics(schemaname, relname, server_version_num, natts,
+ remattrmap, &remstats);
+
+ pfree(remattrmap);
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+}
+
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 4f7ab2ed0ac..c527a1fbb15 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1286,7 +1287,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3903,6 +3905,10 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the table level.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3940,6 +3946,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
@@ -4387,6 +4397,40 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
base-commit: a2e632ece1691be18771644182f769b525991f97
--
2.52.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-07 15:17 Matheus Alcantara <matheusssilv97@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
2 siblings, 1 reply; 89+ messages in thread
From: Matheus Alcantara @ 2026-01-07 15:17 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Wed Jan 7, 2026 at 3:04 AM -03, Corey Huinker wrote:
>>
>> > I agree, if there is no fallback, then the default should be false. When
>> I was initially brainstorming this patch, Nathan Bossart had suggested
>> making it the default because 1) that would be an automatic benefit to
>> users and 2) the cost for attempting to import stats was small in
>> comparison to a table stample, so it was worth the attempt. I still want
>> users to get that automatic benefit, but if there is no fallback to
>> sampling then the default only makes sense as false.
>>
>> I think that the FDW API that I proposed could actually allow us to
>> fall back to sampling, by modifying StatisticsAreImportable so that it
>> also checks if 1) there are statistics on the remote server and 2) the
>> data is fresh enough, and if so, returns true; otherwise, returns
>> false; in the latter case we could fall back to sampling. And if we
>> modified it as such, I think we could change the default to true.
>> (Checking #2 is necessary to avoid importing stale data, which would
>> degrade plan quality.)
>
>
> I've given this some more thought.
>
> First, we'd have to add the va_cols param to StatisticsAreImportable, which
> isn't itself terrible.
>
> Then, we'd have to determine that there are stats available for every
> mapped column (filtered by va_cols, if any). But the only way to do that is
> to query the pg_stats view on the remote end, and if we have done that,
> then we've already fetched the stats. Yes, we could avoid selecting the
> actual statistical values, and that would save some network bandwidth at
> the cost of having to do the query again with stats. So I don't really see
> the savings.
>
> Also, the pg_stats view is our security-barrier black box into statistics,
> and it gives no insight into how recently those stats were acquired. We
> could poke pg_stat_all_tables, assuming we can even query it, and then make
> a value judgement on the value of (CURRENT_TIMESTAMP -
> GREATEST(last_analyze, last_autoanalyze), but that value is highly
> subjective.
>
> I suppose we could move all of the statistics fetching
> into StatisticsAreImportable, And carry those values forward if they are
> satisfactory. That would leave ImportStatistics() with little to do other
> than form up the calls to pg_restore_*_stats(), but those could still fail,
> and at that point we'd have no way to fall back to sampling and analysis.
>
> I really want to make sampling fallback possible.
>
> Anyway, here's v8, incorporating the documentation feedback and Matheus's
> notes.
Thanks for the new version.
+static bool
+postgresStatisticsAreImportable(Relation relation)
+...
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
I don't think that it's good to make StatisticsAreImportable() routine
check if fetch_stats is enabled on foreign server/table options because
if so, every fdw implementation would need this same block of code and
also fdw implementations may forget or bypass these options which I
don't think that it would be a desired behavior. What about move this
check to analyze_rel()? Perhaps create a function that just check if the
fetch_stats is enabled.
If the above statement make sense, it seems to me that
StatisticsAreImportable() may not be needed at all.
I think that we could make analyze_rel() check if fetch_stats is enable
on the foreign server/table and then call ImportStatistics() which could
return true or false. If it returns true it means that the statistics
was imported successfully, otherwise if it returns false we could
fallback to table sampling as we already do today. ImportStatistics
could return false if the foreign server don't have statistics for the
requested table, even after running ANALYZE if remote_analyze is true.
Is that make sense? Any thoughts?
--
Matheus Alcantara
EDB: https://www.enterprisedb.com
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-07 19:17 Corey Huinker <corey.huinker@gmail.com>
parent: Matheus Alcantara <matheusssilv97@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-01-07 19:17 UTC (permalink / raw)
To: Matheus Alcantara <matheusssilv97@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> +
> I don't think that it's good to make StatisticsAreImportable() routine
> check if fetch_stats is enabled on foreign server/table options because
> if so, every fdw implementation would need this same block of code and
> also fdw implementations may forget or bypass these options which I
> don't think that it would be a desired behavior. What about move this
> check to analyze_rel()? Perhaps create a function that just check if the
> fetch_stats is enabled.
>
StatisticsAreImportable() is a virtual function whose goal is to determine
if this specific table supports stats exporting.
postgresStatisticsAreImportable() is the postgres_fdw implementation of
that virtual function.
Any other FDWs that want to implement stats import will need to invent
their own tests and configurations to determine if that is possible.
>
> If the above statement make sense, it seems to me that
> StatisticsAreImportable() may not be needed at all.
>
It wasn't there, initially.
>
> I think that we could make analyze_rel() check if fetch_stats is enable
> on the foreign server/table and then call ImportStatistics() which could
> return true or false.
That we can't do, because there's a chance that those FDWs already have a
setting named fetch_stats.
> If it returns true it means that the statistics
> was imported successfully, otherwise if it returns false we could
> fallback to table sampling as we already do today. ImportStatistics
> could return false if the foreign server don't have statistics for the
> requested table, even after running ANALYZE if remote_analyze is true.
>
> Is that make sense? Any thoughts?
>
That sounds very similar to the design that was presented in v1.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-07 19:27 Matheus Alcantara <matheusssilv97@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 0 replies; 89+ messages in thread
From: Matheus Alcantara @ 2026-01-07 19:27 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; Matheus Alcantara <matheusssilv97@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Wed Jan 7, 2026 at 4:17 PM -03, Corey Huinker wrote:
>>
>> +
>> I don't think that it's good to make StatisticsAreImportable() routine
>> check if fetch_stats is enabled on foreign server/table options because
>> if so, every fdw implementation would need this same block of code and
>> also fdw implementations may forget or bypass these options which I
>> don't think that it would be a desired behavior. What about move this
>> check to analyze_rel()? Perhaps create a function that just check if the
>> fetch_stats is enabled.
>>
>
> StatisticsAreImportable() is a virtual function whose goal is to determine
> if this specific table supports stats exporting.
>
> postgresStatisticsAreImportable() is the postgres_fdw implementation of
> that virtual function.
>
> Any other FDWs that want to implement stats import will need to invent
> their own tests and configurations to determine if that is possible.
>
Ok, now I understand. I thought that fetch_stats and remote_analyze was
a generally fdw option and not only specific to postgres_fdw. Now I
understand that is up to the fdw implementation decide how this should
be enabled or disabled. Thanks for making it clear now.
>> If it returns true it means that the statistics
>> was imported successfully, otherwise if it returns false we could
>> fallback to table sampling as we already do today. ImportStatistics
>> could return false if the foreign server don't have statistics for the
>> requested table, even after running ANALYZE if remote_analyze is true.
>>
>> Is that make sense? Any thoughts?
>>
>
> That sounds very similar to the design that was presented in v1.
>
Yeah, I think that my suggestion don't make sense, I miss understood the
feature. Sorry about the noise, I'll continue reviewing the v8 patch.
--
Matheus Alcantara
EDB: https://www.enterprisedb.com
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-08 19:42 Matheus Alcantara <matheusssilv97@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
2 siblings, 0 replies; 89+ messages in thread
From: Matheus Alcantara @ 2026-01-08 19:42 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Wed Jan 7, 2026 at 3:04 AM -03, Corey Huinker wrote:
> Anyway, here's v8, incorporating the documentation feedback and Matheus's
> notes.
>
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
I think that it would be good also to have a test case where
remote_analyze is false. The test could manually execute an ANALYZE on
the target table and ensure that an ANALYZE on the foreign table fetch
the statistics correctly.
---
If the table don't have columns it fails to fetch the statistics with
remote_analyze=false even if the target table has statistics:
ERROR: P0002: Failed to import statistics from remote table public.t2, no statistics found.
And if I set remote_analyze=true it fails with the following error:
postgres=# analyze t2_fdw;
ERROR: 08006: could not obtain message string for remote error
CONTEXT: remote SQL command: SELECT DISTINCT ON (s.attname) attname,
s.null_frac, s.avg_width, s.n_distinct, s.most_common_vals,
s.most_common_freqs, s.histogram_bounds, s.correlation,
s.most_common_elems, s.most_common_elem_freqs, s.elem_count_histogram,
s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram
FROM pg_catalog.pg_stats AS s WHERE s.schemaname = $1 AND s.tablename =
$2 AND s.attname = ANY($3::text[]) ORDER BY s.attname, s.inherited DESC
LOCATION: pgfdw_report_internal, connection.c:1037
---
If we try to run ANALYZE on a specific table column that don't exists we
get:
postgres=# analyze t(c);
ERROR: 42703: column "c" of relation "t" does not exist
LOCATION: do_analyze_rel, analyze.c:412
With fetch_stats=false we get the same error:
postgres=# ALTER FOREIGN TABLE t_fdw OPTIONS (add fetch_stats 'false');
ALTER FOREIGN TABLE
postgres=# ANALYZE t_fdw(c);
ERROR: 42703: column "c" of relation "t_fdw" does not exist
But with fetch_stats=true we get a different error:
postgres=# ALTER FOREIGN TABLE t_fdw OPTIONS (drop fetch_stats);
ALTER FOREIGN TABLE
postgres=# ANALYZE t_fdw(c);
ERROR: P0002: Failed to import statistics from remote table public.t, no statistics found.
Should all these errors be consistency?
---
I hope that these comments are more useful now. Thanks.
--
Matheus Alcantara
EDB: https://www.enterprisedb.com
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-09 09:35 Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
2 siblings, 1 reply; 89+ messages in thread
From: Ashutosh Bapat @ 2026-01-09 09:35 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Wed, Jan 7, 2026 at 11:34 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>
> Anyway, here's v8, incorporating the documentation feedback and Matheus's notes.
I went through the patches. I have one question: The column names of
the foreign table on the local server are sorted using qsort, which
uses C sorting. The column names the result obtained from the foreign
server are sorted using ORDER BY clause. If the default collation on
the foreign server is different from the one used by qsort(), the
merge sort in import_fetched_statistics() may fail. Shouldn't these
two sorts use the same collation?
Some minor comments
/* avoid including explain_state.h here */
typedef struct ExplainState ExplainState;
-
unintended line deletion?
fetch_remote_statistics() fetches the statistics twice if the first
attempt fails. I think we need same check after the second attempt as
well. The second attempt should not fail, but I think we need some
safety checks and Assert at least, in case the foreign server
misbehaves.
--
Best Wishes,
Ashutosh Bapat
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-09 16:21 Corey Huinker <corey.huinker@gmail.com>
parent: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 2 replies; 89+ messages in thread
From: Corey Huinker @ 2026-01-09 16:21 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Fri, Jan 9, 2026 at 4:35 AM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
wrote:
> On Wed, Jan 7, 2026 at 11:34 AM Corey Huinker <corey.huinker@gmail.com>
> wrote:
>
> >
> > Anyway, here's v8, incorporating the documentation feedback and
> Matheus's notes.
>
> I went through the patches. I have one question: The column names of
> the foreign table on the local server are sorted using qsort, which
> uses C sorting. The column names the result obtained from the foreign
> server are sorted using ORDER BY clause. If the default collation on
> the foreign server is different from the one used by qsort(), the
> merge sort in import_fetched_statistics() may fail. Shouldn't these
> two sorts use the same collation?
>
I wondered about that, but somehow thought that because they're of type
pg_catalog.name rather than text/varchar that they weren't subject to
collation settings. We definitely should explicitly sort by C collation
regardless.
>
> Some minor comments
>
> /* avoid including explain_state.h here */
> typedef struct ExplainState ExplainState;
> -
>
> unintended line deletion?
>
Yeah, must have been.
>
> fetch_remote_statistics() fetches the statistics twice if the first
> attempt fails. I think we need same check after the second attempt as
> well. The second attempt should not fail, but I think we need some
> safety checks and Assert at least, in case the foreign server
> misbehaves.
>
I think the only test *not* done on re-fetch is checking the relkind of the
relation, are you speaking of another check? It's really no big deal to do
that one again, but I made the distinction early on in the coding, and in
retrospect there are relatively few checks we'd consider skipping on the
second pass, so maybe it's not worth the distinction.
Since you're joining the thread, we have an outstanding debate about what
the desired basic workflow should be, and I think we should get some
consensus before we paint ourselves into a corner.
1. The Simplest Possible Model
* There is no remote_analyze functionality
* fetch_stats defaults to false
* Failure to fetch stats results in a failure, no failover to sampling.
2. Simplest Model, but with Failover
* Same as #1, but if we aren't satisfied with the stats we get from the
remote, we issue a WARNING, then fall back to sampling, trusting that the
user will eventually turn off fetch_stats on tables where it isn't working.
3. Analyze and Retry
* Same as #2, but we add remote_analyze option (default false).
* If the first attempt fails AND remote_analyze is set on, then we send the
remote analyze, then retry. Only if that fails do we fall back to sampling.
4. Analyze and Retry, Optimistic
* Same as #3, but fetch_stats defaults to ON, because the worst case
scenario is that we issue a few queries that return 0-1 rows before giving
up and just sampling.
* This is the option that Nathan advocated for in our initial conversation
about the topic, and I found it quite persuasive at the time, but he's been
slammed with other stuff and hasn't been able to add to this thread.
5. Fetch With Retry Or Sample, Optimisitc
* If fetch_stats is on, AND the remote table is seemingly capable of
holding stats, attempt to fetch them, possibly retrying after ANALYZE
depending on remote_analyze.
* If fetching stats failed, just error, as a way to prime the user into
changing the table's setting.
* This is what's currently implemented, and it's not quite what anyone
wants. Defaulting fetch_stats to true doesn't seem great, but not
defaulting it to true will reduce adoption of this feature.
6. Fetch With Retry Or Sample, Pessimistic
* Same as #5, but with fetch_stats = false.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-14 19:41 Corey Huinker <corey.huinker@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 0 replies; 89+ messages in thread
From: Corey Huinker @ 2026-01-14 19:41 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> Since you're joining the thread, we have an outstanding debate about what
> the desired basic workflow should be, and I think we should get some
> consensus before we paint ourselves into a corner.
>
> 1. The Simplest Possible Model
>
> * There is no remote_analyze functionality
> * fetch_stats defaults to false
> * Failure to fetch stats results in a failure, no failover to sampling.
>
> 2. Simplest Model, but with Failover
>
> * Same as #1, but if we aren't satisfied with the stats we get from the
> remote, we issue a WARNING, then fall back to sampling, trusting that the
> user will eventually turn off fetch_stats on tables where it isn't working.
>
> 3. Analyze and Retry
>
> * Same as #2, but we add remote_analyze option (default false).
> * If the first attempt fails AND remote_analyze is set on, then we send
> the remote analyze, then retry. Only if that fails do we fall back to
> sampling.
>
> 4. Analyze and Retry, Optimistic
>
> * Same as #3, but fetch_stats defaults to ON, because the worst case
> scenario is that we issue a few queries that return 0-1 rows before giving
> up and just sampling.
> * This is the option that Nathan advocated for in our initial conversation
> about the topic, and I found it quite persuasive at the time, but he's been
> slammed with other stuff and hasn't been able to add to this thread.
>
> 5. Fetch With Retry Or Sample, Optimisitc
>
> * If fetch_stats is on, AND the remote table is seemingly capable of
> holding stats, attempt to fetch them, possibly retrying after ANALYZE
> depending on remote_analyze.
> * If fetching stats failed, just error, as a way to prime the user into
> changing the table's setting.
> * This is what's currently implemented, and it's not quite what anyone
> wants. Defaulting fetch_stats to true doesn't seem great, but not
> defaulting it to true will reduce adoption of this feature.
>
> 6. Fetch With Retry Or Sample, Pessimistic
>
> * Same as #5, but with fetch_stats = false.
>
Rebased after adding the COLLATE argument to the ORDER-BY statements.
Attachments:
v9-0001-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 42.0K) download
From 212743a9fdb919a0c948c1eeb0c63448791af112 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 7 Aug 2025 23:58:38 -0400
Subject: [PATCH v9] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via two new options, fetch_stats and remote_analyze,
both are available at the server level and table level. If fetch_stats
is true, then the ANALYZE command will attempt to fetch statistics
from the remote table and import those statistics locally.
If remote_analyze is true, and if the first attempt to fetch remote
statistics found no attribute statistics, then an attempt will be made
to ANALYZE the remote table before a second and final attempt to fetch
remote statistics.
If the attempts to fetch statistics result in some analyzed columns
missing imported statistics, then the ANALYZE will raise an error.
This operation will only work on remote relations that can have stored
statistics: tables, partitioned tables, and materialized views. If the
remote relation is a view then remote fetching/analyzing is just wasted
effort and the user is better off setting fetch_stats to false for that
table.
The default for fetch_stats is, for now, true at both server and table
level. The default for remote_analyze is false at both the server
and table level. In both cases, setting a value at the table level
will override the corresponding server-level setting.
---
src/include/foreign/fdwapi.h | 8 +
src/backend/commands/analyze.c | 52 +-
doc/src/sgml/postgres-fdw.sgml | 38 +-
.../postgres_fdw/expected/postgres_fdw.out | 52 +-
contrib/postgres_fdw/option.c | 10 +
contrib/postgres_fdw/postgres_fdw.c | 797 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 46 +-
7 files changed, 983 insertions(+), 20 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..a0b6113a097 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef void (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +261,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index a483424152c..e69288968fc 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -113,6 +113,8 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool import_stats = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -195,26 +197,33 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ import_stats = true;
+ else
{
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
}
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
@@ -248,9 +257,18 @@ analyze_rel(Oid relid, RangeVar *relation,
/*
* Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * tables, which don't contain any rows. For foreign tables, if they
+ * support importing statistics, do that instead of the non-recursive
+ * ANALYZE.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+ else if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 9b032fbf675..05928835355 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,42 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</relation> and
+ <function>pg_restore_attribute_stats</relation>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ is only meaningful if the foreign table has
+ <literal>fetch_stats</literal> enabled at either the server or table
+ level.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 6066510c7c0..1f7ebeda82c 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4551,7 +4552,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11462,6 +11464,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p2
+ANALYZE async_pt;
+ERROR: Failed to import statistics from remote table public.base_tbl2, no statistics found.
+-- Turn off fetch_stats at the table level.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11568,6 +11575,11 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+ERROR: Failed to import statistics from remote table public.base_tbl3, no statistics found.
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
@@ -12665,6 +12677,44 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..2941ecbfb87 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,8 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +280,14 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 3572689e33b..c936ecfc0f1 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -22,6 +22,8 @@
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -48,6 +50,7 @@
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
+#include "utils/syscache.h"
PG_MODULE_MAGIC_EXT(
.name = "postgres_fdw",
@@ -317,6 +320,20 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ char remote_attname[NAMEDATALEN];
+ AttrNumber local_attnum;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -402,6 +419,10 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresStatisticsAreImportable(Relation relation);
+static void postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +567,86 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns {
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_NUM_FIELDS
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+ "SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+ "SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, s.most_common_elems, "
+ "s.most_common_elem_freqs, s.elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+ "SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+static const char *attstats_query_default =
+ "SELECT s.attname, s.null_frac, s.avg_width, "
+ "s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+ "s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+ "NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+ "NULL AS range_length_histogram, NULL AS range_empty_frac, "
+ "NULL AS range_bounds_histogram "
+ "FROM pg_catalog.pg_stats AS s "
+ "WHERE s.schemaname = $1 AND s.tablename = $2 "
+ "AND s.attname = ANY($3::text[]) "
+ "ORDER BY s.attname COLLATE \"C\"";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns {
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS
+};
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +696,8 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->StatisticsAreImportable = postgresStatisticsAreImportable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5038,700 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Process optional argument.
+ *
+ * Cannot be the first argument in the SQL function call.
+ *
+ * It is safe to presume that argname and argtype are quote-safe.
+ *
+ * Argument values can potentially be quite large, so free the quoted string
+ * after use.
+ */
+static void
+append_optional(StringInfo str, PGresult *res, int row, int field,
+ const char *argname, const char *argtype)
+{
+ if (!PQgetisnull(res, row, field))
+ {
+ /* Argument values can be quite large, so free after use */
+ char *argval_l = quote_literal_cstr(PQgetvalue(res, row, field));
+
+ appendStringInfo(str, ",\n\t'%s', %s::%s", argname, argval_l, argtype);
+
+ pfree(argval_l);
+ }
+}
+
+
+/*
+ * Generate a pg_restore_relation_stats command.
+ */
+static char *
+restore_relation_stats_sql(PGresult *res, const char *schemaname,
+ const char *relname, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s",
+ server_version_num, schemaname_l, relname_l);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, 0, RELSTATS_RELPAGES, "relpages", "integer");
+ append_optional(&sql, res, 0, RELSTATS_RELTUPLES, "reltuples", "real");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Generate a pg_restore_attribute_stats command.
+ */
+static char *
+restore_attribute_stats_sql(PGresult *res, int row,
+ const char *schemaname, const char *relname,
+ const AttrNumber attnum, const int server_version_num)
+{
+ StringInfoData sql;
+
+ char *schemaname_l = quote_literal_cstr(schemaname);
+ char *relname_l = quote_literal_cstr(relname);
+
+ initStringInfo(&sql);
+ appendStringInfo(&sql, "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', %d::integer,\n"
+ "\t'schemaname', %s,\n"
+ "\t'relname', %s,\n"
+ "\t'attnum', %d::smallint,\n"
+ "\t'inherited', false::boolean",
+ server_version_num, schemaname_l, relname_l, attnum);
+
+ pfree(schemaname_l);
+ pfree(relname_l);
+
+ append_optional(&sql, res, row, ATTSTATS_NULL_FRAC, "null_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_AVG_WIDTH, "avg_width", "integer");
+ append_optional(&sql, res, row, ATTSTATS_N_DISTINCT, "n_distinct", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_VALS, "most_common_vals", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_FREQS, "most_common_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_HISTOGRAM_BOUNDS, "histogram_bounds", "text");
+ append_optional(&sql, res, row, ATTSTATS_CORRELATION, "correlation", "real");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEMS, "most_common_elems", "text");
+ append_optional(&sql, res, row, ATTSTATS_MOST_COMMON_ELEM_FREQS, "most_common_elem_freqs", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_ELEM_COUNT_HISTOGRAM, "elem_count_histogram", "real[]");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_LENGTH_HISTOGRAM, "range_length_histogram", "text");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_EMPTY_FRAC, "range_empty_frac", "real");
+ append_optional(&sql, res, row, ATTSTATS_RANGE_BOUNDS_HISTOGRAM, "range_bounds_histogram", "text");
+
+ appendStringInfoChar(&sql, ')');
+
+ return sql.data;
+}
+
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static void
+import_fetched_statistics(const char *schemaname, const char *relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping *remattrmap,
+ RemoteStatsResults *remstats)
+{
+ PGresult *res = remstats->att;
+ int spirc;
+ char *relimport_sql;
+ int mapidx = 0;
+
+ Assert(natts > 0);
+
+ SPI_connect();
+
+ /*
+ * Match result set rows to local attnums.
+ *
+ * Every row of the result should be an attribute that we specifically
+ * filtered for, so every row should have at least one match in the
+ * RemoteAttributeMapping, which is also ordered by attname, so we only
+ * need to walk that array once.
+ *
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ for (int i = 0; i < PQntuples(remstats->att); i++)
+ {
+ char *remote_attname;
+ char *attimport_sql;
+ bool match_found = false;
+ int cmp = 0;
+
+ if (PQgetisnull(res, i, ATTSTATS_ATTNAME))
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Remote statistics returned a row with NULL attribute name"));
+
+ remote_attname = PQgetvalue(res, i, ATTSTATS_ATTNAME);
+
+ /*
+ * Handle a series of matching elements in the mapping.
+ *
+ * We exit this loop in the following ways:
+ *
+ * 1. Having found at least match and exhausting the list. We're done.
+ * 2. Having found at least match and ending on a <, advance.
+ * 3. Having found at least match and ending on a >, bad sort.
+ * 4. No match, list exhausted.
+ * 5. No match, <.
+ * 6. No match, >.
+ *
+ */
+ for (; mapidx < natts; mapidx++)
+ {
+ cmp = strcmp(remote_attname, remattrmap[mapidx].remote_attname);
+
+ /* Stop scanning on the first non-match */
+ if (cmp != 0)
+ break;
+
+ match_found = true;
+
+ attimport_sql = restore_attribute_stats_sql(res, i,
+ schemaname, relname,
+ remattrmap[mapidx].local_attnum,
+ server_version_num);
+
+ spirc = SPI_execute(attimport_sql, false, 1);
+ pfree(attimport_sql);
+
+ /*
+ * It takes a lot to make a restore command fail outright, so any
+ * actual failure is a sign that the statistics are seriously
+ * malformed, and we should give up on importing stats for this
+ * table.
+ */
+ if (spirc != SPI_OK_SELECT)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Attribute statistics import failed %s",
+ attimport_sql));
+ }
+
+ /* We found a match, move onto the next result. */
+ if (match_found)
+ continue;
+
+ /*
+ * If no match and we ended on a <, then the mapidx will never find a
+ * match, so stop now and let the cleanup report the error.
+ */
+ if (cmp > 0)
+ break;
+
+ /*
+ * Otherwise this result found no matching mapidx, which should only
+ * happen if the results are out of sort or the wrong query was
+ * executed.
+ */
+ if (cmp < 0)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+ }
+
+ /* Look for a mapidx with no possible matching result */
+ if (mapidx < natts)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+
+ /*
+ * Import relation stats.
+ */
+ relimport_sql = restore_relation_stats_sql(remstats->rel, schemaname,
+ relname, server_version_num);
+
+ spirc = SPI_execute(relimport_sql, false, 1);
+
+ /*
+ * It takes a lot to make a restore command fail outright, so any actual
+ * failure is a sign that the statistics are seriously malformed, and
+ * we should give up on importing stats for this table.
+ */
+ if (spirc != SPI_OK_SELECT)
+ ereport(ERROR,
+ errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
+ errmsg("Relation statistics import failed: %s.",
+ relimport_sql));
+
+ pfree(relimport_sql);
+ SPI_finish();
+}
+
+/*
+ * Analyze a remote table.
+ */
+static void
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s",
+ quote_qualified_identifier(remote_schemaname, remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL ||
+ PQresultStatus(res) != PGRES_COMMAND_OK)
+ pgfdw_report_error(res, conn, buf.data);
+
+ PQclear(res);
+ pfree(buf.data);
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ * Verify that the result is of the proper shape.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname)
+{
+ const char *params[2] = { remote_schemaname, remote_relname };
+
+ /*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case).
+ *
+ * We can ignore this change, because if the remote table wasn't analyzed,
+ * then it would have no attribute stats, and thus we wouldn't have stats that
+ * we would try to import. So we can take the reltuples value as-is.
+ */
+ const char *sql = "SELECT c.relkind, c.relpages, c.reltuples "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n "
+ "ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+ PGresult *res;
+
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS
+ || PQgetisnull(res, 0, RELSTATS_RELKIND))
+ pgfdw_report_error(res, conn, sql);
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ * Verify that the result is of the proper shape.
+ * Note that we do not verify the row count.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list, bool is_retry)
+{
+ const char *params[3] = { remote_schemaname, remote_relname, column_list };
+ int version = PQserverVersion(conn);
+ const char *sql;
+ PGresult *res;
+
+ if (version >= 170000)
+ sql = attstats_query_17;
+ else if (version >= 90200)
+ sql = attstats_query_9_2;
+ else if (version >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ pgfdw_report_error(res, conn, sql);
+
+ /* Getting nothing on the second try is a failure */
+ if (is_retry && PQntuples(res) == 0)
+ pgfdw_report_error(res, conn, sql);
+
+ return res;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static void
+fetch_remote_statistics(PGconn *conn,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping *remattrmap,
+ bool remote_analyze, RemoteStatsResults *remstats)
+{
+ StringInfoData column_list;
+
+ char relkind;
+
+ remstats->rel = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously can't
+ * support a foreign table.
+ */
+ relkind = *PQgetvalue(remstats->rel, 0, RELSTATS_RELKIND);
+
+ switch(relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Remote table %s does not support statistics.",
+ quote_qualified_identifier(remote_schemaname,
+ remote_relname)));
+ return;
+ }
+
+ initStringInfo(&column_list);
+ appendStringInfoChar(&column_list, '{');
+ for (int i = 0; i < natts; i++)
+ {
+ if (i > 0)
+ appendStringInfoChar(&column_list, ',');
+ appendStringInfoString(&column_list,
+ quote_identifier(remattrmap[i].remote_attname));
+ }
+ appendStringInfoChar(&column_list, '}');
+
+ /* See if it actually has any attribute stats. */
+ remstats->att = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list.data, false);
+
+ /*
+ * If we got attribute statistics results, then we are done with fetching.
+ */
+ if (PQntuples(remstats->att) > 0)
+ return;
+
+ /*
+ * Clear off any existing fetched statistics, if any. If the analyze works
+ * then they we want to fetch the new ones.
+ */
+ PQclear(remstats->att);
+ PQclear(remstats->rel);
+ remstats->att = NULL;
+ remstats->rel = NULL;
+
+ /*
+ * If remote_analyze is enabled, then we will try to analyze the table and
+ * then try again.
+ */
+ if (remote_analyze)
+ analyze_remote_table(conn, remote_schemaname, remote_relname);
+ else
+ ereport(ERROR,
+ errcode(ERRCODE_NO_DATA_FOUND),
+ errmsg("Failed to import statistics from remote table %s, "
+ "no statistics found.",
+ quote_qualified_identifier(remote_schemaname,
+ remote_relname)));
+
+ /*
+ * Remote ANALYZE complete, so re-fetch attribute stats query.
+ */
+ remstats->att = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list.data, true);
+
+ /* Re-fetch basic relation stats, as they have been updated. */
+ remstats->rel = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ pfree(column_list.data);
+}
+
+static bool
+postgresStatisticsAreImportable(Relation relation)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ ListCell *lc;
+ bool fetch_stats = true;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ return fetch_stats;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Fetch attstattarget from a pg_attribute tuple.
+ */
+static int16
+get_attstattarget(Relation relation, AttrNumber attnum)
+{
+ HeapTuple atttuple;
+ bool isnull;
+ Datum dat;
+ int16 attstattarget;
+ Oid relid = RelationGetRelid(relation);
+
+ atttuple = SearchSysCache2(ATTNUM,
+ ObjectIdGetDatum(relid),
+ Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, relid);
+ dat = SysCacheGetAttr(ATTNUM, atttuple,
+ Anum_pg_attribute_attstattarget,
+ &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ return attstattarget;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static void
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+
+ ForeignTable *table;
+ ForeignServer *server;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ bool remote_analyze = false;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int natts = 0;
+
+ RemoteAttributeMapping *remattrmap;
+
+ RemoteStatsResults remstats = { .rel = NULL, .att = NULL };
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
+ /*
+ * Assume the relation/schema names are the same as the local name unless
+ * the options tell us otherwise.
+ */
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ /*
+ * Build attnum/remote-attname list.
+ *
+ */
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *attname;
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+
+ /* Ignore dropped columns. */
+ if (attr->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (attr->attgenerated)
+ continue;
+
+ attname = NameStr(attr->attname);
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ attnum = attr->attnum;
+
+ /* Ignore if attstatarget is 0 */
+ if (get_attstattarget(relation,attnum) == 0)
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_colname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].remote_attname, remote_colname, NAMEDATALEN);
+ natts++;
+ }
+
+ /* Sort mapping by remote attribute name */
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ fetch_remote_statistics(conn, remote_schemaname, remote_relname,
+ server_version_num, natts, remattrmap,
+ remote_analyze, &remstats);
+
+ ReleaseConnection(conn);
+
+ Assert(remstats.rel != NULL);
+ Assert(remstats.att != NULL);
+ import_fetched_statistics(schemaname, relname, server_version_num, natts,
+ remattrmap, &remstats);
+
+ pfree(remattrmap);
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+}
+
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 4f7ab2ed0ac..c527a1fbb15 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1286,7 +1287,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3903,6 +3905,10 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the table level.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3940,6 +3946,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
@@ -4387,6 +4397,40 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
base-commit: 556c92a68972818b24d31d060175ae8131d3297b
--
2.52.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-15 13:47 Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Ashutosh Bapat @ 2026-01-15 13:47 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Fri, Jan 9, 2026 at 9:52 PM Corey Huinker <corey.huinker@gmail.com> wrote:
>
> On Fri, Jan 9, 2026 at 4:35 AM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com> wrote:
>>
>> On Wed, Jan 7, 2026 at 11:34 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>>
>> >
>> > Anyway, here's v8, incorporating the documentation feedback and Matheus's notes.
>>
>> I went through the patches. I have one question: The column names of
>> the foreign table on the local server are sorted using qsort, which
>> uses C sorting. The column names the result obtained from the foreign
>> server are sorted using ORDER BY clause. If the default collation on
>> the foreign server is different from the one used by qsort(), the
>> merge sort in import_fetched_statistics() may fail. Shouldn't these
>> two sorts use the same collation?
>
>
> I wondered about that, but somehow thought that because they're of type pg_catalog.name rather than text/varchar that they weren't subject to collation settings. We definitely should explicitly sort by C collation regardless.
>
>>
>>
>> Some minor comments
>>
>> /* avoid including explain_state.h here */
>> typedef struct ExplainState ExplainState;
>> -
>>
>> unintended line deletion?
>
>
> Yeah, must have been.
>
>
>>
>>
>> fetch_remote_statistics() fetches the statistics twice if the first
>> attempt fails. I think we need same check after the second attempt as
>> well. The second attempt should not fail, but I think we need some
>> safety checks and Assert at least, in case the foreign server
>> misbehaves.
>
>
> I think the only test *not* done on re-fetch is checking the relkind of the relation, are you speaking of another check? It's really no big deal to do that one again, but I made the distinction early on in the coding, and in retrospect there are relatively few checks we'd consider skipping on the second pass, so maybe it's not worth the distinction.
>
> Since you're joining the thread, we have an outstanding debate about what the desired basic workflow should be, and I think we should get some consensus before we paint ourselves into a corner.
>
> 1. The Simplest Possible Model
>
> * There is no remote_analyze functionality
> * fetch_stats defaults to false
> * Failure to fetch stats results in a failure, no failover to sampling.
>
Instead of fetch_stats, I would prefer has_stats. But if majority is
on fetch_stats, I am ok with it.
> 2. Simplest Model, but with Failover
>
> * Same as #1, but if we aren't satisfied with the stats we get from the remote, we issue a WARNING, then fall back to sampling, trusting that the user will eventually turn off fetch_stats on tables where it isn't working.
>
> 3. Analyze and Retry
>
> * Same as #2, but we add remote_analyze option (default false).
> * If the first attempt fails AND remote_analyze is set on, then we send the remote analyze, then retry. Only if that fails do we fall back to sampling.
>
> 4. Analyze and Retry, Optimistic
>
> * Same as #3, but fetch_stats defaults to ON, because the worst case scenario is that we issue a few queries that return 0-1 rows before giving up and just sampling.
> * This is the option that Nathan advocated for in our initial conversation about the topic, and I found it quite persuasive at the time, but he's been slammed with other stuff and hasn't been able to add to this thread.
>
> 5. Fetch With Retry Or Sample, Optimisitc
>
> * If fetch_stats is on, AND the remote table is seemingly capable of holding stats, attempt to fetch them, possibly retrying after ANALYZE depending on remote_analyze.
> * If fetching stats failed, just error, as a way to prime the user into changing the table's setting.
> * This is what's currently implemented, and it's not quite what anyone wants. Defaulting fetch_stats to true doesn't seem great, but not defaulting it to true will reduce adoption of this feature.
>
> 6. Fetch With Retry Or Sample, Pessimistic
>
> * Same as #5, but with fetch_stats = false.
I have no strong opinion about whether fetch_stats should be ON or off
by default. In my simple view, the remote relation that the foreign
table points is usually a regular table or a partitioned table. So
default ON makes sense to me. But there's a possibility that in an
OLAP system most of the foreign objects are views exposing only some
data and not all. I think defaulting to off is backward compatible and
requires cautious opt-in. Or else suddenly all ANALYZE on foreign
server will be costly since they are running a couple queries before
falling back to sampling.
Why do we need remote_analyze as a flag? I might have missed some
conversation which led to including this flag. We fetch relkind, so we
know whether the object on the foreign server supports statistics or
not. If it supports statistics, we run ANALYZE automatically. I mean
the user wants us to ANALYZE the foreign table and has also indicated
that the remote object is capable of storing stats. We should document
the fact that we analyze if we do not find existing statistics. Why
would users want to disable running ANALYZE? One possibility is they
don't want to disturb query plans because of suddenly changing
statistics. But then they will need to switch auto-analysis off. So
maybe there is a way to know when it's not acceptable to run ANALYZE
on the remote server. I feel this flag will put another burden on the
user who already has to set so many flags in postgres_fdw. That is
especially true, when the flag is useful only the first time when the
remote object doesn't have stats - usually there will be stats. If at
all we have to introduce remote_analyze, let it default to the value
of fetch_stats.
If both - importing statistics and fallback analysis - fail, I think
we should resort to sampling - since the user has asked for an ANALYZE
table and sampling will achieve that. As you said, giving warnings at
every failure will nudge the user to set their options correctly.
Does that make sense?
--
Best Wishes,
Ashutosh Bapat
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-15 17:57 Corey Huinker <corey.huinker@gmail.com>
parent: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-01-15 17:57 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> Instead of fetch_stats, I would prefer has_stats. But if majority is
> on fetch_stats, I am ok with it.
>
I don't think there are any strong feelings about the names of the
parameters, only their meanings and their defaults.
> I have no strong opinion about whether fetch_stats should be ON or off
> by default. In my simple view, the remote relation that the foreign
> table points is usually a regular table or a partitioned table. So
> default ON makes sense to me. But there's a possibility that in an
> OLAP system most of the foreign objects are views exposing only some
> data and not all. I think defaulting to off is backward compatible and
> requires cautious opt-in.
If the remote object is a postgres view, we're never going to get stats, so
default of fetch_stats = on coupled with automatic failover to regular
sampling would result in some trivial network traffic and some
NOTICE/WARNING log messages until the owner sets fetch_stats = off on the
local table.
> Or else suddenly all ANALYZE on foreign
> server will be costly since they are running a couple queries before
> falling back to sampling.
>
In all scenarios, the remote_analyze setting defaults to false, and the
remote database should continue to have stats going forward from that
point. I can see value in having a more insistent NOTICE/WARNING message
for situations where a remote ANALYZE fails or the table continues to have
inadequate stats after the remote ANALYZE.
> Why do we need remote_analyze as a flag? I might have missed some
> conversation which led to including this flag. We fetch relkind, so we
> know whether the object on the foreign server supports statistics or
> not.
Well, sorta. We know the database on the other end talks libpq and has the
table pg_class. There are more than a few forks, Redshift and Vertica come
to mind, where this check will succeed, but the design diverges after that
and doesn't have pg_statistic or similar. We have to do deeper checks of
the remote system (matching pg_statistic rows to all the va_cols we expect,
etc) to verify that we _probably_ have good stats, but we don't actually
truly know if the stats will actually be there until we fetch and import
them, and at that point we're done. And that is part of my discomfort with
StatisticsAreImportable in that it can identify some of the cases where we
_can't_ import stats, but to identify whether we _can_ import the stats we
have just moved all of the functionality of ImportStatistics into
StatisticsAreImportable.
> If it supports statistics, we run ANALYZE automatically. I mean
> the user wants us to ANALYZE the foreign table and has also indicated
> that the remote object is capable of storing stats. We should document
> the fact that we analyze if we do not find existing statistics. Why
> would users want to disable running ANALYZE? One possibility is they
> don't want to disturb query plans because of suddenly changing
> statistics. But then they will need to switch auto-analysis off. So
> maybe there is a way to know when it's not acceptable to run ANALYZE
> on the remote server. I feel this flag will put another burden on the
> user who already has to set so many flags in postgres_fdw. That is
> especially true, when the flag is useful only the first time when the
> remote object doesn't have stats - usually there will be stats. If at
> all we have to introduce remote_analyze, let it default to the value
> of fetch_stats.
>
I may have answered this question in the above responses, but
remote_analyze does not default to ON, nor do I envision making it the
default. I think the primary purpose for the flag is situations where the
remote database is often "swapped out" with one that has a fresher set of
the data (via DNS swapping, port swapping, etc) and the new database was
put online before vacuum got around to those tables. I would agree that
running the remote analyze is pulling a big lever, hence only trying it if
we failed to find sufficient existing stats.
> If both - importing statistics and fallback analysis - fail, I think
> we should resort to sampling - since the user has asked for an ANALYZE
> table and sampling will achieve that. As you said, giving warnings at
> every failure will nudge the user to set their options correctly.
>
Sorry if my description was confusing, I should have been more clear that
"fallback analysis" is the regular row sampling. In scenario #4 (the one I
advocate and Nathan advocate[d?]), the decision tree is this:
1. if fetch_stats = off OR StatisticsAreImportable = false THEN
resort_to_regular_row_sampling and exit normally.
2. attempt_to_fetch_remote_stats. If we fetched and imported remote stats,
THEN exit normally.
3. if remote_analyze = false THEN resort_to_regular_row_sampling and exit
normally.
4. send_remote_analyze_command, if that fails then THEN WARN and
resort_to_regular_row_sampling and exit normally.
5. (step #2, again, essentially) attempt_to_fetch_remote_stats. If we
fetched and imported remote stats, THEN exit normally.
6. WARN user of potentially intractable
problem, resort_to_regular_row_sampling and exit normally.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-16 07:10 Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Ashutosh Bapat @ 2026-01-16 07:10 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Thu, Jan 15, 2026 at 11:27 PM Corey Huinker <corey.huinker@gmail.com> wrote:
>
>>
>> Or else suddenly all ANALYZE on foreign
>> server will be costly since they are running a couple queries before
>> falling back to sampling.
>
>
> In all scenarios, the remote_analyze setting defaults to false, and the remote database should continue to have stats going forward from that point. I can see value in having a more insistent NOTICE/WARNING message for situations where a remote ANALYZE fails or the table continues to have inadequate stats after the remote ANALYZE.
>
>>
>> Why do we need remote_analyze as a flag? I might have missed some
>> conversation which led to including this flag. We fetch relkind, so we
>> know whether the object on the foreign server supports statistics or
>> not.
>
>
> Well, sorta. We know the database on the other end talks libpq and has the table pg_class. There are more than a few forks, Redshift and Vertica come to mind, where this check will succeed, but the design diverges after that and doesn't have pg_statistic or similar. We have to do deeper checks of the remote system (matching pg_statistic rows to all the va_cols we expect, etc) to verify that we _probably_ have good stats, but we don't actually truly know if the stats will actually be there until we fetch and import them, and at that point we're done. And that is part of my discomfort with StatisticsAreImportable in that it can identify some of the cases where we _can't_ import stats, but to identify whether we _can_ import the stats we have just moved all of the functionality of ImportStatistics into StatisticsAreImportable.
>
>>
>> If it supports statistics, we run ANALYZE automatically. I mean
>> the user wants us to ANALYZE the foreign table and has also indicated
>> that the remote object is capable of storing stats. We should document
>> the fact that we analyze if we do not find existing statistics. Why
>> would users want to disable running ANALYZE? One possibility is they
>> don't want to disturb query plans because of suddenly changing
>> statistics. But then they will need to switch auto-analysis off. So
>> maybe there is a way to know when it's not acceptable to run ANALYZE
>> on the remote server. I feel this flag will put another burden on the
>> user who already has to set so many flags in postgres_fdw. That is
>> especially true, when the flag is useful only the first time when the
>> remote object doesn't have stats - usually there will be stats. If at
>> all we have to introduce remote_analyze, let it default to the value
>> of fetch_stats.
>
>
> I may have answered this question in the above responses, but remote_analyze does not default to ON, nor do I envision making it the default. I think the primary purpose for the flag is situations where the remote database is often "swapped out" with one that has a fresher set of the data (via DNS swapping, port swapping, etc) and the new database was put online before vacuum got around to those tables. I would agree that running the remote analyze is pulling a big lever, hence only trying it if we failed to find sufficient existing stats.
>
Assuming following conditions to be true
1. object on the other side usually has statistics
2. it didn't when we queried.
The reason for that situation is that the object was not analyzed
before for the reasons you mention. Then why not just run ANALYZE and
instantiate the statistics. That will happen only rarely. Why do we
need a table and server option to control that behaviour? Maybe you
have already explained and I am not able to understand your answer.
Sorry.
--
Best Wishes,
Ashutosh Bapat
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-16 16:49 Corey Huinker <corey.huinker@gmail.com>
parent: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-01-16 16:49 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> Assuming following conditions to be true
> 1. object on the other side usually has statistics
> 2. it didn't when we queried.
>
> The reason for that situation is that the object was not analyzed
> before for the reasons you mention. Then why not just run ANALYZE and
> instantiate the statistics. That will happen only rarely.
I agree.
> Why do we
> need a table and server option to control that behaviour? Maybe you
> have already explained and I am not able to understand your answer.
>
I probably didn't explain it, but one reason for having the option is that
the role used to connect to the remote database might not have the
permissions to analyze tables in general, or that table in particular.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-18 02:53 Corey Huinker <corey.huinker@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 2 replies; 89+ messages in thread
From: Corey Huinker @ 2026-01-18 02:53 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Fri, Jan 16, 2026 at 11:49 AM Corey Huinker <corey.huinker@gmail.com>
wrote:
> Assuming following conditions to be true
>> 1. object on the other side usually has statistics
>> 2. it didn't when we queried.
>>
>> The reason for that situation is that the object was not analyzed
>> before for the reasons you mention. Then why not just run ANALYZE and
>> instantiate the statistics. That will happen only rarely.
>
>
> I agree.
>
>
>> Why do we
>> need a table and server option to control that behaviour? Maybe you
>> have already explained and I am not able to understand your answer.
>>
>
> I probably didn't explain it, but one reason for having the option is that
> the role used to connect to the remote database might not have the
> permissions to analyze tables in general, or that table in particular.
>
Changes in this release, aside from rebasing:
- The generic analyze and fdw.h changes are in their own patch (0001) that
ignores contrib/postgres_fdw entirely.
- The option for remote_analyze has been moved to its own patch (0003).
- The errors raised are now warnings, to ensure that we can always fall
back to row sampling.
- All local attributes with attstatarget > 0 must get matching remote
statistics or the import is considered a failure.
- The pg_restore_attribute_stats() call has been turned into a prepared
statement, for clarity and some minor parsing savings.
- The calls to pg_restore_relation_stats() are parameterized, but not
prepared as this is rarely called more than once.
- postgresStatisticsAreImportable will now disqualify a table if has
extended statistics objects, because we can't compute those without a row
sample.
Attachments: download all (3 files, .tar.gz)
v10-0001-Add-FDW-functions-for-importing-optimizer-statis.patch (text/x-patch, 5.0K) download
From 7b695148065be8d3456ebb0af92cf3f93fc6ae10 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 16:39:45 -0500
Subject: [PATCH v10 1/3] Add FDW functions for importing optimizer statistics.
Add the the function StatisticsAreImportable which is used as a
lightweight preliminary scan to determine if the remote table could
potentially have statistics that could be imported instead of fetching a
row sample from the remote table, which can be expensive.
Also add the function ImportStatistics which attempts to actually fetch
those statistics from the remote server, and if successful import them
into the local statistics catalog.
---
src/include/foreign/fdwapi.h | 8 ++++
src/backend/commands/analyze.c | 68 ++++++++++++++++++++++++----------
2 files changed, 56 insertions(+), 20 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..59beeae4f45 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef bool (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +261,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index a483424152c..c84367461fb 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -113,6 +113,9 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool can_import_stats = false;
+ bool stats_imported = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -195,27 +198,16 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
- {
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
- }
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ can_import_stats = true;
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
{
@@ -247,10 +239,46 @@ analyze_rel(Oid relid, RangeVar *relation,
PROGRESS_ANALYZE_STARTED_BY_MANUAL);
/*
- * Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * If this table can import statistics, attempt to do so.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (can_import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ stats_imported = fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+
+ /*
+ * Foreign tables that were not able to import stats will resort to
+ * regular sampling.
+ */
+ if ((onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
+ && !stats_imported)
+ {
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
+ }
+
+ /*
+ * Do the normal non-recursive ANALYZE. We can skip this for partitioned
+ * tables and foreign tables that successfully imported statistics.
+ */
+ if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ && !stats_imported)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
base-commit: 6831cd9e3b082d7b830c3196742dd49e3540c49b
--
2.52.0
v10-0002-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 36.1K) download
From 7de88b6864124f52a497cf123b2b23836401b985 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:06:05 -0500
Subject: [PATCH v10 2/3] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via a new option, fetch_stats, which is available at the
server level and table level. The global default is true, but this can
be overriden by at the server level, which in turn can be overridden at
the table level.
If fetch_stats is true, and the remote table is an actual table or
materialized view that can hold statistics, and the local table does not
have any extended statistics objects built upon it, then the remote
database will first be queried for relation statistics and attribute
statistics similar to the method used in pg_dump.
If there are remote statistics for all of the columns in the local
table, then those statistics will be imported using
pg_restore_relation_statistics and pg_restore_attribute_statistics
functions similar to the way pg_restore uses them.
If fetch_stats is false, or if the fetched statistics were missing or
otherwise inadequate, then the ANALYZE operation will issue a WARNING
and then fall back to regular table sampling to generate local
statistics.
---
doc/src/sgml/postgres-fdw.sgml | 21 +-
.../postgres_fdw/expected/postgres_fdw.out | 15 +-
contrib/postgres_fdw/option.c | 5 +
contrib/postgres_fdw/postgres_fdw.c | 912 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 13 +-
5 files changed, 963 insertions(+), 3 deletions(-)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 9b032fbf675..933b90de1d0 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,25 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</relation> and
+ <function>pg_restore_attribute_stats</relation>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 6066510c7c0..cb84d453f4f 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4551,7 +4552,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11462,6 +11464,12 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+WARNING: Failed to import statistics from remote table public.base_tbl2, will try to ANALYZE with regular row sampling.
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11568,6 +11576,11 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+WARNING: Failed to import statistics from remote table public.base_tbl3, will try to ANALYZE with regular row sampling.
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..5b7726800d0 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +279,10 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 3572689e33b..86bdfc57c07 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -18,10 +18,13 @@
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_opfamily.h"
+#include "catalog/pg_statistic_ext.h"
#include "commands/defrem.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -42,12 +45,14 @@
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
+#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
+#include "utils/syscache.h"
PG_MODULE_MAGIC_EXT(
.name = "postgres_fdw",
@@ -317,6 +322,20 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ char remote_attname[NAMEDATALEN];
+ AttrNumber local_attnum;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -402,6 +421,10 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresStatisticsAreImportable(Relation relation);
+static bool postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +569,188 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns
+{
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_NUM_FIELDS,
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+static const char *attstats_query_default =
+"SELECT s.attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\"";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns
+{
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS,
+};
+
+static const char *relimport_sql =
+"SELECT pg_catalog.pg_restore_relation_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'relpages', $4::integer,\n"
+"\t'reltuples', $5::real)";
+
+enum RelImportSqlArgs
+{
+ RELIMPORT_SQL_VERSION = 0,
+ RELIMPORT_SQL_SCHEMANAME,
+ RELIMPORT_SQL_RELNAME,
+ RELIMPORT_SQL_RELPAGES,
+ RELIMPORT_SQL_RELTUPLES,
+ RELIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid relimport_argtypes[RELIMPORT_SQL_NUM_FIELDS] = {
+INT4OID, TEXTOID, TEXTOID, TEXTOID, TEXTOID,};
+
+static const char *attimport_sql =
+"SELECT pg_catalog.pg_restore_attribute_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'attnum', $4,\n"
+"\t'inherited', false::boolean,\n"
+"\t'null_frac', $5::real,\n"
+"\t'avg_width', $6::integer,\n"
+"\t'n_distinct', $7::real,\n"
+"\t'most_common_vals', $8,\n"
+"\t'most_common_freqs', $9::real[],\n"
+"\t'histogram_bounds', $10,\n"
+"\t'correlation', $11::real,\n"
+"\t'most_common_elems', $12,\n"
+"\t'most_common_elem_freqs', $13::real[],\n"
+"\t'elem_count_histogram', $14::real[],\n"
+"\t'range_length_histogram', $15,\n"
+"\t'range_empty_frac', $16::real,\n"
+"\t'range_bounds_histogram', $17)";
+
+enum AttImportSqlArgs
+{
+ ATTIMPORT_SQL_VERSION = 0,
+ ATTIMPORT_SQL_SCHEMANAME,
+ ATTIMPORT_SQL_RELNAME,
+ ATTIMPORT_SQL_ATTNUM,
+ ATTIMPORT_SQL_NULL_FRAC,
+ ATTIMPORT_SQL_AVG_WIDTH,
+ ATTIMPORT_SQL_N_DISTINCT,
+ ATTIMPORT_SQL_MOST_COMMON_VALS,
+ ATTIMPORT_SQL_MOST_COMMON_FREQS,
+ ATTIMPORT_SQL_HISTOGRAM_BOUNDS,
+ ATTIMPORT_SQL_CORRELATION,
+ ATTIMPORT_SQL_MOST_COMMON_ELEMS,
+ ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS,
+ ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_EMPTY_FRAC,
+ ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM,
+ ATTIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid attimport_argtypes[ATTIMPORT_SQL_NUM_FIELDS] = {
+ INT4OID, TEXTOID, TEXTOID, INT2OID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+TEXTOID,};
+
+/* Pairs AttStatsColumns:AttImportSqlArgs Map */
+typedef struct
+{
+ enum AttStatsColumns res_field;
+ enum AttImportSqlArgs arg_num;
+} AttrResultArgMap;
+
+/*
+ * The mapping of attribute stats query columns to the positional arguments in
+ * the prepared pg_restore_attribute_stats() statement.
+ */
+#define NUM_MAPPED_ATTIMPORT_ARGS 13
+static const AttrResultArgMap attr_result_arg_map[NUM_MAPPED_ATTIMPORT_ARGS] = {
+ {ATTSTATS_NULL_FRAC, ATTIMPORT_SQL_NULL_FRAC},
+ {ATTSTATS_AVG_WIDTH, ATTIMPORT_SQL_AVG_WIDTH},
+ {ATTSTATS_N_DISTINCT, ATTIMPORT_SQL_N_DISTINCT},
+ {ATTSTATS_MOST_COMMON_VALS, ATTIMPORT_SQL_MOST_COMMON_VALS},
+ {ATTSTATS_MOST_COMMON_FREQS, ATTIMPORT_SQL_MOST_COMMON_FREQS},
+ {ATTSTATS_HISTOGRAM_BOUNDS, ATTIMPORT_SQL_HISTOGRAM_BOUNDS},
+ {ATTSTATS_CORRELATION, ATTIMPORT_SQL_CORRELATION},
+ {ATTSTATS_MOST_COMMON_ELEMS, ATTIMPORT_SQL_MOST_COMMON_ELEMS},
+ {ATTSTATS_MOST_COMMON_ELEM_FREQS, ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS},
+ {ATTSTATS_ELEM_COUNT_HISTOGRAM, ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM},
+ {ATTSTATS_RANGE_LENGTH_HISTOGRAM, ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM},
+ {ATTSTATS_RANGE_EMPTY_FRAC, ATTIMPORT_SQL_RANGE_EMPTY_FRAC},
+ {ATTSTATS_RANGE_BOUNDS_HISTOGRAM, ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM},
+};
+
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +800,8 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->StatisticsAreImportable = postgresStatisticsAreImportable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5142,711 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Move a string value from a result set to a Text value of a Datum array.
+ */
+static void
+map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls)
+{
+ if (PQgetisnull(res, row, field))
+ {
+ values[arg] = (Datum) 0;
+ nulls[arg] = 'n';
+ }
+ else
+ {
+ const char *s = PQgetvalue(res, row, field);
+
+ values[arg] = CStringGetTextDatum(s);
+ nulls[arg] = ' ';
+ }
+}
+
+/*
+ * Check the 1x1 result set of a pg_restore_*_stats() command for success.
+ */
+static bool
+import_spi_query_ok(int spirc)
+{
+ char *s;
+ bool ok;
+
+ if (spirc != SPI_OK_SELECT
+ || SPI_tuptable == NULL
+ || SPI_processed != 1)
+ return false;
+
+ s = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
+
+ ok = (s != NULL && s[0] == 't' && s[1] == '\0');
+ pfree(s);
+
+ return ok;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static bool
+import_fetched_statistics(const char *schemaname, const char *relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping * remattrmap,
+ RemoteStatsResults * remstats)
+{
+ SPIPlanPtr plan = NULL;
+ PGresult *res = remstats->att;
+ int spirc;
+ int mapidx = 0;
+ Datum values[ATTIMPORT_SQL_NUM_FIELDS];
+ char nulls[ATTIMPORT_SQL_NUM_FIELDS];
+ bool ok = false;
+
+ /* Assign all the invariant parameters */
+ values[ATTIMPORT_SQL_VERSION] = Int32GetDatum(server_version_num);
+ nulls[ATTIMPORT_SQL_VERSION] = ' ';
+
+ values[ATTIMPORT_SQL_SCHEMANAME] = CStringGetTextDatum(schemaname);
+ nulls[ATTIMPORT_SQL_SCHEMANAME] = ' ';
+
+ values[ATTIMPORT_SQL_RELNAME] = CStringGetTextDatum(relname);
+ nulls[ATTIMPORT_SQL_RELNAME] = ' ';
+
+ nulls[ATTIMPORT_SQL_ATTNUM] = ' ';
+
+ SPI_connect();
+
+ plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+
+ if (plan == NULL || SPI_result < 0)
+ {
+ ereport(WARNING,
+ errmsg("Import attribute statistics prepare failed %s "
+ "with error code %d",
+ attimport_sql, SPI_result));
+ goto import_cleanup;
+ }
+
+ /*
+ * Match result set rows to local attnums.
+ *
+ * Every row of the result should be an attribute that we specifically
+ * filtered for, so every row should have at least one match in the
+ * RemoteAttributeMapping, which is also ordered by attname, so we only
+ * need to walk that array once.
+ *
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ for (int row = 0; row < PQntuples(remstats->att); row++)
+ {
+ char *remote_attname;
+ bool match_found = false;
+ int cmp = 0;
+
+ if (PQgetisnull(res, row, ATTSTATS_ATTNAME))
+ {
+ ereport(WARNING,
+ errmsg("Remote statistics returned a row with NULL attribute name"));
+ goto import_cleanup;
+ }
+
+ remote_attname = PQgetvalue(res, row, ATTSTATS_ATTNAME);
+
+ /*
+ * Handle a series of matching elements in the mapping.
+ *
+ * We exit this loop in the following ways:
+ *
+ * 1. Having found at least match and exhausting the list. We're done.
+ * 2. Having found at least match and ending on a <, advance. 3.
+ * Having found at least match and ending on a >, bad sort. 4. No
+ * match, list exhausted. 5. No match, <. 6. No match, >.
+ *
+ */
+ for (; mapidx < natts; mapidx++)
+ {
+ cmp = strcmp(remote_attname, remattrmap[mapidx].remote_attname);
+
+ /* Stop scanning on the first non-match */
+ if (cmp != 0)
+ break;
+
+ match_found = true;
+ values[ATTIMPORT_SQL_ATTNUM] =
+ Int16GetDatum(remattrmap[mapidx].local_attnum);
+
+ /* Loop through all mappable columns->arguments */
+ for (int i = 0; i < NUM_MAPPED_ATTIMPORT_ARGS; i++)
+ map_field_to_arg(res, row,
+ attr_result_arg_map[i].res_field,
+ attr_result_arg_map[i].arg_num,
+ values, nulls);
+
+ spirc = SPI_execute_plan(plan, values, nulls, false, 0);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("Attribute statistics import failed %s",
+ attimport_sql));
+ goto import_cleanup;
+ }
+ }
+
+ /* We found a match, move onto the next result. */
+ if (match_found)
+ continue;
+
+ /*
+ * If no match and we ended on a <, then the mapidx will never find a
+ * match, so stop now and let the cleanup report the error.
+ */
+ if (cmp > 0)
+ break;
+
+ /*
+ * Otherwise this result found no matching mapidx, which should only
+ * happen if the results are out of sort or the wrong query was
+ * executed.
+ */
+ if (cmp < 0)
+ {
+ ereport(WARNING,
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+ goto import_cleanup;
+ }
+ }
+
+ /* Look for a mapidx with no possible matching result */
+ if (mapidx < natts)
+ {
+ ereport(WARNING,
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+ goto import_cleanup;
+ }
+
+ /*
+ * Import relstats.
+ *
+ * Import relation stats. We only perform this once, so there is no point
+ * in preparing the statement.
+ *
+ * We can re-use the values/nulls because the number of parameters is less
+ * and the first three params are the same as attstats_import.
+ */
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELPAGES,
+ RELIMPORT_SQL_RELPAGES, values, nulls);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELTUPLES,
+ RELIMPORT_SQL_RELTUPLES, values, nulls);
+
+ spirc = SPI_execute_with_args(relimport_sql, RELIMPORT_SQL_NUM_FIELDS,
+ (Oid *) relimport_argtypes,
+ values, nulls, false, 1);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("Relation statistics import failed %s",
+ relimport_sql));
+ goto import_cleanup;
+ }
+
+ ok = true;
+
+import_cleanup:
+ if (plan)
+ SPI_freeplan(plan);
+ SPI_finish();
+ return ok;
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ *
+ * Verify that the result is of the proper shape, return NULL otherwise.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname)
+{
+ const char *params[2] = {remote_schemaname, remote_relname};
+
+ /*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case).
+ *
+ * We can ignore this change, because if the remote table wasn't analyzed,
+ * then it would have no attribute stats, and thus we wouldn't have stats
+ * that we would try to import. So we can take the reltuples value as-is.
+ */
+ const char *sql = "SELECT c.relkind, c.relpages, c.reltuples "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n "
+ "ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+ PGresult *res = NULL;
+
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ {
+ pgfdw_report(WARNING, NULL, conn, sql);
+ return NULL;
+ }
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS
+ || PQgetisnull(res, 0, RELSTATS_RELKIND))
+ {
+ pgfdw_report(WARNING, res, conn, sql);
+ PQclear(res);
+ return NULL;
+ }
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ *
+ * Verify that the result is of the proper shape, return NULL otherwise. Note
+ * that we do not verify the row count.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list)
+{
+ const char *params[3] = {remote_schemaname, remote_relname, column_list};
+ int version = PQserverVersion(conn);
+ const char *sql;
+ PGresult *res;
+
+ if (version >= 170000)
+ sql = attstats_query_17;
+ else if (version >= 90200)
+ sql = attstats_query_9_2;
+ else if (version >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ {
+ pgfdw_report(WARNING, NULL, conn, sql);
+ return NULL;
+ }
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(WARNING, res, conn, sql);
+ PQclear(res);
+ return NULL;
+ }
+
+ return res;
+}
+
+/*
+ * Make a '{column,list,array}'.
+ */
+static char *
+get_column_list(int natts, const RemoteAttributeMapping * remattrmap)
+{
+ StringInfoData column_list;
+
+ initStringInfo(&column_list);
+ appendStringInfoChar(&column_list, '{');
+ for (int i = 0; i < natts; i++)
+ {
+ if (i > 0)
+ appendStringInfoChar(&column_list, ',');
+ appendStringInfoString(&column_list,
+ quote_identifier(remattrmap[i].remote_attname));
+ }
+ appendStringInfoChar(&column_list, '}');
+
+ return column_list.data;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static bool
+fetch_remote_statistics(PGconn *conn,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping * remattrmap,
+ RemoteStatsResults * remstats)
+{
+ char *column_list = NULL;
+ PGresult *attstats = NULL;
+ PGresult *relstats = NULL;
+
+ char relkind;
+
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ if (relstats == NULL)
+ goto fetch_remote_statistics_fail;
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
+ * can't support a foreign table.
+ */
+ relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
+
+ switch (relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ goto fetch_remote_statistics_fail;
+ }
+
+ column_list = get_column_list(natts, remattrmap);
+
+ /* See if it actually has any attribute stats. */
+ attstats = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list);
+
+ /*
+ * If we got attribute statistics results, then we are done with fetching.
+ */
+ if (attstats != NULL
+ && PQntuples(attstats) > 0)
+ {
+ pfree(column_list);
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+ }
+
+fetch_remote_statistics_fail:
+ ereport(WARNING,
+ errmsg("Failed to import statistics from remote table %s, "
+ "will try to ANALYZE with regular row sampling.",
+ quote_qualified_identifier(remote_schemaname,
+ remote_relname)));
+ PQclear(attstats);
+ PQclear(relstats);
+ if (column_list)
+ pfree(column_list);
+ return false;
+}
+
+/*
+ * Test if the relation has extended statistics objects.
+ */
+static bool
+table_has_extended_stats(Relation relation)
+{
+ Relation pg_statext;
+ SysScanDesc scan;
+ ScanKeyData skey;
+ bool found;
+
+ pg_statext = table_open(StatisticExtRelationId, RowExclusiveLock);
+
+ /*
+ * Prepare to scan pg_statistic_ext for entries having stxrelid = this
+ * rel.
+ */
+ ScanKeyInit(&skey,
+ Anum_pg_statistic_ext_stxrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(relation)));
+
+ scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
+ NULL, 1, &skey);
+
+ found = (systable_getnext(scan) != NULL);
+
+ systable_endscan(scan);
+
+ table_close(pg_statext, RowExclusiveLock);
+
+ return found;
+}
+
+static bool
+postgresStatisticsAreImportable(Relation relation)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ ListCell *lc;
+ bool fetch_stats = true;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ /*
+ * Additional checks that can disqualify a table from importing stats.
+ */
+ if (fetch_stats)
+ {
+ /*
+ * We can't compute extended stats from the column stats, for that we
+ * need a table sample.
+ */
+ if (table_has_extended_stats(relation))
+ {
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Cannot import statistics for foreign table \"%s\" "
+ "because it has extended statistics objects.",
+ RelationGetRelationName(relation)));
+ fetch_stats = false;
+ }
+ }
+
+ return fetch_stats;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Fetch attstattarget from a pg_attribute tuple.
+ */
+static int16
+get_attstattarget(Relation relation, AttrNumber attnum)
+{
+ HeapTuple atttuple;
+ bool isnull;
+ Datum dat;
+ int16 attstattarget;
+ Oid relid = RelationGetRelid(relation);
+
+ atttuple = SearchSysCache2(ATTNUM,
+ ObjectIdGetDatum(relid),
+ Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, relid);
+ dat = SysCacheGetAttr(ATTNUM, atttuple,
+ Anum_pg_attribute_attstattarget,
+ &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ return attstattarget;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static bool
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+
+ ForeignTable *table;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int natts = 0;
+ bool ok = false;
+
+ RemoteAttributeMapping *remattrmap;
+
+ RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ }
+
+ /*
+ * Assume the relation/schema names are the same as the local name unless
+ * the options tell us otherwise.
+ */
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ /*
+ * Build attnum/remote-attname list.
+ *
+ */
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *attname;
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+
+ /* Ignore dropped columns. */
+ if (attr->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (attr->attgenerated)
+ continue;
+
+ attname = NameStr(attr->attname);
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ attnum = attr->attnum;
+
+ /* Ignore if attstatarget is 0 */
+ if (get_attstattarget(relation, attnum) == 0)
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_colname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].remote_attname, remote_colname, NAMEDATALEN);
+ natts++;
+ }
+
+ /* Sort mapping by remote attribute name */
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
+ server_version_num, natts, remattrmap,
+ &remstats);
+
+ ReleaseConnection(conn);
+
+ if (ok)
+ {
+ Assert(remstats.rel != NULL);
+ Assert(PQnfields(remstats.rel) == RELSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.rel) == 1);
+ Assert(remstats.att != NULL);
+ Assert(PQnfields(remstats.att) == ATTSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.att) >= 1);
+ ok = import_fetched_statistics(schemaname, relname, server_version_num,
+ natts, remattrmap, &remstats);
+ }
+
+ pfree(remattrmap);
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+ return ok;
+}
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 4f7ab2ed0ac..ea4a2153190 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1286,7 +1287,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3903,6 +3905,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3940,6 +3947,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
--
2.52.0
v10-0003-Add-remote_analyze-to-postgres_fdw-remote-statis.patch (text/x-patch, 10.8K) download
From 8b4ffd7f187febc05094accc8e2bba71d7d49a0d Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:33:53 -0500
Subject: [PATCH v10 3/3] Add remote_analyze to postgres_fdw remote statistics
fetching.
This is accomplished through a new option, remote_analyze, which is
available at the server level and table level. The default value is
false.
If remote_analyze is enabled, and if the first attempt to fetch remote
statistics did not fetch attribute statistics for every local table
column, then an attempt will be made to ANALYZE the remote table. If
that remote ANALYZE succeeds, then a second and final attempt will be
made to fetch remote statistics. If the statistics found are still
insufficient, then the local ANALYZE command will fall back to regular
row sampling and computing the statistics locally.
---
doc/src/sgml/postgres-fdw.sgml | 16 ++++
.../postgres_fdw/expected/postgres_fdw.out | 38 +++++++++
contrib/postgres_fdw/option.c | 5 ++
contrib/postgres_fdw/postgres_fdw.c | 80 ++++++++++++++++++-
contrib/postgres_fdw/sql/postgres_fdw.sql | 34 ++++++++
5 files changed, 171 insertions(+), 2 deletions(-)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 933b90de1d0..5d46f619a7c 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -383,6 +383,22 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ has no meaning if the foreign table has <literal>fetch_stats</literal>
+ disabled.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index cb84d453f4f..b3ec0ce1559 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -12678,6 +12678,44 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 5b7726800d0..2941ecbfb87 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -121,6 +121,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -283,6 +284,10 @@ InitPgFdwOptions(void)
{"fetch_stats", ForeignServerRelationId, false},
{"fetch_stats", ForeignTableRelationId, false},
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 86bdfc57c07..1ba743c7fb2 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -5390,6 +5390,36 @@ import_cleanup:
return ok;
}
+/*
+ * Analyze a remote table.
+ */
+static bool
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+ bool ok = true;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s",
+ quote_qualified_identifier(remote_schemaname, remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL ||
+ PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ pgfdw_report(WARNING, res, conn, buf.data);
+ ok = false;
+ }
+
+ PQclear(res);
+ pfree(buf.data);
+ return ok;
+}
+
/*
* Attempt to fetch remote relations stats.
*
@@ -5516,7 +5546,7 @@ fetch_remote_statistics(PGconn *conn,
const char *remote_relname,
int server_version_num, int natts,
const RemoteAttributeMapping * remattrmap,
- RemoteStatsResults * remstats)
+ bool remote_analyze, RemoteStatsResults * remstats)
{
char *column_list = NULL;
PGresult *attstats = NULL;
@@ -5568,6 +5598,35 @@ fetch_remote_statistics(PGconn *conn,
return true;
}
+ /*
+ * If remote_analyze is enabled, then we will try to analyze the table and
+ * then try again.
+ */
+ if (!remote_analyze)
+ goto fetch_remote_statistics_fail;
+
+ if (!analyze_remote_table(conn, remote_schemaname, remote_relname))
+ goto fetch_remote_statistics_fail;
+
+ PQclear(attstats);
+ attstats = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list);
+
+ if (attstats == NULL || PQntuples(attstats) == 0)
+ goto fetch_remote_statistics_fail;
+
+ PQclear(relstats);
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ if (relstats == NULL)
+ goto fetch_remote_statistics_fail;
+
+ /* Second attempt worked */
+ pfree(column_list);
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+
fetch_remote_statistics_fail:
ereport(WARNING,
errmsg("Failed to import statistics from remote table %s, "
@@ -5723,9 +5782,11 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
{
ForeignTable *table;
+ ForeignServer *server;
UserMapping *user;
PGconn *conn;
ListCell *lc;
+ bool remote_analyze = false;
int server_version_num = 0;
const char *schemaname = NULL;
const char *relname = NULL;
@@ -5740,12 +5801,25 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
user = GetUserMapping(GetUserId(), table->serverid);
conn = GetConnection(user, false, NULL);
server_version_num = PQserverVersion(conn);
schemaname = get_namespace_name(RelationGetNamespace(relation));
relname = RelationGetRelationName(relation);
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
foreach(lc, table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
@@ -5754,6 +5828,8 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
remote_schemaname = defGetString(def);
else if (strcmp(def->defname, "table_name") == 0)
remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
}
/*
@@ -5825,7 +5901,7 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
server_version_num, natts, remattrmap,
- &remstats);
+ remote_analyze, &remstats);
ReleaseConnection(conn);
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index ea4a2153190..ac284fba069 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -4398,6 +4398,40 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
--
2.52.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-21 20:51 Corey Huinker <corey.huinker@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-01-21 20:51 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> Changes in this release, aside from rebasing:
>
> - The generic analyze and fdw.h changes are in their own patch (0001) that
> ignores contrib/postgres_fdw entirely.
> - The option for remote_analyze has been moved to its own patch (0003).
> - The errors raised are now warnings, to ensure that we can always fall
> back to row sampling.
> - All local attributes with attstatarget > 0 must get matching remote
> statistics or the import is considered a failure.
> - The pg_restore_attribute_stats() call has been turned into a prepared
> statement, for clarity and some minor parsing savings.
> - The calls to pg_restore_relation_stats() are parameterized, but not
> prepared as this is rarely called more than once.
> - postgresStatisticsAreImportable will now disqualify a table if has
> extended statistics objects, because we can't compute those without a row
> sample.
>
Rebase
Attachments: download all (3 files, .tar.gz)
v11-0001-Add-FDW-functions-for-importing-optimizer-statis.patch (text/x-patch, 5.0K) download
From e0ff37ed436cd4f50e2c6de17d1d9c89ce2d0b72 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 16:39:45 -0500
Subject: [PATCH v11 1/3] Add FDW functions for importing optimizer statistics.
Add the the function StatisticsAreImportable which is used as a
lightweight preliminary scan to determine if the remote table could
potentially have statistics that could be imported instead of fetching a
row sample from the remote table, which can be expensive.
Also add the function ImportStatistics which attempts to actually fetch
those statistics from the remote server, and if successful import them
into the local statistics catalog.
---
src/include/foreign/fdwapi.h | 8 ++++
src/backend/commands/analyze.c | 68 ++++++++++++++++++++++++----------
2 files changed, 56 insertions(+), 20 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..59beeae4f45 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef bool (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +261,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index a483424152c..c84367461fb 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -113,6 +113,9 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool can_import_stats = false;
+ bool stats_imported = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -195,27 +198,16 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
- {
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
- }
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ can_import_stats = true;
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
{
@@ -247,10 +239,46 @@ analyze_rel(Oid relid, RangeVar *relation,
PROGRESS_ANALYZE_STARTED_BY_MANUAL);
/*
- * Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * If this table can import statistics, attempt to do so.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (can_import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ stats_imported = fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+
+ /*
+ * Foreign tables that were not able to import stats will resort to
+ * regular sampling.
+ */
+ if ((onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
+ && !stats_imported)
+ {
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
+ }
+
+ /*
+ * Do the normal non-recursive ANALYZE. We can skip this for partitioned
+ * tables and foreign tables that successfully imported statistics.
+ */
+ if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ && !stats_imported)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
base-commit: 25dc4850747bb12e871af3589736463edd1d2aa6
--
2.52.0
v11-0002-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 36.1K) download
From 629fa3d0a6d4019a1fc67f531c5fbeb64d40388b Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:06:05 -0500
Subject: [PATCH v11 2/3] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via a new option, fetch_stats, which is available at the
server level and table level. The global default is true, but this can
be overriden by at the server level, which in turn can be overridden at
the table level.
If fetch_stats is true, and the remote table is an actual table or
materialized view that can hold statistics, and the local table does not
have any extended statistics objects built upon it, then the remote
database will first be queried for relation statistics and attribute
statistics similar to the method used in pg_dump.
If there are remote statistics for all of the columns in the local
table, then those statistics will be imported using
pg_restore_relation_statistics and pg_restore_attribute_statistics
functions similar to the way pg_restore uses them.
If fetch_stats is false, or if the fetched statistics were missing or
otherwise inadequate, then the ANALYZE operation will issue a WARNING
and then fall back to regular table sampling to generate local
statistics.
---
doc/src/sgml/postgres-fdw.sgml | 21 +-
.../postgres_fdw/expected/postgres_fdw.out | 15 +-
contrib/postgres_fdw/option.c | 5 +
contrib/postgres_fdw/postgres_fdw.c | 912 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 13 +-
5 files changed, 963 insertions(+), 3 deletions(-)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 9b032fbf675..933b90de1d0 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,25 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</relation> and
+ <function>pg_restore_attribute_stats</relation>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views).
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 6066510c7c0..cb84d453f4f 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4551,7 +4552,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11462,6 +11464,12 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+WARNING: Failed to import statistics from remote table public.base_tbl2, will try to ANALYZE with regular row sampling.
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11568,6 +11576,11 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+WARNING: Failed to import statistics from remote table public.base_tbl3, will try to ANALYZE with regular row sampling.
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..5b7726800d0 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +279,10 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 3572689e33b..86bdfc57c07 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -18,10 +18,13 @@
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_opfamily.h"
+#include "catalog/pg_statistic_ext.h"
#include "commands/defrem.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -42,12 +45,14 @@
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
+#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
+#include "utils/syscache.h"
PG_MODULE_MAGIC_EXT(
.name = "postgres_fdw",
@@ -317,6 +322,20 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ char remote_attname[NAMEDATALEN];
+ AttrNumber local_attnum;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -402,6 +421,10 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresStatisticsAreImportable(Relation relation);
+static bool postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +569,188 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns
+{
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_NUM_FIELDS,
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+static const char *attstats_query_default =
+"SELECT s.attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\"";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns
+{
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS,
+};
+
+static const char *relimport_sql =
+"SELECT pg_catalog.pg_restore_relation_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'relpages', $4::integer,\n"
+"\t'reltuples', $5::real)";
+
+enum RelImportSqlArgs
+{
+ RELIMPORT_SQL_VERSION = 0,
+ RELIMPORT_SQL_SCHEMANAME,
+ RELIMPORT_SQL_RELNAME,
+ RELIMPORT_SQL_RELPAGES,
+ RELIMPORT_SQL_RELTUPLES,
+ RELIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid relimport_argtypes[RELIMPORT_SQL_NUM_FIELDS] = {
+INT4OID, TEXTOID, TEXTOID, TEXTOID, TEXTOID,};
+
+static const char *attimport_sql =
+"SELECT pg_catalog.pg_restore_attribute_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'attnum', $4,\n"
+"\t'inherited', false::boolean,\n"
+"\t'null_frac', $5::real,\n"
+"\t'avg_width', $6::integer,\n"
+"\t'n_distinct', $7::real,\n"
+"\t'most_common_vals', $8,\n"
+"\t'most_common_freqs', $9::real[],\n"
+"\t'histogram_bounds', $10,\n"
+"\t'correlation', $11::real,\n"
+"\t'most_common_elems', $12,\n"
+"\t'most_common_elem_freqs', $13::real[],\n"
+"\t'elem_count_histogram', $14::real[],\n"
+"\t'range_length_histogram', $15,\n"
+"\t'range_empty_frac', $16::real,\n"
+"\t'range_bounds_histogram', $17)";
+
+enum AttImportSqlArgs
+{
+ ATTIMPORT_SQL_VERSION = 0,
+ ATTIMPORT_SQL_SCHEMANAME,
+ ATTIMPORT_SQL_RELNAME,
+ ATTIMPORT_SQL_ATTNUM,
+ ATTIMPORT_SQL_NULL_FRAC,
+ ATTIMPORT_SQL_AVG_WIDTH,
+ ATTIMPORT_SQL_N_DISTINCT,
+ ATTIMPORT_SQL_MOST_COMMON_VALS,
+ ATTIMPORT_SQL_MOST_COMMON_FREQS,
+ ATTIMPORT_SQL_HISTOGRAM_BOUNDS,
+ ATTIMPORT_SQL_CORRELATION,
+ ATTIMPORT_SQL_MOST_COMMON_ELEMS,
+ ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS,
+ ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_EMPTY_FRAC,
+ ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM,
+ ATTIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid attimport_argtypes[ATTIMPORT_SQL_NUM_FIELDS] = {
+ INT4OID, TEXTOID, TEXTOID, INT2OID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+TEXTOID,};
+
+/* Pairs AttStatsColumns:AttImportSqlArgs Map */
+typedef struct
+{
+ enum AttStatsColumns res_field;
+ enum AttImportSqlArgs arg_num;
+} AttrResultArgMap;
+
+/*
+ * The mapping of attribute stats query columns to the positional arguments in
+ * the prepared pg_restore_attribute_stats() statement.
+ */
+#define NUM_MAPPED_ATTIMPORT_ARGS 13
+static const AttrResultArgMap attr_result_arg_map[NUM_MAPPED_ATTIMPORT_ARGS] = {
+ {ATTSTATS_NULL_FRAC, ATTIMPORT_SQL_NULL_FRAC},
+ {ATTSTATS_AVG_WIDTH, ATTIMPORT_SQL_AVG_WIDTH},
+ {ATTSTATS_N_DISTINCT, ATTIMPORT_SQL_N_DISTINCT},
+ {ATTSTATS_MOST_COMMON_VALS, ATTIMPORT_SQL_MOST_COMMON_VALS},
+ {ATTSTATS_MOST_COMMON_FREQS, ATTIMPORT_SQL_MOST_COMMON_FREQS},
+ {ATTSTATS_HISTOGRAM_BOUNDS, ATTIMPORT_SQL_HISTOGRAM_BOUNDS},
+ {ATTSTATS_CORRELATION, ATTIMPORT_SQL_CORRELATION},
+ {ATTSTATS_MOST_COMMON_ELEMS, ATTIMPORT_SQL_MOST_COMMON_ELEMS},
+ {ATTSTATS_MOST_COMMON_ELEM_FREQS, ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS},
+ {ATTSTATS_ELEM_COUNT_HISTOGRAM, ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM},
+ {ATTSTATS_RANGE_LENGTH_HISTOGRAM, ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM},
+ {ATTSTATS_RANGE_EMPTY_FRAC, ATTIMPORT_SQL_RANGE_EMPTY_FRAC},
+ {ATTSTATS_RANGE_BOUNDS_HISTOGRAM, ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM},
+};
+
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +800,8 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->StatisticsAreImportable = postgresStatisticsAreImportable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5142,711 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Move a string value from a result set to a Text value of a Datum array.
+ */
+static void
+map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls)
+{
+ if (PQgetisnull(res, row, field))
+ {
+ values[arg] = (Datum) 0;
+ nulls[arg] = 'n';
+ }
+ else
+ {
+ const char *s = PQgetvalue(res, row, field);
+
+ values[arg] = CStringGetTextDatum(s);
+ nulls[arg] = ' ';
+ }
+}
+
+/*
+ * Check the 1x1 result set of a pg_restore_*_stats() command for success.
+ */
+static bool
+import_spi_query_ok(int spirc)
+{
+ char *s;
+ bool ok;
+
+ if (spirc != SPI_OK_SELECT
+ || SPI_tuptable == NULL
+ || SPI_processed != 1)
+ return false;
+
+ s = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
+
+ ok = (s != NULL && s[0] == 't' && s[1] == '\0');
+ pfree(s);
+
+ return ok;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static bool
+import_fetched_statistics(const char *schemaname, const char *relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping * remattrmap,
+ RemoteStatsResults * remstats)
+{
+ SPIPlanPtr plan = NULL;
+ PGresult *res = remstats->att;
+ int spirc;
+ int mapidx = 0;
+ Datum values[ATTIMPORT_SQL_NUM_FIELDS];
+ char nulls[ATTIMPORT_SQL_NUM_FIELDS];
+ bool ok = false;
+
+ /* Assign all the invariant parameters */
+ values[ATTIMPORT_SQL_VERSION] = Int32GetDatum(server_version_num);
+ nulls[ATTIMPORT_SQL_VERSION] = ' ';
+
+ values[ATTIMPORT_SQL_SCHEMANAME] = CStringGetTextDatum(schemaname);
+ nulls[ATTIMPORT_SQL_SCHEMANAME] = ' ';
+
+ values[ATTIMPORT_SQL_RELNAME] = CStringGetTextDatum(relname);
+ nulls[ATTIMPORT_SQL_RELNAME] = ' ';
+
+ nulls[ATTIMPORT_SQL_ATTNUM] = ' ';
+
+ SPI_connect();
+
+ plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+
+ if (plan == NULL || SPI_result < 0)
+ {
+ ereport(WARNING,
+ errmsg("Import attribute statistics prepare failed %s "
+ "with error code %d",
+ attimport_sql, SPI_result));
+ goto import_cleanup;
+ }
+
+ /*
+ * Match result set rows to local attnums.
+ *
+ * Every row of the result should be an attribute that we specifically
+ * filtered for, so every row should have at least one match in the
+ * RemoteAttributeMapping, which is also ordered by attname, so we only
+ * need to walk that array once.
+ *
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ for (int row = 0; row < PQntuples(remstats->att); row++)
+ {
+ char *remote_attname;
+ bool match_found = false;
+ int cmp = 0;
+
+ if (PQgetisnull(res, row, ATTSTATS_ATTNAME))
+ {
+ ereport(WARNING,
+ errmsg("Remote statistics returned a row with NULL attribute name"));
+ goto import_cleanup;
+ }
+
+ remote_attname = PQgetvalue(res, row, ATTSTATS_ATTNAME);
+
+ /*
+ * Handle a series of matching elements in the mapping.
+ *
+ * We exit this loop in the following ways:
+ *
+ * 1. Having found at least match and exhausting the list. We're done.
+ * 2. Having found at least match and ending on a <, advance. 3.
+ * Having found at least match and ending on a >, bad sort. 4. No
+ * match, list exhausted. 5. No match, <. 6. No match, >.
+ *
+ */
+ for (; mapidx < natts; mapidx++)
+ {
+ cmp = strcmp(remote_attname, remattrmap[mapidx].remote_attname);
+
+ /* Stop scanning on the first non-match */
+ if (cmp != 0)
+ break;
+
+ match_found = true;
+ values[ATTIMPORT_SQL_ATTNUM] =
+ Int16GetDatum(remattrmap[mapidx].local_attnum);
+
+ /* Loop through all mappable columns->arguments */
+ for (int i = 0; i < NUM_MAPPED_ATTIMPORT_ARGS; i++)
+ map_field_to_arg(res, row,
+ attr_result_arg_map[i].res_field,
+ attr_result_arg_map[i].arg_num,
+ values, nulls);
+
+ spirc = SPI_execute_plan(plan, values, nulls, false, 0);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("Attribute statistics import failed %s",
+ attimport_sql));
+ goto import_cleanup;
+ }
+ }
+
+ /* We found a match, move onto the next result. */
+ if (match_found)
+ continue;
+
+ /*
+ * If no match and we ended on a <, then the mapidx will never find a
+ * match, so stop now and let the cleanup report the error.
+ */
+ if (cmp > 0)
+ break;
+
+ /*
+ * Otherwise this result found no matching mapidx, which should only
+ * happen if the results are out of sort or the wrong query was
+ * executed.
+ */
+ if (cmp < 0)
+ {
+ ereport(WARNING,
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+ goto import_cleanup;
+ }
+ }
+
+ /* Look for a mapidx with no possible matching result */
+ if (mapidx < natts)
+ {
+ ereport(WARNING,
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+ goto import_cleanup;
+ }
+
+ /*
+ * Import relstats.
+ *
+ * Import relation stats. We only perform this once, so there is no point
+ * in preparing the statement.
+ *
+ * We can re-use the values/nulls because the number of parameters is less
+ * and the first three params are the same as attstats_import.
+ */
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELPAGES,
+ RELIMPORT_SQL_RELPAGES, values, nulls);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELTUPLES,
+ RELIMPORT_SQL_RELTUPLES, values, nulls);
+
+ spirc = SPI_execute_with_args(relimport_sql, RELIMPORT_SQL_NUM_FIELDS,
+ (Oid *) relimport_argtypes,
+ values, nulls, false, 1);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("Relation statistics import failed %s",
+ relimport_sql));
+ goto import_cleanup;
+ }
+
+ ok = true;
+
+import_cleanup:
+ if (plan)
+ SPI_freeplan(plan);
+ SPI_finish();
+ return ok;
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ *
+ * Verify that the result is of the proper shape, return NULL otherwise.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname)
+{
+ const char *params[2] = {remote_schemaname, remote_relname};
+
+ /*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case).
+ *
+ * We can ignore this change, because if the remote table wasn't analyzed,
+ * then it would have no attribute stats, and thus we wouldn't have stats
+ * that we would try to import. So we can take the reltuples value as-is.
+ */
+ const char *sql = "SELECT c.relkind, c.relpages, c.reltuples "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n "
+ "ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+ PGresult *res = NULL;
+
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ {
+ pgfdw_report(WARNING, NULL, conn, sql);
+ return NULL;
+ }
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS
+ || PQgetisnull(res, 0, RELSTATS_RELKIND))
+ {
+ pgfdw_report(WARNING, res, conn, sql);
+ PQclear(res);
+ return NULL;
+ }
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ *
+ * Verify that the result is of the proper shape, return NULL otherwise. Note
+ * that we do not verify the row count.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list)
+{
+ const char *params[3] = {remote_schemaname, remote_relname, column_list};
+ int version = PQserverVersion(conn);
+ const char *sql;
+ PGresult *res;
+
+ if (version >= 170000)
+ sql = attstats_query_17;
+ else if (version >= 90200)
+ sql = attstats_query_9_2;
+ else if (version >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ {
+ pgfdw_report(WARNING, NULL, conn, sql);
+ return NULL;
+ }
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(WARNING, res, conn, sql);
+ PQclear(res);
+ return NULL;
+ }
+
+ return res;
+}
+
+/*
+ * Make a '{column,list,array}'.
+ */
+static char *
+get_column_list(int natts, const RemoteAttributeMapping * remattrmap)
+{
+ StringInfoData column_list;
+
+ initStringInfo(&column_list);
+ appendStringInfoChar(&column_list, '{');
+ for (int i = 0; i < natts; i++)
+ {
+ if (i > 0)
+ appendStringInfoChar(&column_list, ',');
+ appendStringInfoString(&column_list,
+ quote_identifier(remattrmap[i].remote_attname));
+ }
+ appendStringInfoChar(&column_list, '}');
+
+ return column_list.data;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static bool
+fetch_remote_statistics(PGconn *conn,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping * remattrmap,
+ RemoteStatsResults * remstats)
+{
+ char *column_list = NULL;
+ PGresult *attstats = NULL;
+ PGresult *relstats = NULL;
+
+ char relkind;
+
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ if (relstats == NULL)
+ goto fetch_remote_statistics_fail;
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
+ * can't support a foreign table.
+ */
+ relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
+
+ switch (relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ goto fetch_remote_statistics_fail;
+ }
+
+ column_list = get_column_list(natts, remattrmap);
+
+ /* See if it actually has any attribute stats. */
+ attstats = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list);
+
+ /*
+ * If we got attribute statistics results, then we are done with fetching.
+ */
+ if (attstats != NULL
+ && PQntuples(attstats) > 0)
+ {
+ pfree(column_list);
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+ }
+
+fetch_remote_statistics_fail:
+ ereport(WARNING,
+ errmsg("Failed to import statistics from remote table %s, "
+ "will try to ANALYZE with regular row sampling.",
+ quote_qualified_identifier(remote_schemaname,
+ remote_relname)));
+ PQclear(attstats);
+ PQclear(relstats);
+ if (column_list)
+ pfree(column_list);
+ return false;
+}
+
+/*
+ * Test if the relation has extended statistics objects.
+ */
+static bool
+table_has_extended_stats(Relation relation)
+{
+ Relation pg_statext;
+ SysScanDesc scan;
+ ScanKeyData skey;
+ bool found;
+
+ pg_statext = table_open(StatisticExtRelationId, RowExclusiveLock);
+
+ /*
+ * Prepare to scan pg_statistic_ext for entries having stxrelid = this
+ * rel.
+ */
+ ScanKeyInit(&skey,
+ Anum_pg_statistic_ext_stxrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(relation)));
+
+ scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
+ NULL, 1, &skey);
+
+ found = (systable_getnext(scan) != NULL);
+
+ systable_endscan(scan);
+
+ table_close(pg_statext, RowExclusiveLock);
+
+ return found;
+}
+
+static bool
+postgresStatisticsAreImportable(Relation relation)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ ListCell *lc;
+ bool fetch_stats = true;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ /*
+ * Additional checks that can disqualify a table from importing stats.
+ */
+ if (fetch_stats)
+ {
+ /*
+ * We can't compute extended stats from the column stats, for that we
+ * need a table sample.
+ */
+ if (table_has_extended_stats(relation))
+ {
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Cannot import statistics for foreign table \"%s\" "
+ "because it has extended statistics objects.",
+ RelationGetRelationName(relation)));
+ fetch_stats = false;
+ }
+ }
+
+ return fetch_stats;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Fetch attstattarget from a pg_attribute tuple.
+ */
+static int16
+get_attstattarget(Relation relation, AttrNumber attnum)
+{
+ HeapTuple atttuple;
+ bool isnull;
+ Datum dat;
+ int16 attstattarget;
+ Oid relid = RelationGetRelid(relation);
+
+ atttuple = SearchSysCache2(ATTNUM,
+ ObjectIdGetDatum(relid),
+ Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, relid);
+ dat = SysCacheGetAttr(ATTNUM, atttuple,
+ Anum_pg_attribute_attstattarget,
+ &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ return attstattarget;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static bool
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+
+ ForeignTable *table;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int natts = 0;
+ bool ok = false;
+
+ RemoteAttributeMapping *remattrmap;
+
+ RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ }
+
+ /*
+ * Assume the relation/schema names are the same as the local name unless
+ * the options tell us otherwise.
+ */
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ /*
+ * Build attnum/remote-attname list.
+ *
+ */
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *attname;
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+
+ /* Ignore dropped columns. */
+ if (attr->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (attr->attgenerated)
+ continue;
+
+ attname = NameStr(attr->attname);
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ attnum = attr->attnum;
+
+ /* Ignore if attstatarget is 0 */
+ if (get_attstattarget(relation, attnum) == 0)
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_colname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].remote_attname, remote_colname, NAMEDATALEN);
+ natts++;
+ }
+
+ /* Sort mapping by remote attribute name */
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
+ server_version_num, natts, remattrmap,
+ &remstats);
+
+ ReleaseConnection(conn);
+
+ if (ok)
+ {
+ Assert(remstats.rel != NULL);
+ Assert(PQnfields(remstats.rel) == RELSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.rel) == 1);
+ Assert(remstats.att != NULL);
+ Assert(PQnfields(remstats.att) == ATTSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.att) >= 1);
+ ok = import_fetched_statistics(schemaname, relname, server_version_num,
+ natts, remattrmap, &remstats);
+ }
+
+ pfree(remattrmap);
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+ return ok;
+}
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 4f7ab2ed0ac..ea4a2153190 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1286,7 +1287,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3903,6 +3905,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3940,6 +3947,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
--
2.52.0
v11-0003-Add-remote_analyze-to-postgres_fdw-remote-statis.patch (text/x-patch, 10.8K) download
From 40a4d867915caa65a25f15c8784a811730990091 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:33:53 -0500
Subject: [PATCH v11 3/3] Add remote_analyze to postgres_fdw remote statistics
fetching.
This is accomplished through a new option, remote_analyze, which is
available at the server level and table level. The default value is
false.
If remote_analyze is enabled, and if the first attempt to fetch remote
statistics did not fetch attribute statistics for every local table
column, then an attempt will be made to ANALYZE the remote table. If
that remote ANALYZE succeeds, then a second and final attempt will be
made to fetch remote statistics. If the statistics found are still
insufficient, then the local ANALYZE command will fall back to regular
row sampling and computing the statistics locally.
---
doc/src/sgml/postgres-fdw.sgml | 16 ++++
.../postgres_fdw/expected/postgres_fdw.out | 38 +++++++++
contrib/postgres_fdw/option.c | 5 ++
contrib/postgres_fdw/postgres_fdw.c | 80 ++++++++++++++++++-
contrib/postgres_fdw/sql/postgres_fdw.sql | 34 ++++++++
5 files changed, 171 insertions(+), 2 deletions(-)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 933b90de1d0..5d46f619a7c 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -383,6 +383,22 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ has no meaning if the foreign table has <literal>fetch_stats</literal>
+ disabled.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index cb84d453f4f..b3ec0ce1559 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -12678,6 +12678,44 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 5b7726800d0..2941ecbfb87 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -121,6 +121,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -283,6 +284,10 @@ InitPgFdwOptions(void)
{"fetch_stats", ForeignServerRelationId, false},
{"fetch_stats", ForeignTableRelationId, false},
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 86bdfc57c07..1ba743c7fb2 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -5390,6 +5390,36 @@ import_cleanup:
return ok;
}
+/*
+ * Analyze a remote table.
+ */
+static bool
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+ bool ok = true;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s",
+ quote_qualified_identifier(remote_schemaname, remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL ||
+ PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ pgfdw_report(WARNING, res, conn, buf.data);
+ ok = false;
+ }
+
+ PQclear(res);
+ pfree(buf.data);
+ return ok;
+}
+
/*
* Attempt to fetch remote relations stats.
*
@@ -5516,7 +5546,7 @@ fetch_remote_statistics(PGconn *conn,
const char *remote_relname,
int server_version_num, int natts,
const RemoteAttributeMapping * remattrmap,
- RemoteStatsResults * remstats)
+ bool remote_analyze, RemoteStatsResults * remstats)
{
char *column_list = NULL;
PGresult *attstats = NULL;
@@ -5568,6 +5598,35 @@ fetch_remote_statistics(PGconn *conn,
return true;
}
+ /*
+ * If remote_analyze is enabled, then we will try to analyze the table and
+ * then try again.
+ */
+ if (!remote_analyze)
+ goto fetch_remote_statistics_fail;
+
+ if (!analyze_remote_table(conn, remote_schemaname, remote_relname))
+ goto fetch_remote_statistics_fail;
+
+ PQclear(attstats);
+ attstats = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list);
+
+ if (attstats == NULL || PQntuples(attstats) == 0)
+ goto fetch_remote_statistics_fail;
+
+ PQclear(relstats);
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ if (relstats == NULL)
+ goto fetch_remote_statistics_fail;
+
+ /* Second attempt worked */
+ pfree(column_list);
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+
fetch_remote_statistics_fail:
ereport(WARNING,
errmsg("Failed to import statistics from remote table %s, "
@@ -5723,9 +5782,11 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
{
ForeignTable *table;
+ ForeignServer *server;
UserMapping *user;
PGconn *conn;
ListCell *lc;
+ bool remote_analyze = false;
int server_version_num = 0;
const char *schemaname = NULL;
const char *relname = NULL;
@@ -5740,12 +5801,25 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
user = GetUserMapping(GetUserId(), table->serverid);
conn = GetConnection(user, false, NULL);
server_version_num = PQserverVersion(conn);
schemaname = get_namespace_name(RelationGetNamespace(relation));
relname = RelationGetRelationName(relation);
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
foreach(lc, table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
@@ -5754,6 +5828,8 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
remote_schemaname = defGetString(def);
else if (strcmp(def->defname, "table_name") == 0)
remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
}
/*
@@ -5825,7 +5901,7 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
server_version_num, natts, remattrmap,
- &remstats);
+ remote_analyze, &remstats);
ReleaseConnection(conn);
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index ea4a2153190..ac284fba069 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -4398,6 +4398,40 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
--
2.52.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-22 10:15 Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 2 replies; 89+ messages in thread
From: Ashutosh Bapat @ 2026-01-22 10:15 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Thu, Jan 22, 2026 at 2:21 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>>
>> Changes in this release, aside from rebasing:
>>
>> - The generic analyze and fdw.h changes are in their own patch (0001) that ignores contrib/postgres_fdw entirely.
>> - The option for remote_analyze has been moved to its own patch (0003).
>> - The errors raised are now warnings, to ensure that we can always fall back to row sampling.
>> - All local attributes with attstatarget > 0 must get matching remote statistics or the import is considered a failure.
>> - The pg_restore_attribute_stats() call has been turned into a prepared statement, for clarity and some minor parsing savings.
>> - The calls to pg_restore_relation_stats() are parameterized, but not prepared as this is rarely called more than once.
>> - postgresStatisticsAreImportable will now disqualify a table if has extended statistics objects, because we can't compute those without a row sample.
>
Thanks Corey for breaking down these patches. It makes reviewing easier.
analyze_rel() and acquire_inherited_sample_rows() both call
fdwroutine->AnalyzeForeignTable() but only the first one uses the
statistics import facility. Is that intentional? Typical use case of
sharding will create a partitioned table with foreign tables as
partitions. The partitions will be analyzed by the second function.
Thus a big use case of postgres_fdw won't be able to use the import
statistics facility. That seems like a major drawback of this patch.
Thinking more about it, acquire_inherited_sample_rows() accumulates
the sample rows from the child tables and extracts statistics from
those rows and then updates corresponding pg_statistics rows. Doing
that through import statistics seems a bit tricky since we need to be
able to combine statistics from multiple relations. Can we do that?
There's an advantage if we can combine stats across multiple relations
- we don't have to sample children twice when analyzing the parent
without ONLY. Instead we could produce parent statistics by combining
statistics across children and the parent. To me this looks like
altogether a different beast just like partial aggregates.
It will be good to fix this drawback. If not, at least we should
figure out (plan/POC) how to deal with the child tables? We need to at
least document this drawback - the documentation in the current patch
reads as if all foreign tables will use this facility when available.
--
Best Wishes,
Ashutosh Bapat
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-22 11:29 Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
parent: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
1 sibling, 0 replies; 89+ messages in thread
From: Ashutosh Bapat @ 2026-01-22 11:29 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Thu, Jan 22, 2026 at 3:45 PM Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:
>
> On Thu, Jan 22, 2026 at 2:21 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> >>
> >> Changes in this release, aside from rebasing:
> >>
> >> - The generic analyze and fdw.h changes are in their own patch (0001) that ignores contrib/postgres_fdw entirely.
> >> - The option for remote_analyze has been moved to its own patch (0003).
> >> - The errors raised are now warnings, to ensure that we can always fall back to row sampling.
> >> - All local attributes with attstatarget > 0 must get matching remote statistics or the import is considered a failure.
> >> - The pg_restore_attribute_stats() call has been turned into a prepared statement, for clarity and some minor parsing savings.
> >> - The calls to pg_restore_relation_stats() are parameterized, but not prepared as this is rarely called more than once.
> >> - postgresStatisticsAreImportable will now disqualify a table if has extended statistics objects, because we can't compute those without a row sample.
> >
The patches fail to build the document. Attached diff fixes that.
--
Best Wishes,
Ashutosh Bapat
Attachments:
doc_errors_fix.diff.nocibot (application/octet-stream, 880B) download
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-22 22:20 Corey Huinker <corey.huinker@gmail.com>
parent: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-01-22 22:20 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Thu, Jan 22, 2026 at 5:16 AM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
wrote:
> On Thu, Jan 22, 2026 at 2:21 AM Corey Huinker <corey.huinker@gmail.com>
> wrote:
> >>
> >> Changes in this release, aside from rebasing:
> >>
> >> - The generic analyze and fdw.h changes are in their own patch (0001)
> that ignores contrib/postgres_fdw entirely.
> >> - The option for remote_analyze has been moved to its own patch (0003).
> >> - The errors raised are now warnings, to ensure that we can always fall
> back to row sampling.
> >> - All local attributes with attstatarget > 0 must get matching remote
> statistics or the import is considered a failure.
> >> - The pg_restore_attribute_stats() call has been turned into a prepared
> statement, for clarity and some minor parsing savings.
> >> - The calls to pg_restore_relation_stats() are parameterized, but not
> prepared as this is rarely called more than once.
> >> - postgresStatisticsAreImportable will now disqualify a table if has
> extended statistics objects, because we can't compute those without a row
> sample.
> >
>
> Thanks Corey for breaking down these patches. It makes reviewing easier.
>
> analyze_rel() and acquire_inherited_sample_rows() both call
> fdwroutine->AnalyzeForeignTable() but only the first one uses the
> statistics import facility. Is that intentional? Typical use case of
> sharding will create a partitioned table with foreign tables as
> partitions. The partitions will be analyzed by the second function.
> Thus a big use case of postgres_fdw won't be able to use the import
> statistics facility. That seems like a major drawback of this patch.
> Thinking more about it, acquire_inherited_sample_rows() accumulates
> the sample rows from the child tables and extracts statistics from
> those rows and then updates corresponding pg_statistics rows. Doing
> that through import statistics seems a bit tricky since we need to be
> able to combine statistics from multiple relations. Can we do that?
>
We can't synthesize sample rows from imported statistics, no.
> There's an advantage if we can combine stats across multiple relations
> - we don't have to sample children twice when analyzing the parent
> without ONLY. Instead we could produce parent statistics by combining
> statistics across children and the parent. To me this looks like
> altogether a different beast just like partial aggregates.
>
I think this patch is only ever going to get us out of 1 of the 2 samples,
which isn't ideal but it is a savings.
>
> It will be good to fix this drawback. If not, at least we should
> figure out (plan/POC) how to deal with the child tables? We need to at
> least document this drawback - the documentation in the current patch
> reads as if all foreign tables will use this facility when available.
>
Yes, we will have to note the limitation. I have made that note, as well
as the documentation fix attached.
Attachments: download all (3 files, .tar.gz)
v12-0003-Add-remote_analyze-to-postgres_fdw-remote-statis.patch (text/x-patch, 10.8K) download
From 312db45e3b04d15a31ff1de11d704051d8ae1b7d Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:33:53 -0500
Subject: [PATCH v12 3/3] Add remote_analyze to postgres_fdw remote statistics
fetching.
This is accomplished through a new option, remote_analyze, which is
available at the server level and table level. The default value is
false.
If remote_analyze is enabled, and if the first attempt to fetch remote
statistics did not fetch attribute statistics for every local table
column, then an attempt will be made to ANALYZE the remote table. If
that remote ANALYZE succeeds, then a second and final attempt will be
made to fetch remote statistics. If the statistics found are still
insufficient, then the local ANALYZE command will fall back to regular
row sampling and computing the statistics locally.
---
doc/src/sgml/postgres-fdw.sgml | 16 ++++
.../postgres_fdw/expected/postgres_fdw.out | 38 +++++++++
contrib/postgres_fdw/option.c | 5 ++
contrib/postgres_fdw/postgres_fdw.c | 80 ++++++++++++++++++-
contrib/postgres_fdw/sql/postgres_fdw.sql | 34 ++++++++
5 files changed, 171 insertions(+), 2 deletions(-)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index ee1cfbb385a..45692942a6b 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -387,6 +387,22 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ has no meaning if the foreign table has <literal>fetch_stats</literal>
+ disabled.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index cb84d453f4f..b3ec0ce1559 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -12678,6 +12678,44 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 5b7726800d0..2941ecbfb87 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -121,6 +121,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -283,6 +284,10 @@ InitPgFdwOptions(void)
{"fetch_stats", ForeignServerRelationId, false},
{"fetch_stats", ForeignTableRelationId, false},
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 86bdfc57c07..1ba743c7fb2 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -5390,6 +5390,36 @@ import_cleanup:
return ok;
}
+/*
+ * Analyze a remote table.
+ */
+static bool
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+ bool ok = true;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s",
+ quote_qualified_identifier(remote_schemaname, remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL ||
+ PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ pgfdw_report(WARNING, res, conn, buf.data);
+ ok = false;
+ }
+
+ PQclear(res);
+ pfree(buf.data);
+ return ok;
+}
+
/*
* Attempt to fetch remote relations stats.
*
@@ -5516,7 +5546,7 @@ fetch_remote_statistics(PGconn *conn,
const char *remote_relname,
int server_version_num, int natts,
const RemoteAttributeMapping * remattrmap,
- RemoteStatsResults * remstats)
+ bool remote_analyze, RemoteStatsResults * remstats)
{
char *column_list = NULL;
PGresult *attstats = NULL;
@@ -5568,6 +5598,35 @@ fetch_remote_statistics(PGconn *conn,
return true;
}
+ /*
+ * If remote_analyze is enabled, then we will try to analyze the table and
+ * then try again.
+ */
+ if (!remote_analyze)
+ goto fetch_remote_statistics_fail;
+
+ if (!analyze_remote_table(conn, remote_schemaname, remote_relname))
+ goto fetch_remote_statistics_fail;
+
+ PQclear(attstats);
+ attstats = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list);
+
+ if (attstats == NULL || PQntuples(attstats) == 0)
+ goto fetch_remote_statistics_fail;
+
+ PQclear(relstats);
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ if (relstats == NULL)
+ goto fetch_remote_statistics_fail;
+
+ /* Second attempt worked */
+ pfree(column_list);
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+
fetch_remote_statistics_fail:
ereport(WARNING,
errmsg("Failed to import statistics from remote table %s, "
@@ -5723,9 +5782,11 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
{
ForeignTable *table;
+ ForeignServer *server;
UserMapping *user;
PGconn *conn;
ListCell *lc;
+ bool remote_analyze = false;
int server_version_num = 0;
const char *schemaname = NULL;
const char *relname = NULL;
@@ -5740,12 +5801,25 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
user = GetUserMapping(GetUserId(), table->serverid);
conn = GetConnection(user, false, NULL);
server_version_num = PQserverVersion(conn);
schemaname = get_namespace_name(RelationGetNamespace(relation));
relname = RelationGetRelationName(relation);
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
foreach(lc, table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
@@ -5754,6 +5828,8 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
remote_schemaname = defGetString(def);
else if (strcmp(def->defname, "table_name") == 0)
remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
}
/*
@@ -5825,7 +5901,7 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
server_version_num, natts, remattrmap,
- &remstats);
+ remote_analyze, &remstats);
ReleaseConnection(conn);
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index ea4a2153190..ac284fba069 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -4398,6 +4398,40 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
--
2.52.0
v12-0002-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 36.4K) download
From ddb04632094a17f79182c2e565826b2b57fa5a84 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:06:05 -0500
Subject: [PATCH v12 2/3] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via a new option, fetch_stats, which is available at the
server level and table level. The global default is true, but this can
be overriden by at the server level, which in turn can be overridden at
the table level.
If fetch_stats is true, and the remote table is an actual table or
materialized view that can hold statistics, and the local table does not
have any extended statistics objects built upon it, then the remote
database will first be queried for relation statistics and attribute
statistics similar to the method used in pg_dump.
If there are remote statistics for all of the columns in the local
table, then those statistics will be imported using
pg_restore_relation_statistics and pg_restore_attribute_statistics
functions similar to the way pg_restore uses them.
If fetch_stats is false, or if the fetched statistics were missing or
otherwise inadequate, then the ANALYZE operation will issue a WARNING
and then fall back to regular table sampling to generate local
statistics.
---
doc/src/sgml/postgres-fdw.sgml | 25 +-
.../postgres_fdw/expected/postgres_fdw.out | 15 +-
contrib/postgres_fdw/option.c | 5 +
contrib/postgres_fdw/postgres_fdw.c | 912 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 13 +-
5 files changed, 967 insertions(+), 3 deletions(-)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 9b032fbf675..ee1cfbb385a 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,29 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</function> and
+ <function>pg_restore_attribute_stats</function>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views). If the foreign table is a partition
+ of a partitioned table, analyzing the partitioned table will still
+ result in row sampling on the foreign table regardless of this setting,
+ though direct analysis of the foreign table would have attempted to
+ fetch remote statistics first.
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 6066510c7c0..cb84d453f4f 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4551,7 +4552,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11462,6 +11464,12 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+WARNING: Failed to import statistics from remote table public.base_tbl2, will try to ANALYZE with regular row sampling.
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11568,6 +11576,11 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+WARNING: Failed to import statistics from remote table public.base_tbl3, will try to ANALYZE with regular row sampling.
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..5b7726800d0 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +279,10 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 3572689e33b..86bdfc57c07 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -18,10 +18,13 @@
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_opfamily.h"
+#include "catalog/pg_statistic_ext.h"
#include "commands/defrem.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -42,12 +45,14 @@
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
+#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
+#include "utils/syscache.h"
PG_MODULE_MAGIC_EXT(
.name = "postgres_fdw",
@@ -317,6 +322,20 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ char remote_attname[NAMEDATALEN];
+ AttrNumber local_attnum;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -402,6 +421,10 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresStatisticsAreImportable(Relation relation);
+static bool postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +569,188 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns
+{
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_NUM_FIELDS,
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+static const char *attstats_query_default =
+"SELECT s.attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\"";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns
+{
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS,
+};
+
+static const char *relimport_sql =
+"SELECT pg_catalog.pg_restore_relation_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'relpages', $4::integer,\n"
+"\t'reltuples', $5::real)";
+
+enum RelImportSqlArgs
+{
+ RELIMPORT_SQL_VERSION = 0,
+ RELIMPORT_SQL_SCHEMANAME,
+ RELIMPORT_SQL_RELNAME,
+ RELIMPORT_SQL_RELPAGES,
+ RELIMPORT_SQL_RELTUPLES,
+ RELIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid relimport_argtypes[RELIMPORT_SQL_NUM_FIELDS] = {
+INT4OID, TEXTOID, TEXTOID, TEXTOID, TEXTOID,};
+
+static const char *attimport_sql =
+"SELECT pg_catalog.pg_restore_attribute_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'attnum', $4,\n"
+"\t'inherited', false::boolean,\n"
+"\t'null_frac', $5::real,\n"
+"\t'avg_width', $6::integer,\n"
+"\t'n_distinct', $7::real,\n"
+"\t'most_common_vals', $8,\n"
+"\t'most_common_freqs', $9::real[],\n"
+"\t'histogram_bounds', $10,\n"
+"\t'correlation', $11::real,\n"
+"\t'most_common_elems', $12,\n"
+"\t'most_common_elem_freqs', $13::real[],\n"
+"\t'elem_count_histogram', $14::real[],\n"
+"\t'range_length_histogram', $15,\n"
+"\t'range_empty_frac', $16::real,\n"
+"\t'range_bounds_histogram', $17)";
+
+enum AttImportSqlArgs
+{
+ ATTIMPORT_SQL_VERSION = 0,
+ ATTIMPORT_SQL_SCHEMANAME,
+ ATTIMPORT_SQL_RELNAME,
+ ATTIMPORT_SQL_ATTNUM,
+ ATTIMPORT_SQL_NULL_FRAC,
+ ATTIMPORT_SQL_AVG_WIDTH,
+ ATTIMPORT_SQL_N_DISTINCT,
+ ATTIMPORT_SQL_MOST_COMMON_VALS,
+ ATTIMPORT_SQL_MOST_COMMON_FREQS,
+ ATTIMPORT_SQL_HISTOGRAM_BOUNDS,
+ ATTIMPORT_SQL_CORRELATION,
+ ATTIMPORT_SQL_MOST_COMMON_ELEMS,
+ ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS,
+ ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_EMPTY_FRAC,
+ ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM,
+ ATTIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid attimport_argtypes[ATTIMPORT_SQL_NUM_FIELDS] = {
+ INT4OID, TEXTOID, TEXTOID, INT2OID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+TEXTOID,};
+
+/* Pairs AttStatsColumns:AttImportSqlArgs Map */
+typedef struct
+{
+ enum AttStatsColumns res_field;
+ enum AttImportSqlArgs arg_num;
+} AttrResultArgMap;
+
+/*
+ * The mapping of attribute stats query columns to the positional arguments in
+ * the prepared pg_restore_attribute_stats() statement.
+ */
+#define NUM_MAPPED_ATTIMPORT_ARGS 13
+static const AttrResultArgMap attr_result_arg_map[NUM_MAPPED_ATTIMPORT_ARGS] = {
+ {ATTSTATS_NULL_FRAC, ATTIMPORT_SQL_NULL_FRAC},
+ {ATTSTATS_AVG_WIDTH, ATTIMPORT_SQL_AVG_WIDTH},
+ {ATTSTATS_N_DISTINCT, ATTIMPORT_SQL_N_DISTINCT},
+ {ATTSTATS_MOST_COMMON_VALS, ATTIMPORT_SQL_MOST_COMMON_VALS},
+ {ATTSTATS_MOST_COMMON_FREQS, ATTIMPORT_SQL_MOST_COMMON_FREQS},
+ {ATTSTATS_HISTOGRAM_BOUNDS, ATTIMPORT_SQL_HISTOGRAM_BOUNDS},
+ {ATTSTATS_CORRELATION, ATTIMPORT_SQL_CORRELATION},
+ {ATTSTATS_MOST_COMMON_ELEMS, ATTIMPORT_SQL_MOST_COMMON_ELEMS},
+ {ATTSTATS_MOST_COMMON_ELEM_FREQS, ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS},
+ {ATTSTATS_ELEM_COUNT_HISTOGRAM, ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM},
+ {ATTSTATS_RANGE_LENGTH_HISTOGRAM, ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM},
+ {ATTSTATS_RANGE_EMPTY_FRAC, ATTIMPORT_SQL_RANGE_EMPTY_FRAC},
+ {ATTSTATS_RANGE_BOUNDS_HISTOGRAM, ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM},
+};
+
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +800,8 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->StatisticsAreImportable = postgresStatisticsAreImportable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5142,711 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Move a string value from a result set to a Text value of a Datum array.
+ */
+static void
+map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls)
+{
+ if (PQgetisnull(res, row, field))
+ {
+ values[arg] = (Datum) 0;
+ nulls[arg] = 'n';
+ }
+ else
+ {
+ const char *s = PQgetvalue(res, row, field);
+
+ values[arg] = CStringGetTextDatum(s);
+ nulls[arg] = ' ';
+ }
+}
+
+/*
+ * Check the 1x1 result set of a pg_restore_*_stats() command for success.
+ */
+static bool
+import_spi_query_ok(int spirc)
+{
+ char *s;
+ bool ok;
+
+ if (spirc != SPI_OK_SELECT
+ || SPI_tuptable == NULL
+ || SPI_processed != 1)
+ return false;
+
+ s = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
+
+ ok = (s != NULL && s[0] == 't' && s[1] == '\0');
+ pfree(s);
+
+ return ok;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static bool
+import_fetched_statistics(const char *schemaname, const char *relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping * remattrmap,
+ RemoteStatsResults * remstats)
+{
+ SPIPlanPtr plan = NULL;
+ PGresult *res = remstats->att;
+ int spirc;
+ int mapidx = 0;
+ Datum values[ATTIMPORT_SQL_NUM_FIELDS];
+ char nulls[ATTIMPORT_SQL_NUM_FIELDS];
+ bool ok = false;
+
+ /* Assign all the invariant parameters */
+ values[ATTIMPORT_SQL_VERSION] = Int32GetDatum(server_version_num);
+ nulls[ATTIMPORT_SQL_VERSION] = ' ';
+
+ values[ATTIMPORT_SQL_SCHEMANAME] = CStringGetTextDatum(schemaname);
+ nulls[ATTIMPORT_SQL_SCHEMANAME] = ' ';
+
+ values[ATTIMPORT_SQL_RELNAME] = CStringGetTextDatum(relname);
+ nulls[ATTIMPORT_SQL_RELNAME] = ' ';
+
+ nulls[ATTIMPORT_SQL_ATTNUM] = ' ';
+
+ SPI_connect();
+
+ plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+
+ if (plan == NULL || SPI_result < 0)
+ {
+ ereport(WARNING,
+ errmsg("Import attribute statistics prepare failed %s "
+ "with error code %d",
+ attimport_sql, SPI_result));
+ goto import_cleanup;
+ }
+
+ /*
+ * Match result set rows to local attnums.
+ *
+ * Every row of the result should be an attribute that we specifically
+ * filtered for, so every row should have at least one match in the
+ * RemoteAttributeMapping, which is also ordered by attname, so we only
+ * need to walk that array once.
+ *
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ for (int row = 0; row < PQntuples(remstats->att); row++)
+ {
+ char *remote_attname;
+ bool match_found = false;
+ int cmp = 0;
+
+ if (PQgetisnull(res, row, ATTSTATS_ATTNAME))
+ {
+ ereport(WARNING,
+ errmsg("Remote statistics returned a row with NULL attribute name"));
+ goto import_cleanup;
+ }
+
+ remote_attname = PQgetvalue(res, row, ATTSTATS_ATTNAME);
+
+ /*
+ * Handle a series of matching elements in the mapping.
+ *
+ * We exit this loop in the following ways:
+ *
+ * 1. Having found at least match and exhausting the list. We're done.
+ * 2. Having found at least match and ending on a <, advance. 3.
+ * Having found at least match and ending on a >, bad sort. 4. No
+ * match, list exhausted. 5. No match, <. 6. No match, >.
+ *
+ */
+ for (; mapidx < natts; mapidx++)
+ {
+ cmp = strcmp(remote_attname, remattrmap[mapidx].remote_attname);
+
+ /* Stop scanning on the first non-match */
+ if (cmp != 0)
+ break;
+
+ match_found = true;
+ values[ATTIMPORT_SQL_ATTNUM] =
+ Int16GetDatum(remattrmap[mapidx].local_attnum);
+
+ /* Loop through all mappable columns->arguments */
+ for (int i = 0; i < NUM_MAPPED_ATTIMPORT_ARGS; i++)
+ map_field_to_arg(res, row,
+ attr_result_arg_map[i].res_field,
+ attr_result_arg_map[i].arg_num,
+ values, nulls);
+
+ spirc = SPI_execute_plan(plan, values, nulls, false, 0);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("Attribute statistics import failed %s",
+ attimport_sql));
+ goto import_cleanup;
+ }
+ }
+
+ /* We found a match, move onto the next result. */
+ if (match_found)
+ continue;
+
+ /*
+ * If no match and we ended on a <, then the mapidx will never find a
+ * match, so stop now and let the cleanup report the error.
+ */
+ if (cmp > 0)
+ break;
+
+ /*
+ * Otherwise this result found no matching mapidx, which should only
+ * happen if the results are out of sort or the wrong query was
+ * executed.
+ */
+ if (cmp < 0)
+ {
+ ereport(WARNING,
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+ goto import_cleanup;
+ }
+ }
+
+ /* Look for a mapidx with no possible matching result */
+ if (mapidx < natts)
+ {
+ ereport(WARNING,
+ errmsg("No remote statistics found for %s of %s.",
+ quote_identifier(remattrmap[mapidx].remote_attname),
+ quote_qualified_identifier(schemaname, relname)));
+ goto import_cleanup;
+ }
+
+ /*
+ * Import relstats.
+ *
+ * Import relation stats. We only perform this once, so there is no point
+ * in preparing the statement.
+ *
+ * We can re-use the values/nulls because the number of parameters is less
+ * and the first three params are the same as attstats_import.
+ */
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELPAGES,
+ RELIMPORT_SQL_RELPAGES, values, nulls);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELTUPLES,
+ RELIMPORT_SQL_RELTUPLES, values, nulls);
+
+ spirc = SPI_execute_with_args(relimport_sql, RELIMPORT_SQL_NUM_FIELDS,
+ (Oid *) relimport_argtypes,
+ values, nulls, false, 1);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("Relation statistics import failed %s",
+ relimport_sql));
+ goto import_cleanup;
+ }
+
+ ok = true;
+
+import_cleanup:
+ if (plan)
+ SPI_freeplan(plan);
+ SPI_finish();
+ return ok;
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ *
+ * Verify that the result is of the proper shape, return NULL otherwise.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname)
+{
+ const char *params[2] = {remote_schemaname, remote_relname};
+
+ /*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case).
+ *
+ * We can ignore this change, because if the remote table wasn't analyzed,
+ * then it would have no attribute stats, and thus we wouldn't have stats
+ * that we would try to import. So we can take the reltuples value as-is.
+ */
+ const char *sql = "SELECT c.relkind, c.relpages, c.reltuples "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n "
+ "ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+ PGresult *res = NULL;
+
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ {
+ pgfdw_report(WARNING, NULL, conn, sql);
+ return NULL;
+ }
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS
+ || PQgetisnull(res, 0, RELSTATS_RELKIND))
+ {
+ pgfdw_report(WARNING, res, conn, sql);
+ PQclear(res);
+ return NULL;
+ }
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ *
+ * Verify that the result is of the proper shape, return NULL otherwise. Note
+ * that we do not verify the row count.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list)
+{
+ const char *params[3] = {remote_schemaname, remote_relname, column_list};
+ int version = PQserverVersion(conn);
+ const char *sql;
+ PGresult *res;
+
+ if (version >= 170000)
+ sql = attstats_query_17;
+ else if (version >= 90200)
+ sql = attstats_query_9_2;
+ else if (version >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ {
+ pgfdw_report(WARNING, NULL, conn, sql);
+ return NULL;
+ }
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(WARNING, res, conn, sql);
+ PQclear(res);
+ return NULL;
+ }
+
+ return res;
+}
+
+/*
+ * Make a '{column,list,array}'.
+ */
+static char *
+get_column_list(int natts, const RemoteAttributeMapping * remattrmap)
+{
+ StringInfoData column_list;
+
+ initStringInfo(&column_list);
+ appendStringInfoChar(&column_list, '{');
+ for (int i = 0; i < natts; i++)
+ {
+ if (i > 0)
+ appendStringInfoChar(&column_list, ',');
+ appendStringInfoString(&column_list,
+ quote_identifier(remattrmap[i].remote_attname));
+ }
+ appendStringInfoChar(&column_list, '}');
+
+ return column_list.data;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static bool
+fetch_remote_statistics(PGconn *conn,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping * remattrmap,
+ RemoteStatsResults * remstats)
+{
+ char *column_list = NULL;
+ PGresult *attstats = NULL;
+ PGresult *relstats = NULL;
+
+ char relkind;
+
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ if (relstats == NULL)
+ goto fetch_remote_statistics_fail;
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
+ * can't support a foreign table.
+ */
+ relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
+
+ switch (relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ goto fetch_remote_statistics_fail;
+ }
+
+ column_list = get_column_list(natts, remattrmap);
+
+ /* See if it actually has any attribute stats. */
+ attstats = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list);
+
+ /*
+ * If we got attribute statistics results, then we are done with fetching.
+ */
+ if (attstats != NULL
+ && PQntuples(attstats) > 0)
+ {
+ pfree(column_list);
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+ }
+
+fetch_remote_statistics_fail:
+ ereport(WARNING,
+ errmsg("Failed to import statistics from remote table %s, "
+ "will try to ANALYZE with regular row sampling.",
+ quote_qualified_identifier(remote_schemaname,
+ remote_relname)));
+ PQclear(attstats);
+ PQclear(relstats);
+ if (column_list)
+ pfree(column_list);
+ return false;
+}
+
+/*
+ * Test if the relation has extended statistics objects.
+ */
+static bool
+table_has_extended_stats(Relation relation)
+{
+ Relation pg_statext;
+ SysScanDesc scan;
+ ScanKeyData skey;
+ bool found;
+
+ pg_statext = table_open(StatisticExtRelationId, RowExclusiveLock);
+
+ /*
+ * Prepare to scan pg_statistic_ext for entries having stxrelid = this
+ * rel.
+ */
+ ScanKeyInit(&skey,
+ Anum_pg_statistic_ext_stxrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(relation)));
+
+ scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
+ NULL, 1, &skey);
+
+ found = (systable_getnext(scan) != NULL);
+
+ systable_endscan(scan);
+
+ table_close(pg_statext, RowExclusiveLock);
+
+ return found;
+}
+
+static bool
+postgresStatisticsAreImportable(Relation relation)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ ListCell *lc;
+ bool fetch_stats = true;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ /*
+ * Additional checks that can disqualify a table from importing stats.
+ */
+ if (fetch_stats)
+ {
+ /*
+ * We can't compute extended stats from the column stats, for that we
+ * need a table sample.
+ */
+ if (table_has_extended_stats(relation))
+ {
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("Cannot import statistics for foreign table \"%s\" "
+ "because it has extended statistics objects.",
+ RelationGetRelationName(relation)));
+ fetch_stats = false;
+ }
+ }
+
+ return fetch_stats;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Fetch attstattarget from a pg_attribute tuple.
+ */
+static int16
+get_attstattarget(Relation relation, AttrNumber attnum)
+{
+ HeapTuple atttuple;
+ bool isnull;
+ Datum dat;
+ int16 attstattarget;
+ Oid relid = RelationGetRelid(relation);
+
+ atttuple = SearchSysCache2(ATTNUM,
+ ObjectIdGetDatum(relid),
+ Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, relid);
+ dat = SysCacheGetAttr(ATTNUM, atttuple,
+ Anum_pg_attribute_attstattarget,
+ &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ return attstattarget;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static bool
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+
+ ForeignTable *table;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int natts = 0;
+ bool ok = false;
+
+ RemoteAttributeMapping *remattrmap;
+
+ RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ }
+
+ /*
+ * Assume the relation/schema names are the same as the local name unless
+ * the options tell us otherwise.
+ */
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ /*
+ * Build attnum/remote-attname list.
+ *
+ */
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *attname;
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+
+ /* Ignore dropped columns. */
+ if (attr->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (attr->attgenerated)
+ continue;
+
+ attname = NameStr(attr->attname);
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ attnum = attr->attnum;
+
+ /* Ignore if attstatarget is 0 */
+ if (get_attstattarget(relation, attnum) == 0)
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_colname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].remote_attname, remote_colname, NAMEDATALEN);
+ natts++;
+ }
+
+ /* Sort mapping by remote attribute name */
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
+ server_version_num, natts, remattrmap,
+ &remstats);
+
+ ReleaseConnection(conn);
+
+ if (ok)
+ {
+ Assert(remstats.rel != NULL);
+ Assert(PQnfields(remstats.rel) == RELSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.rel) == 1);
+ Assert(remstats.att != NULL);
+ Assert(PQnfields(remstats.att) == ATTSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.att) >= 1);
+ ok = import_fetched_statistics(schemaname, relname, server_version_num,
+ natts, remattrmap, &remstats);
+ }
+
+ pfree(remattrmap);
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+ return ok;
+}
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 4f7ab2ed0ac..ea4a2153190 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1286,7 +1287,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3903,6 +3905,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3940,6 +3947,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
--
2.52.0
v12-0001-Add-FDW-functions-for-importing-optimizer-statis.patch (text/x-patch, 5.0K) download
From a0b389f2cc7590cf247995b9b350bc3755a439cd Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 16:39:45 -0500
Subject: [PATCH v12 1/3] Add FDW functions for importing optimizer statistics.
Add the the function StatisticsAreImportable which is used as a
lightweight preliminary scan to determine if the remote table could
potentially have statistics that could be imported instead of fetching a
row sample from the remote table, which can be expensive.
Also add the function ImportStatistics which attempts to actually fetch
those statistics from the remote server, and if successful import them
into the local statistics catalog.
---
src/include/foreign/fdwapi.h | 8 ++++
src/backend/commands/analyze.c | 68 ++++++++++++++++++++++++----------
2 files changed, 56 insertions(+), 20 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..59beeae4f45 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef bool (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +261,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index a483424152c..c84367461fb 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -113,6 +113,9 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool can_import_stats = false;
+ bool stats_imported = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -195,27 +198,16 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
- {
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
- }
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ can_import_stats = true;
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
{
@@ -247,10 +239,46 @@ analyze_rel(Oid relid, RangeVar *relation,
PROGRESS_ANALYZE_STARTED_BY_MANUAL);
/*
- * Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * If this table can import statistics, attempt to do so.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (can_import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ stats_imported = fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+
+ /*
+ * Foreign tables that were not able to import stats will resort to
+ * regular sampling.
+ */
+ if ((onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
+ && !stats_imported)
+ {
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
+ }
+
+ /*
+ * Do the normal non-recursive ANALYZE. We can skip this for partitioned
+ * tables and foreign tables that successfully imported statistics.
+ */
+ if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ && !stats_imported)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
base-commit: 69f98fce5bfb82260c66bdae88b6293146cf79ec
--
2.52.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-23 15:43 Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Ashutosh Bapat @ 2026-01-23 15:43 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Fri, Jan 23, 2026 at 3:50 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>
> On Thu, Jan 22, 2026 at 5:16 AM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com> wrote:
>>
>> On Thu, Jan 22, 2026 at 2:21 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>> >>
>> >> Changes in this release, aside from rebasing:
>> >>
>> >> - The generic analyze and fdw.h changes are in their own patch (0001) that ignores contrib/postgres_fdw entirely.
>> >> - The option for remote_analyze has been moved to its own patch (0003).
>> >> - The errors raised are now warnings, to ensure that we can always fall back to row sampling.
>> >> - All local attributes with attstatarget > 0 must get matching remote statistics or the import is considered a failure.
>> >> - The pg_restore_attribute_stats() call has been turned into a prepared statement, for clarity and some minor parsing savings.
>> >> - The calls to pg_restore_relation_stats() are parameterized, but not prepared as this is rarely called more than once.
>> >> - postgresStatisticsAreImportable will now disqualify a table if has extended statistics objects, because we can't compute those without a row sample.
>> >
>>
>> Thanks Corey for breaking down these patches. It makes reviewing easier.
>>
>> analyze_rel() and acquire_inherited_sample_rows() both call
>> fdwroutine->AnalyzeForeignTable() but only the first one uses the
>> statistics import facility. Is that intentional? Typical use case of
>> sharding will create a partitioned table with foreign tables as
>> partitions. The partitions will be analyzed by the second function.
>> Thus a big use case of postgres_fdw won't be able to use the import
>> statistics facility. That seems like a major drawback of this patch.
>> Thinking more about it, acquire_inherited_sample_rows() accumulates
>> the sample rows from the child tables and extracts statistics from
>> those rows and then updates corresponding pg_statistics rows. Doing
>> that through import statistics seems a bit tricky since we need to be
>> able to combine statistics from multiple relations. Can we do that?
>
>
> We can't synthesize sample rows from imported statistics, no.
>
>>
>> There's an advantage if we can combine stats across multiple relations
>> - we don't have to sample children twice when analyzing the parent
>> without ONLY. Instead we could produce parent statistics by combining
>> statistics across children and the parent. To me this looks like
>> altogether a different beast just like partial aggregates.
>
>
> I think this patch is only ever going to get us out of 1 of the 2 samples, which isn't ideal but it is a savings.
>
I am not suggesting to synthesize sample rows. Calculate the
statistics of the parent table from that of its children.
>>
>>
>> It will be good to fix this drawback. If not, at least we should
>> figure out (plan/POC) how to deal with the child tables? We need to at
>> least document this drawback - the documentation in the current patch
>> reads as if all foreign tables will use this facility when available.
>
>
> Yes, we will have to note the limitation. I have made that note, as well as the documentation fix attached.
The note just mentions partition table but the limitation applies to
any foreign child table.
--
Best Wishes,
Ashutosh Bapat
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-23 17:15 Corey Huinker <corey.huinker@gmail.com>
parent: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-01-23 17:15 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> >> There's an advantage if we can combine stats across multiple relations
> >> - we don't have to sample children twice when analyzing the parent
> >> without ONLY. Instead we could produce parent statistics by combining
> >> statistics across children and the parent. To me this looks like
> >> altogether a different beast just like partial aggregates.
> >
> >
> > I think this patch is only ever going to get us out of 1 of the 2
> samples, which isn't ideal but it is a savings.
> >
>
> I am not suggesting to synthesize sample rows. Calculate the
> statistics of the parent table from that of its children.
>
I'm not sure we can actually do that. The functions that compute the
statistics are all based off of row samples, not already computed
statistics. I don't think we can synthesize a rowsample from the imported
statistics, at least not accurately. If I'm misunderstanding what you're
suggesting, please correct me.
> The note just mentions partition table but the limitation applies to
> any foreign child table.
>
Noted. Will fix in next revision.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-27 05:47 Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Ashutosh Bapat @ 2026-01-27 05:47 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Fri, Jan 23, 2026 at 10:45 PM Corey Huinker <corey.huinker@gmail.com> wrote:
>>
>> >> There's an advantage if we can combine stats across multiple relations
>> >> - we don't have to sample children twice when analyzing the parent
>> >> without ONLY. Instead we could produce parent statistics by combining
>> >> statistics across children and the parent. To me this looks like
>> >> altogether a different beast just like partial aggregates.
>> >
>> >
>> > I think this patch is only ever going to get us out of 1 of the 2 samples, which isn't ideal but it is a savings.
>> >
>>
>> I am not suggesting to synthesize sample rows. Calculate the
>> statistics of the parent table from that of its children.
>
>
> I'm not sure we can actually do that. The functions that compute the statistics are all based off of row samples, not already computed statistics. I don't think we can synthesize a rowsample from the imported statistics, at least not accurately. If I'm misunderstanding what you're suggesting, please correct me.
I am comparing the calculation of statistics to the calculation of
aggregates. We have code to compute aggregates on a partitioned table
from the partial aggregates computed from the individual partitions.
(Even though I am mentioning the partitioned table, the technique can
be used for an inheritance hierarchy.) Similarly if we could come up
with a representation of partial statistics, we could get partial
statistics computed for the children (and the parent in
non-partitioned inheritance). Use the partial statistics to compute
the statistics for the parent without the need to synthesize row
samples from the children. I haven't looked at all the kinds of
statistics to see whether this is feasible.
--
Best Wishes,
Ashutosh Bapat
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-27 08:04 Corey Huinker <corey.huinker@gmail.com>
parent: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-01-27 08:04 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> > I'm not sure we can actually do that. The functions that compute the
> statistics are all based off of row samples, not already computed
> statistics. I don't think we can synthesize a rowsample from the imported
> statistics, at least not accurately. If I'm misunderstanding what you're
> suggesting, please correct me.
>
> I am comparing the calculation of statistics to the calculation of
> aggregates. We have code to compute aggregates on a partitioned table
> from the partial aggregates computed from the individual partitions.
> (Even though I am mentioning the partitioned table, the technique can
> be used for an inheritance hierarchy.) Similarly if we could come up
with a representation of partial statistics, we could get partial
> statistics computed for the children (and the parent in
> non-partitioned inheritance). Use the partial statistics to compute
> the statistics for the parent without the need to synthesize row
> samples from the children. I haven't looked at all the kinds of
> statistics to see whether this is feasible.
>
We're limited to the existing data from pg_class and the security-barrier
view pg_stats. We also have pg_stats_ext and pg_stats_ext_exprs as well,
but those are for extended stats objects, which aren't useful to us in this
context.
I've been a part of some research into the feasibility of caching the row
samples fetched, allowing the planner to generate on-the-fly statistics for
OLAP queries. If we ever got that functionality, we'd need a means of
exposing those row samples externally, and even then we'd have to wait for
the remote postgresql server to have that feature. So for now we are
limited to what pg_class and pg_stats tell us.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-29 11:03 Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Ashutosh Bapat @ 2026-01-29 11:03 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Tue, Jan 27, 2026 at 1:35 PM Corey Huinker <corey.huinker@gmail.com> wrote:
>>
>> > I'm not sure we can actually do that. The functions that compute the statistics are all based off of row samples, not already computed statistics. I don't think we can synthesize a rowsample from the imported statistics, at least not accurately. If I'm misunderstanding what you're suggesting, please correct me.
>>
>> I am comparing the calculation of statistics to the calculation of
>> aggregates. We have code to compute aggregates on a partitioned table
>> from the partial aggregates computed from the individual partitions.
>> (Even though I am mentioning the partitioned table, the technique can
>> be used for an inheritance hierarchy.) Similarly if we could come up
>>
>> with a representation of partial statistics, we could get partial
>> statistics computed for the children (and the parent in
>> non-partitioned inheritance). Use the partial statistics to compute
>> the statistics for the parent without the need to synthesize row
>> samples from the children. I haven't looked at all the kinds of
>> statistics to see whether this is feasible.
>
>
> We're limited to the existing data from pg_class and the security-barrier view pg_stats. We also have pg_stats_ext and pg_stats_ext_exprs as well, but those are for extended stats objects, which aren't useful to us in this context.
>
> I've been a part of some research into the feasibility of caching the row samples fetched, allowing the planner to generate on-the-fly statistics for OLAP queries. If we ever got that functionality, we'd need a means of exposing those row samples externally, and even then we'd have to wait for the remote postgresql server to have that feature. So for now we are limited to what pg_class and pg_stats tell us.
The way this is implemented, it will favour the usecases where foreign
tables are not child tables. That leaves out the sharding use case
which I believe is also a significant usecase. I think we need to
think, how can we make that usecase benefit from this optimization. In
case of sharding the foreign tables will be child tables pointing to
very large tables on the remote side or at least the parent table they
are part of will have very large data spread across multiple remotes.
Not being able to use statistics available on the remote side seems a
major limitation. But I don't have a better solution than to think of
supporting some kind of partial statistics.
--
Best Wishes,
Ashutosh Bapat
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-01-29 19:20 Corey Huinker <corey.huinker@gmail.com>
parent: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-01-29 19:20 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
>
> The way this is implemented, it will favour the usecases where foreign
> tables are not child tables.
It is true that this feature does not benefit the recursive
do_analyze_rel() case. But it does help when those same tables are analyzed
directly.
> That leaves out the sharding use case
> which I believe is also a significant usecase. I think we need to
> think, how can we make that usecase benefit from this optimization.
I agree that we should find a way to do that, but this handles the other
case, and doesn't prevent us from later teaching
postgresAnalyzeForeignTable() to use cache the rowsample locally for later
use, which postgresImportStatistics() could then consider the relative
benefits of using that local cached sample vs the already formed remote
statistics. Even in that case, I'm guessing that the remote table's stats
will be based on a larger and therefore better sample size then the sample
we are able to pull across the wire and cache locally, so the remotely
computed statistics would be better.
Not being able to use statistics available on the remote side seems a
> major limitation. But I don't have a better solution than to think of
> supporting some kind of partial statistics.
I'm not against trying to fetch and cache rowsamples, or cache some
partially aggregated results of a rowsample, but this patch does not cover
that. This patch should, at least in theory, reduce the number of table
samples pulled across the wire by 50% and that seems worthwhile.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-02-12 14:29 Corey Huinker <corey.huinker@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 0 replies; 89+ messages in thread
From: Corey Huinker @ 2026-02-12 14:29 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Thu, Jan 29, 2026 at 2:20 PM Corey Huinker <corey.huinker@gmail.com>
wrote:
>
>> The way this is implemented, it will favour the usecases where foreign
>> tables are not child tables.
>
>
> It is true that this feature does not benefit the recursive
> do_analyze_rel() case. But it does help when those same tables are analyzed
> directly.
>
>
>> That leaves out the sharding use case
>> which I believe is also a significant usecase. I think we need to
>> think, how can we make that usecase benefit from this optimization.
>
>
> I agree that we should find a way to do that, but this handles the other
> case, and doesn't prevent us from later teaching
> postgresAnalyzeForeignTable() to use cache the rowsample locally for later
> use, which postgresImportStatistics() could then consider the relative
> benefits of using that local cached sample vs the already formed remote
> statistics. Even in that case, I'm guessing that the remote table's stats
> will be based on a larger and therefore better sample size then the sample
> we are able to pull across the wire and cache locally, so the remotely
> computed statistics would be better.
>
> Not being able to use statistics available on the remote side seems a
>> major limitation. But I don't have a better solution than to think of
>> supporting some kind of partial statistics.
>
>
> I'm not against trying to fetch and cache rowsamples, or cache some
> partially aggregated results of a rowsample, but this patch does not cover
> that. This patch should, at least in theory, reduce the number of table
> samples pulled across the wire by 50% and that seems worthwhile.
>
>
Rebase with some error message cleanups.
Attachments: download all (3 files, .tar.gz)
v13-0001-Add-FDW-functions-for-importing-optimizer-statis.patch (text/x-patch, 5.0K) download
From 1d2a58ea79956e8aafd4d7d481bdef1e63b5caab Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 16:39:45 -0500
Subject: [PATCH v13 1/3] Add FDW functions for importing optimizer statistics.
Add the the function StatisticsAreImportable which is used as a
lightweight preliminary scan to determine if the remote table could
potentially have statistics that could be imported instead of fetching a
row sample from the remote table, which can be expensive.
Also add the function ImportStatistics which attempts to actually fetch
those statistics from the remote server, and if successful import them
into the local statistics catalog.
---
src/include/foreign/fdwapi.h | 8 ++++
src/backend/commands/analyze.c | 68 ++++++++++++++++++++++++----------
2 files changed, 56 insertions(+), 20 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..59beeae4f45 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef bool (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +261,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index a483424152c..c84367461fb 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -113,6 +113,9 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool can_import_stats = false;
+ bool stats_imported = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -195,27 +198,16 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
- {
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
- }
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ can_import_stats = true;
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
{
@@ -247,10 +239,46 @@ analyze_rel(Oid relid, RangeVar *relation,
PROGRESS_ANALYZE_STARTED_BY_MANUAL);
/*
- * Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * If this table can import statistics, attempt to do so.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (can_import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ stats_imported = fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+
+ /*
+ * Foreign tables that were not able to import stats will resort to
+ * regular sampling.
+ */
+ if ((onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
+ && !stats_imported)
+ {
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
+ }
+
+ /*
+ * Do the normal non-recursive ANALYZE. We can skip this for partitioned
+ * tables and foreign tables that successfully imported statistics.
+ */
+ if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ && !stats_imported)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
base-commit: 88327092ff06c48676d2a603420089bf493770f3
--
2.53.0
v13-0002-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 36.9K) download
From 0d117a35693e03a4cc3e21d1843403376bbf36c5 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:06:05 -0500
Subject: [PATCH v13 2/3] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via a new option, fetch_stats, which is available at the
server level and table level. The global default is true, but this can
be overriden by at the server level, which in turn can be overridden at
the table level.
If fetch_stats is true, and the remote table is an actual table or
materialized view that can hold statistics, and the local table does not
have any extended statistics objects built upon it, then the remote
database will first be queried for relation statistics and attribute
statistics similar to the method used in pg_dump.
If there are remote statistics for all of the columns in the local
table, then those statistics will be imported using
pg_restore_relation_statistics and pg_restore_attribute_statistics
functions similar to the way pg_restore uses them.
If fetch_stats is false, or if the fetched statistics were missing or
otherwise inadequate, then the ANALYZE operation will issue a WARNING
and then fall back to regular table sampling to generate local
statistics.
---
src/backend/commands/analyze.c | 3 +-
doc/src/sgml/postgres-fdw.sgml | 25 +-
.../postgres_fdw/expected/postgres_fdw.out | 17 +-
contrib/postgres_fdw/option.c | 5 +
contrib/postgres_fdw/postgres_fdw.c | 909 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 13 +-
6 files changed, 968 insertions(+), 4 deletions(-)
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index c84367461fb..c235f8041df 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -239,7 +239,8 @@ analyze_rel(Oid relid, RangeVar *relation,
PROGRESS_ANALYZE_STARTED_BY_MANUAL);
/*
- * If this table can import statistics, attempt to do so.
+ * If this table can import statistics, attempt to do so. If statistics
+ * import fails, then we will fall back to table sampling.
*/
if (can_import_stats)
{
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index fcf10e4317e..f695415575d 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,29 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</function> and
+ <function>pg_restore_attribute_stats</function>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views). If the foreign table is a partition
+ of a partitioned table, analyzing the partitioned table will still
+ result in row sampling on the foreign table regardless of this setting,
+ though direct analysis of the foreign table would have attempted to
+ fetch remote statistics first.
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 2ccb72c539a..9ca3a14fa74 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4551,7 +4552,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11473,6 +11475,13 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+WARNING: failed to import statistics from remote table public.base_tbl2,
+HINT: Falling back to ANALYZE with regular row sampling.
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11579,6 +11588,12 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+WARNING: failed to import statistics from remote table public.base_tbl3,
+HINT: Falling back to ANALYZE with regular row sampling.
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..5b7726800d0 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +279,10 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 60d90329a65..657cfced012 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -18,10 +18,13 @@
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_opfamily.h"
+#include "catalog/pg_statistic_ext.h"
#include "commands/defrem.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -42,12 +45,14 @@
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
+#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
+#include "utils/syscache.h"
PG_MODULE_MAGIC_EXT(
.name = "postgres_fdw",
@@ -317,6 +322,20 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ char remote_attname[NAMEDATALEN];
+ AttrNumber local_attnum;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -402,6 +421,10 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresStatisticsAreImportable(Relation relation);
+static bool postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +569,188 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns
+{
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_NUM_FIELDS,
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+static const char *attstats_query_default =
+"SELECT s.attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\"";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns
+{
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS,
+};
+
+static const char *relimport_sql =
+"SELECT pg_catalog.pg_restore_relation_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'relpages', $4::integer,\n"
+"\t'reltuples', $5::real)";
+
+enum RelImportSqlArgs
+{
+ RELIMPORT_SQL_VERSION = 0,
+ RELIMPORT_SQL_SCHEMANAME,
+ RELIMPORT_SQL_RELNAME,
+ RELIMPORT_SQL_RELPAGES,
+ RELIMPORT_SQL_RELTUPLES,
+ RELIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid relimport_argtypes[RELIMPORT_SQL_NUM_FIELDS] = {
+INT4OID, TEXTOID, TEXTOID, TEXTOID, TEXTOID,};
+
+static const char *attimport_sql =
+"SELECT pg_catalog.pg_restore_attribute_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'attnum', $4,\n"
+"\t'inherited', false::boolean,\n"
+"\t'null_frac', $5::real,\n"
+"\t'avg_width', $6::integer,\n"
+"\t'n_distinct', $7::real,\n"
+"\t'most_common_vals', $8,\n"
+"\t'most_common_freqs', $9::real[],\n"
+"\t'histogram_bounds', $10,\n"
+"\t'correlation', $11::real,\n"
+"\t'most_common_elems', $12,\n"
+"\t'most_common_elem_freqs', $13::real[],\n"
+"\t'elem_count_histogram', $14::real[],\n"
+"\t'range_length_histogram', $15,\n"
+"\t'range_empty_frac', $16::real,\n"
+"\t'range_bounds_histogram', $17)";
+
+enum AttImportSqlArgs
+{
+ ATTIMPORT_SQL_VERSION = 0,
+ ATTIMPORT_SQL_SCHEMANAME,
+ ATTIMPORT_SQL_RELNAME,
+ ATTIMPORT_SQL_ATTNUM,
+ ATTIMPORT_SQL_NULL_FRAC,
+ ATTIMPORT_SQL_AVG_WIDTH,
+ ATTIMPORT_SQL_N_DISTINCT,
+ ATTIMPORT_SQL_MOST_COMMON_VALS,
+ ATTIMPORT_SQL_MOST_COMMON_FREQS,
+ ATTIMPORT_SQL_HISTOGRAM_BOUNDS,
+ ATTIMPORT_SQL_CORRELATION,
+ ATTIMPORT_SQL_MOST_COMMON_ELEMS,
+ ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS,
+ ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_EMPTY_FRAC,
+ ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM,
+ ATTIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid attimport_argtypes[ATTIMPORT_SQL_NUM_FIELDS] = {
+ INT4OID, TEXTOID, TEXTOID, INT2OID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+TEXTOID,};
+
+/* Pairs AttStatsColumns:AttImportSqlArgs Map */
+typedef struct
+{
+ enum AttStatsColumns res_field;
+ enum AttImportSqlArgs arg_num;
+} AttrResultArgMap;
+
+/*
+ * The mapping of attribute stats query columns to the positional arguments in
+ * the prepared pg_restore_attribute_stats() statement.
+ */
+#define NUM_MAPPED_ATTIMPORT_ARGS 13
+static const AttrResultArgMap attr_result_arg_map[NUM_MAPPED_ATTIMPORT_ARGS] = {
+ {ATTSTATS_NULL_FRAC, ATTIMPORT_SQL_NULL_FRAC},
+ {ATTSTATS_AVG_WIDTH, ATTIMPORT_SQL_AVG_WIDTH},
+ {ATTSTATS_N_DISTINCT, ATTIMPORT_SQL_N_DISTINCT},
+ {ATTSTATS_MOST_COMMON_VALS, ATTIMPORT_SQL_MOST_COMMON_VALS},
+ {ATTSTATS_MOST_COMMON_FREQS, ATTIMPORT_SQL_MOST_COMMON_FREQS},
+ {ATTSTATS_HISTOGRAM_BOUNDS, ATTIMPORT_SQL_HISTOGRAM_BOUNDS},
+ {ATTSTATS_CORRELATION, ATTIMPORT_SQL_CORRELATION},
+ {ATTSTATS_MOST_COMMON_ELEMS, ATTIMPORT_SQL_MOST_COMMON_ELEMS},
+ {ATTSTATS_MOST_COMMON_ELEM_FREQS, ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS},
+ {ATTSTATS_ELEM_COUNT_HISTOGRAM, ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM},
+ {ATTSTATS_RANGE_LENGTH_HISTOGRAM, ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM},
+ {ATTSTATS_RANGE_EMPTY_FRAC, ATTIMPORT_SQL_RANGE_EMPTY_FRAC},
+ {ATTSTATS_RANGE_BOUNDS_HISTOGRAM, ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM},
+};
+
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +800,8 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->StatisticsAreImportable = postgresStatisticsAreImportable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5142,708 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Move a string value from a result set to a Text value of a Datum array.
+ */
+static void
+map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls)
+{
+ if (PQgetisnull(res, row, field))
+ {
+ values[arg] = (Datum) 0;
+ nulls[arg] = 'n';
+ }
+ else
+ {
+ const char *s = PQgetvalue(res, row, field);
+
+ values[arg] = CStringGetTextDatum(s);
+ nulls[arg] = ' ';
+ }
+}
+
+/*
+ * Check the 1x1 result set of a pg_restore_*_stats() command for success.
+ */
+static bool
+import_spi_query_ok(int spirc)
+{
+ char *s;
+ bool ok;
+
+ if (spirc != SPI_OK_SELECT
+ || SPI_tuptable == NULL
+ || SPI_processed != 1)
+ return false;
+
+ s = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
+
+ ok = (s != NULL && s[0] == 't' && s[1] == '\0');
+ pfree(s);
+
+ return ok;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static bool
+import_fetched_statistics(const char *schemaname, const char *relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping * remattrmap,
+ RemoteStatsResults * remstats)
+{
+ SPIPlanPtr plan = NULL;
+ PGresult *res = remstats->att;
+ int spirc;
+ int mapidx = 0;
+ Datum values[ATTIMPORT_SQL_NUM_FIELDS];
+ char nulls[ATTIMPORT_SQL_NUM_FIELDS];
+ bool ok = false;
+
+ /* Assign all the invariant parameters */
+ values[ATTIMPORT_SQL_VERSION] = Int32GetDatum(server_version_num);
+ nulls[ATTIMPORT_SQL_VERSION] = ' ';
+
+ values[ATTIMPORT_SQL_SCHEMANAME] = CStringGetTextDatum(schemaname);
+ nulls[ATTIMPORT_SQL_SCHEMANAME] = ' ';
+
+ values[ATTIMPORT_SQL_RELNAME] = CStringGetTextDatum(relname);
+ nulls[ATTIMPORT_SQL_RELNAME] = ' ';
+
+ nulls[ATTIMPORT_SQL_ATTNUM] = ' ';
+
+ SPI_connect();
+
+ plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+
+ if (plan == NULL || SPI_result < 0)
+ {
+ ereport(WARNING,
+ errmsg("import attribute statistics prepare failed %s "
+ "with error code %d",
+ attimport_sql, SPI_result));
+ goto import_cleanup;
+ }
+
+ /*
+ * Match result set rows to local attnums.
+ *
+ * Every row of the result should be an attribute that we specifically
+ * filtered for, so every row should have at least one match in the
+ * RemoteAttributeMapping, which is also ordered by attname, so we only
+ * need to walk that array once.
+ *
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ for (int row = 0; row < PQntuples(remstats->att); row++)
+ {
+ char *remote_attname;
+ bool match_found = false;
+ int cmp = 0;
+
+ if (PQgetisnull(res, row, ATTSTATS_ATTNAME))
+ {
+ ereport(WARNING,
+ errmsg("remote statistics returned a row with NULL attribute name"));
+ goto import_cleanup;
+ }
+
+ remote_attname = PQgetvalue(res, row, ATTSTATS_ATTNAME);
+
+ /*
+ * Handle a series of matching elements in the mapping.
+ *
+ * We exit this loop in the following ways:
+ *
+ * 1. Having found at least match and exhausting the list. We're done.
+ * 2. Having found at least match and ending on a <, advance. 3.
+ * Having found at least match and ending on a >, bad sort. 4. No
+ * match, list exhausted. 5. No match, <. 6. No match, >.
+ *
+ */
+ for (; mapidx < natts; mapidx++)
+ {
+ cmp = strcmp(remote_attname, remattrmap[mapidx].remote_attname);
+
+ /* Stop scanning on the first non-match */
+ if (cmp != 0)
+ break;
+
+ match_found = true;
+ values[ATTIMPORT_SQL_ATTNUM] =
+ Int16GetDatum(remattrmap[mapidx].local_attnum);
+
+ /* Loop through all mappable columns->arguments */
+ for (int i = 0; i < NUM_MAPPED_ATTIMPORT_ARGS; i++)
+ map_field_to_arg(res, row,
+ attr_result_arg_map[i].res_field,
+ attr_result_arg_map[i].arg_num,
+ values, nulls);
+
+ spirc = SPI_execute_plan(plan, values, nulls, false, 0);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("attribute statistics import failed %s",
+ attimport_sql));
+ goto import_cleanup;
+ }
+ }
+
+ /* We found a match, move onto the next result. */
+ if (match_found)
+ continue;
+
+ /*
+ * If no match and we ended on a <, then the mapidx will never find a
+ * match, so stop now and let the cleanup report the error.
+ */
+ if (cmp > 0)
+ break;
+
+ /*
+ * Otherwise this result found no matching mapidx, which should only
+ * happen if the results are out of sort or the wrong query was
+ * executed.
+ */
+ if (cmp < 0)
+ {
+ ereport(WARNING,
+ errmsg("no remote statistics found for %s of %s.%s",
+ remattrmap[mapidx].remote_attname, schemaname, relname));
+ goto import_cleanup;
+ }
+ }
+
+ /* Look for a mapidx with no possible matching result */
+ if (mapidx < natts)
+ {
+ ereport(WARNING,
+ errmsg("no remote statistics found for %s of %s.%s",
+ remattrmap[mapidx].remote_attname, schemaname, relname));
+ goto import_cleanup;
+ }
+
+ /*
+ * Import relstats.
+ *
+ * Import relation stats. We only perform this once, so there is no point
+ * in preparing the statement.
+ *
+ * We can re-use the values/nulls because the number of parameters is less
+ * and the first three params are the same as attstats_import.
+ */
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELPAGES,
+ RELIMPORT_SQL_RELPAGES, values, nulls);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELTUPLES,
+ RELIMPORT_SQL_RELTUPLES, values, nulls);
+
+ spirc = SPI_execute_with_args(relimport_sql, RELIMPORT_SQL_NUM_FIELDS,
+ (Oid *) relimport_argtypes,
+ values, nulls, false, 1);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("relation statistics import failed %s",
+ relimport_sql));
+ goto import_cleanup;
+ }
+
+ ok = true;
+
+import_cleanup:
+ if (plan)
+ SPI_freeplan(plan);
+ SPI_finish();
+ return ok;
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ *
+ * Verify that the result is of the proper shape, return NULL otherwise.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname)
+{
+ const char *params[2] = {remote_schemaname, remote_relname};
+
+ /*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case).
+ *
+ * We can ignore this change, because if the remote table wasn't analyzed,
+ * then it would have no attribute stats, and thus we wouldn't have stats
+ * that we would try to import. So we can take the reltuples value as-is.
+ */
+ const char *sql = "SELECT c.relkind, c.relpages, c.reltuples "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n "
+ "ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+ PGresult *res = NULL;
+
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ {
+ pgfdw_report(WARNING, NULL, conn, sql);
+ return NULL;
+ }
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS
+ || PQgetisnull(res, 0, RELSTATS_RELKIND))
+ {
+ pgfdw_report(WARNING, res, conn, sql);
+ PQclear(res);
+ return NULL;
+ }
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ *
+ * Verify that the result is of the proper shape, return NULL otherwise. Note
+ * that we do not verify the row count.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list)
+{
+ const char *params[3] = {remote_schemaname, remote_relname, column_list};
+ int version = PQserverVersion(conn);
+ const char *sql;
+ PGresult *res;
+
+ if (version >= 170000)
+ sql = attstats_query_17;
+ else if (version >= 90200)
+ sql = attstats_query_9_2;
+ else if (version >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ {
+ pgfdw_report(WARNING, NULL, conn, sql);
+ return NULL;
+ }
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ {
+ pgfdw_report(WARNING, res, conn, sql);
+ PQclear(res);
+ return NULL;
+ }
+
+ return res;
+}
+
+/*
+ * Make a '{column,list,array}'.
+ */
+static char *
+get_column_list(int natts, const RemoteAttributeMapping * remattrmap)
+{
+ StringInfoData column_list;
+
+ initStringInfo(&column_list);
+ appendStringInfoChar(&column_list, '{');
+ for (int i = 0; i < natts; i++)
+ {
+ if (i > 0)
+ appendStringInfoChar(&column_list, ',');
+ appendStringInfoString(&column_list,
+ quote_identifier(remattrmap[i].remote_attname));
+ }
+ appendStringInfoChar(&column_list, '}');
+
+ return column_list.data;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static bool
+fetch_remote_statistics(PGconn *conn,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping * remattrmap,
+ RemoteStatsResults * remstats)
+{
+ char *column_list = NULL;
+ PGresult *attstats = NULL;
+ PGresult *relstats = NULL;
+
+ char relkind;
+
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ if (relstats == NULL)
+ goto fetch_remote_statistics_fail;
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
+ * can't support a foreign table.
+ */
+ relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
+
+ switch (relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ goto fetch_remote_statistics_fail;
+ }
+
+ column_list = get_column_list(natts, remattrmap);
+
+ /* See if it actually has any attribute stats. */
+ attstats = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list);
+
+ /*
+ * If we got attribute statistics results, then we are done with fetching.
+ */
+ if (attstats != NULL
+ && PQntuples(attstats) > 0)
+ {
+ pfree(column_list);
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+ }
+
+fetch_remote_statistics_fail:
+ ereport(WARNING,
+ errmsg("failed to import statistics from remote table %s.%s, ",
+ remote_schemaname, remote_relname),
+ errhint("Falling back to ANALYZE with regular row sampling."));
+ PQclear(attstats);
+ PQclear(relstats);
+ if (column_list)
+ pfree(column_list);
+ return false;
+}
+
+/*
+ * Test if the relation has extended statistics objects.
+ */
+static bool
+table_has_extended_stats(Relation relation)
+{
+ Relation pg_statext;
+ SysScanDesc scan;
+ ScanKeyData skey;
+ bool found;
+
+ pg_statext = table_open(StatisticExtRelationId, RowExclusiveLock);
+
+ /*
+ * Prepare to scan pg_statistic_ext for entries having stxrelid = this
+ * rel.
+ */
+ ScanKeyInit(&skey,
+ Anum_pg_statistic_ext_stxrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(relation)));
+
+ scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
+ NULL, 1, &skey);
+
+ found = (systable_getnext(scan) != NULL);
+
+ systable_endscan(scan);
+
+ table_close(pg_statext, RowExclusiveLock);
+
+ return found;
+}
+
+static bool
+postgresStatisticsAreImportable(Relation relation)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ ListCell *lc;
+ bool fetch_stats = true;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ /*
+ * Additional checks that can disqualify a table from importing stats.
+ */
+ if (fetch_stats)
+ {
+ /*
+ * We can't compute extended stats from the column stats, for that we
+ * need a table sample.
+ */
+ if (table_has_extended_stats(relation))
+ {
+ ereport(WARNING,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("cannot import statistics for foreign table \"%s\" "
+ "because it has extended statistics objects.",
+ RelationGetRelationName(relation)));
+ fetch_stats = false;
+ }
+ }
+
+ return fetch_stats;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Fetch attstattarget from a pg_attribute tuple.
+ */
+static int16
+get_attstattarget(Relation relation, AttrNumber attnum)
+{
+ HeapTuple atttuple;
+ bool isnull;
+ Datum dat;
+ int16 attstattarget;
+ Oid relid = RelationGetRelid(relation);
+
+ atttuple = SearchSysCache2(ATTNUM,
+ ObjectIdGetDatum(relid),
+ Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, relid);
+ dat = SysCacheGetAttr(ATTNUM, atttuple,
+ Anum_pg_attribute_attstattarget,
+ &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ return attstattarget;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static bool
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+
+ ForeignTable *table;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int natts = 0;
+ bool ok = false;
+
+ RemoteAttributeMapping *remattrmap;
+
+ RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ }
+
+ /*
+ * Assume the relation/schema names are the same as the local name unless
+ * the options tell us otherwise.
+ */
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ /*
+ * Build attnum/remote-attname list.
+ *
+ */
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *attname;
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+
+ /* Ignore dropped columns. */
+ if (attr->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (attr->attgenerated)
+ continue;
+
+ attname = NameStr(attr->attname);
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ attnum = attr->attnum;
+
+ /* Ignore if attstatarget is 0 */
+ if (get_attstattarget(relation, attnum) == 0)
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_colname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].remote_attname, remote_colname, NAMEDATALEN);
+ natts++;
+ }
+
+ /* Sort mapping by remote attribute name */
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
+ server_version_num, natts, remattrmap,
+ &remstats);
+
+ ReleaseConnection(conn);
+
+ if (ok)
+ {
+ Assert(remstats.rel != NULL);
+ Assert(PQnfields(remstats.rel) == RELSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.rel) == 1);
+ Assert(remstats.att != NULL);
+ Assert(PQnfields(remstats.att) == ATTSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.att) >= 1);
+ ok = import_fetched_statistics(schemaname, relname, server_version_num,
+ natts, remattrmap, &remstats);
+ }
+
+ pfree(remattrmap);
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+ return ok;
+}
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 72d2d9c311b..204ef78b1a4 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1286,7 +1287,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3910,6 +3912,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3947,6 +3954,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
--
2.53.0
v13-0003-Add-remote_analyze-to-postgres_fdw-remote-statis.patch (text/x-patch, 10.8K) download
From c25cb9fb4c5dff0711de4827670e801783c2a124 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:33:53 -0500
Subject: [PATCH v13 3/3] Add remote_analyze to postgres_fdw remote statistics
fetching.
This is accomplished through a new option, remote_analyze, which is
available at the server level and table level. The default value is
false.
If remote_analyze is enabled, and if the first attempt to fetch remote
statistics did not fetch attribute statistics for every local table
column, then an attempt will be made to ANALYZE the remote table. If
that remote ANALYZE succeeds, then a second and final attempt will be
made to fetch remote statistics. If the statistics found are still
insufficient, then the local ANALYZE command will fall back to regular
row sampling and computing the statistics locally.
---
doc/src/sgml/postgres-fdw.sgml | 16 ++++
.../postgres_fdw/expected/postgres_fdw.out | 38 +++++++++
contrib/postgres_fdw/option.c | 5 ++
contrib/postgres_fdw/postgres_fdw.c | 80 ++++++++++++++++++-
contrib/postgres_fdw/sql/postgres_fdw.sql | 34 ++++++++
5 files changed, 171 insertions(+), 2 deletions(-)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index f695415575d..97754053bac 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -387,6 +387,22 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ has no meaning if the foreign table has <literal>fetch_stats</literal>
+ disabled.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 9ca3a14fa74..3c704c11d73 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -12691,6 +12691,44 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 5b7726800d0..2941ecbfb87 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -121,6 +121,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -283,6 +284,10 @@ InitPgFdwOptions(void)
{"fetch_stats", ForeignServerRelationId, false},
{"fetch_stats", ForeignTableRelationId, false},
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 657cfced012..c52ddcb7a69 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -5388,6 +5388,36 @@ import_cleanup:
return ok;
}
+/*
+ * Analyze a remote table.
+ */
+static bool
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+ bool ok = true;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s",
+ quote_qualified_identifier(remote_schemaname, remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL ||
+ PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ pgfdw_report(WARNING, res, conn, buf.data);
+ ok = false;
+ }
+
+ PQclear(res);
+ pfree(buf.data);
+ return ok;
+}
+
/*
* Attempt to fetch remote relations stats.
*
@@ -5514,7 +5544,7 @@ fetch_remote_statistics(PGconn *conn,
const char *remote_relname,
int server_version_num, int natts,
const RemoteAttributeMapping * remattrmap,
- RemoteStatsResults * remstats)
+ bool remote_analyze, RemoteStatsResults * remstats)
{
char *column_list = NULL;
PGresult *attstats = NULL;
@@ -5566,6 +5596,35 @@ fetch_remote_statistics(PGconn *conn,
return true;
}
+ /*
+ * If remote_analyze is enabled, then we will try to analyze the table and
+ * then try again.
+ */
+ if (!remote_analyze)
+ goto fetch_remote_statistics_fail;
+
+ if (!analyze_remote_table(conn, remote_schemaname, remote_relname))
+ goto fetch_remote_statistics_fail;
+
+ PQclear(attstats);
+ attstats = fetch_attstats(conn, remote_schemaname, remote_relname,
+ column_list);
+
+ if (attstats == NULL || PQntuples(attstats) == 0)
+ goto fetch_remote_statistics_fail;
+
+ PQclear(relstats);
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ if (relstats == NULL)
+ goto fetch_remote_statistics_fail;
+
+ /* Second attempt worked */
+ pfree(column_list);
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+
fetch_remote_statistics_fail:
ereport(WARNING,
errmsg("failed to import statistics from remote table %s.%s, ",
@@ -5720,9 +5779,11 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
{
ForeignTable *table;
+ ForeignServer *server;
UserMapping *user;
PGconn *conn;
ListCell *lc;
+ bool remote_analyze = false;
int server_version_num = 0;
const char *schemaname = NULL;
const char *relname = NULL;
@@ -5737,12 +5798,25 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
user = GetUserMapping(GetUserId(), table->serverid);
conn = GetConnection(user, false, NULL);
server_version_num = PQserverVersion(conn);
schemaname = get_namespace_name(RelationGetNamespace(relation));
relname = RelationGetRelationName(relation);
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
foreach(lc, table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
@@ -5751,6 +5825,8 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
remote_schemaname = defGetString(def);
else if (strcmp(def->defname, "table_name") == 0)
remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
}
/*
@@ -5822,7 +5898,7 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
server_version_num, natts, remattrmap,
- &remstats);
+ remote_analyze, &remstats);
ReleaseConnection(conn);
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 204ef78b1a4..6aa3b42dd4f 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -4405,6 +4405,40 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
--
2.53.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-12 11:02 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-03-12 11:02 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Sun, Jan 18, 2026 at 11:53 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> Changes in this release, aside from rebasing:
>
> - The generic analyze and fdw.h changes are in their own patch (0001) that ignores contrib/postgres_fdw entirely.
> - The option for remote_analyze has been moved to its own patch (0003).
Thanks for splitting the patch! That makes reviewing easy!
> - The errors raised are now warnings, to ensure that we can always fall back to row sampling.
Falling back to sampling improves the usability, so I don't object to
adding it anymore, but I'm concerned about changes made to the error
handling of libpq functions in fetch_relstats() and fetch_attstats(),
like this bit in the former function:
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ {
+ pgfdw_report(WARNING, NULL, conn, sql);
+ return NULL;
+ }
+
+ res = pgfdw_get_result(conn);
+
+ if (res == NULL
+ || PQresultStatus(res) != PGRES_TUPLES_OK
+ || PQntuples(res) != 1
+ || PQnfields(res) != RELSTATS_NUM_FIELDS
+ || PQgetisnull(res, 0, RELSTATS_RELKIND))
+ {
+ pgfdw_report(WARNING, res, conn, sql);
+ PQclear(res);
+ return NULL;
+ }
By the errors-to-warnings change, even when those libpq functions
fail, we fall back to the normal ANALYZE processing, but I don't think
that that is OK, because if those functions fail for some reasons
(network-related issues like network disconnection or memory-related
issues like out of memory), then libpq functions called later for the
normal processing would also be likely to fail for the same reasons,
causing the same failure again, which I don't think is good. To avoid
that, when libpq functions in fetch_relstats() and fetch_attstats()
fail, shouldn't we just throw an error, as before?
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-12 19:41 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-03-12 19:41 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> By the errors-to-warnings change, even when those libpq functions
> fail, we fall back to the normal ANALYZE processing, but I don't think
> that that is OK, because if those functions fail for some reasons
> (network-related issues like network disconnection or memory-related
> issues like out of memory), then libpq functions called later for the
> normal processing would also be likely to fail for the same reasons,
> causing the same failure again, which I don't think is good. To avoid
> that, when libpq functions in fetch_relstats() and fetch_attstats()
> fail, shouldn't we just throw an error, as before?
>
Right now the code doesn't differentiate on the kind of an error that was
encountered. If it was a network error, then not only do we expect fallback
to also fail, but simple fdw queries will fail as well. If, however it were
a permission issue (no SELECT permission on pg_stats, for instance, or
pg_stats doesn't exist because the remote database is not a regular
Postgres like redshift or something) then I definitely want to fall back.
Currently, the code makes no judgement on the details of the error, it just
trusts that fallback-analyze will either succeed (because it was
permissions related) or it will quickly encounter the same insurmountable
effort, and one extra PQsendQuery isn't that much overhead.
If you think that inspecting the error that we get and matching against a
list of errors that should skip the retry or skip the fallback, I'd be in
favor of that. It's probably easier to start with a list of errorcodes that
we feel are hopeless and should remain ERRORs not WARNINGs.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-13 12:16 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-03-13 12:16 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Fri, Mar 13, 2026 at 4:42 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>>
>> By the errors-to-warnings change, even when those libpq functions
>> fail, we fall back to the normal ANALYZE processing, but I don't think
>> that that is OK, because if those functions fail for some reasons
>> (network-related issues like network disconnection or memory-related
>> issues like out of memory), then libpq functions called later for the
>> normal processing would also be likely to fail for the same reasons,
>> causing the same failure again, which I don't think is good. To avoid
>> that, when libpq functions in fetch_relstats() and fetch_attstats()
>> fail, shouldn't we just throw an error, as before?
> Right now the code doesn't differentiate on the kind of an error that was encountered. If it was a network error, then not only do we expect fallback to also fail, but simple fdw queries will fail as well. If, however it were a permission issue (no SELECT permission on pg_stats, for instance, or pg_stats doesn't exist because the remote database is not a regular Postgres like redshift or something) then I definitely want to fall back. Currently, the code makes no judgement on the details of the error, it just trusts that fallback-analyze will either succeed (because it was permissions related) or it will quickly encounter the same insurmountable effort, and one extra PQsendQuery isn't that much overhead.
I'm not sure if that's really true; if the error is the one that
doesn't take a time to detect, the extra function call wouldn't
probably be a problem, but if the error is the one that takes a long
time to detect, the function call would make the situation worse.
> If you think that inspecting the error that we get and matching against a list of errors that should skip the retry or skip the fallback, I'd be in favor of that. It's probably easier to start with a list of errorcodes that we feel are hopeless and should remain ERRORs not WARNINGs.
That's an improvement, but I think that that's nice-to-have, not
must-have. As there's not much time left until the feature freeze,
I'd like to propose to make the first cut as simple as possible and
thus leave that for future work, if this is intended for v19. If no
objections from you (or anyone else), I'd like to update the patch as
I proposed.
Another thing I noticed is related to this comment in fetch_relstats():
+ /*
+ * Before v14, a reltuples value of 0 was ambiguous: it could either mean
+ * the relation is empty, or it could mean that it hadn't yet been
+ * vacuumed or analyzed. (Newer versions use -1 for the latter case).
+ *
+ * We can ignore this change, because if the remote table wasn't analyzed,
+ * then it would have no attribute stats, and thus we wouldn't have stats
+ * that we would try to import. So we can take the reltuples value as-is.
+ */
I might have misread the patch, but for v14 or later the patch tries
to import remote stats even when we have reltuples = -1. Is that
intentional? In that case the remote table has never yet been
vacuumed/analyzed, so I think we should just fall back to the normal
processing. Also, for v13 or earlier it also tries to import remote
stats even when we have reltuples = 0, but in that case the remote
table might not have been vacuumed/analyzed, so to avoid possibly
useless processing, I think we should just fall back to it in that
case as well.
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-13 15:36 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-03-13 15:36 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Fri, Mar 13, 2026 at 8:17 AM Etsuro Fujita <etsuro.fujita@gmail.com>
wrote:
> On Fri, Mar 13, 2026 at 4:42 AM Corey Huinker <corey.huinker@gmail.com>
> wrote:
> >>
> >> By the errors-to-warnings change, even when those libpq functions
> >> fail, we fall back to the normal ANALYZE processing, but I don't think
> >> that that is OK, because if those functions fail for some reasons
> >> (network-related issues like network disconnection or memory-related
> >> issues like out of memory), then libpq functions called later for the
> >> normal processing would also be likely to fail for the same reasons,
> >> causing the same failure again, which I don't think is good. To avoid
> >> that, when libpq functions in fetch_relstats() and fetch_attstats()
> >> fail, shouldn't we just throw an error, as before?
>
> > Right now the code doesn't differentiate on the kind of an error that
> was encountered. If it was a network error, then not only do we expect
> fallback to also fail, but simple fdw queries will fail as well. If,
> however it were a permission issue (no SELECT permission on pg_stats, for
> instance, or pg_stats doesn't exist because the remote database is not a
> regular Postgres like redshift or something) then I definitely want to fall
> back. Currently, the code makes no judgement on the details of the error,
> it just trusts that fallback-analyze will either succeed (because it was
> permissions related) or it will quickly encounter the same insurmountable
> effort, and one extra PQsendQuery isn't that much overhead.
>
> I'm not sure if that's really true; if the error is the one that
> doesn't take a time to detect, the extra function call wouldn't
> probably be a problem, but if the error is the one that takes a long
> time to detect, the function call would make the situation worse.
>
I'm struggling to think of what kind of error that would be that would take
a long time to detect. Network timeouts could be one thing, but such a
situation would affect normal query operations as well, not just analyzes.
If you have a specific error in mind, please let me know.
>
> > If you think that inspecting the error that we get and matching against
> a list of errors that should skip the retry or skip the fallback, I'd be in
> favor of that. It's probably easier to start with a list of errorcodes that
> we feel are hopeless and should remain ERRORs not WARNINGs.
>
> That's an improvement, but I think that that's nice-to-have, not
> must-have. As there's not much time left until the feature freeze,
> I'd like to propose to make the first cut as simple as possible and
> thus leave that for future work, if this is intended for v19. If no
> objections from you (or anyone else), I'd like to update the patch as
> I proposed.
>
I'd like to get this into 19 as well, so I'm likely to agree to your
proposal.
>
> Another thing I noticed is related to this comment in fetch_relstats():
>
> + /*
> + * Before v14, a reltuples value of 0 was ambiguous: it could either
> mean
> + * the relation is empty, or it could mean that it hadn't yet been
> + * vacuumed or analyzed. (Newer versions use -1 for the latter case).
> + *
> + * We can ignore this change, because if the remote table wasn't
> analyzed,
> + * then it would have no attribute stats, and thus we wouldn't have
> stats
> + * that we would try to import. So we can take the reltuples value
> as-is.
> + */
>
> I might have misread the patch, but for v14 or later the patch tries
> to import remote stats even when we have reltuples = -1. Is that
> intentional? In that case the remote table has never yet been
> vacuumed/analyzed, so I think we should just fall back to the normal
> processing.
For cases where we affirmatively have -1, it makes sense to immediately go
to the ANALYZE option (if available) and fall back if not. I'll make that
change.
> Also, for v13 or earlier it also tries to import remote
> stats even when we have reltuples = 0, but in that case the remote
> table might not have been vacuumed/analyzed, so to avoid possibly
> useless processing, I think we should just fall back to it in that
> case as well.
>
+1
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-14 11:40 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-03-14 11:40 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Sat, Mar 14, 2026 at 12:36 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> On Fri, Mar 13, 2026 at 8:17 AM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
>> On Fri, Mar 13, 2026 at 4:42 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>> >>
>> >> By the errors-to-warnings change, even when those libpq functions
>> >> fail, we fall back to the normal ANALYZE processing, but I don't think
>> >> that that is OK, because if those functions fail for some reasons
>> >> (network-related issues like network disconnection or memory-related
>> >> issues like out of memory), then libpq functions called later for the
>> >> normal processing would also be likely to fail for the same reasons,
>> >> causing the same failure again, which I don't think is good. To avoid
>> >> that, when libpq functions in fetch_relstats() and fetch_attstats()
>> >> fail, shouldn't we just throw an error, as before?
>>
>> > Right now the code doesn't differentiate on the kind of an error that was encountered. If it was a network error, then not only do we expect fallback to also fail, but simple fdw queries will fail as well. If, however it were a permission issue (no SELECT permission on pg_stats, for instance, or pg_stats doesn't exist because the remote database is not a regular Postgres like redshift or something) then I definitely want to fall back. Currently, the code makes no judgement on the details of the error, it just trusts that fallback-analyze will either succeed (because it was permissions related) or it will quickly encounter the same insurmountable effort, and one extra PQsendQuery isn't that much overhead.
>>
>> I'm not sure if that's really true; if the error is the one that
>> doesn't take a time to detect, the extra function call wouldn't
>> probably be a problem, but if the error is the one that takes a long
>> time to detect, the function call would make the situation worse.
>
> I'm struggling to think of what kind of error that would be that would take a long time to detect. Network timeouts could be one thing, but such a situation would affect normal query operations as well, not just analyzes. If you have a specific error in mind, please let me know.
I too was thinking of network timeouts (and in such a case I thought
that even if PQsendQuery was run successfully, the following
PQgetResult would have to block for a long time). And yes, that
situation can occur for normal queries, but in such a query, the extra
functions call is done only when aborting the remote transaction, in a
way libpq functions don't have to wait for a network timeout.
>> > If you think that inspecting the error that we get and matching against a list of errors that should skip the retry or skip the fallback, I'd be in favor of that. It's probably easier to start with a list of errorcodes that we feel are hopeless and should remain ERRORs not WARNINGs.
>>
>> That's an improvement, but I think that that's nice-to-have, not
>> must-have. As there's not much time left until the feature freeze,
>> I'd like to propose to make the first cut as simple as possible and
>> thus leave that for future work, if this is intended for v19. If no
>> objections from you (or anyone else), I'd like to update the patch as
>> I proposed.
>
> I'd like to get this into 19 as well, so I'm likely to agree to your proposal.
Ok, will update the patch.
>> Another thing I noticed is related to this comment in fetch_relstats():
>>
>> + /*
>> + * Before v14, a reltuples value of 0 was ambiguous: it could either mean
>> + * the relation is empty, or it could mean that it hadn't yet been
>> + * vacuumed or analyzed. (Newer versions use -1 for the latter case).
>> + *
>> + * We can ignore this change, because if the remote table wasn't analyzed,
>> + * then it would have no attribute stats, and thus we wouldn't have stats
>> + * that we would try to import. So we can take the reltuples value as-is.
>> + */
>>
>> I might have misread the patch, but for v14 or later the patch tries
>> to import remote stats even when we have reltuples = -1. Is that
>> intentional? In that case the remote table has never yet been
>> vacuumed/analyzed, so I think we should just fall back to the normal
>> processing.
>
> For cases where we affirmatively have -1, it makes sense to immediately go to the ANALYZE option (if available) and fall back if not. I'll make that change.
>
>> Also, for v13 or earlier it also tries to import remote
>> stats even when we have reltuples = 0, but in that case the remote
>> table might not have been vacuumed/analyzed, so to avoid possibly
>> useless processing, I think we should just fall back to it in that
>> case as well.
>
> +1
I forgot to mention this, but when we have reltuples = 0 for v14 or
later, the patch tries to import both relstats and attstats, but in
that case I think it would be OK to do so only for the former for the
consistency with the normal processing. What do you think about that?
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-14 19:51 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 3 replies; 89+ messages in thread
From: Corey Huinker @ 2026-03-14 19:51 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
>
> I too was thinking of network timeouts (and in such a case I thought
> that even if PQsendQuery was run successfully, the following
> PQgetResult would have to block for a long time). And yes, that
> situation can occur for normal queries, but in such a query, the extra
> functions call is done only when aborting the remote transaction, in a
> way libpq functions don't have to wait for a network timeout.
>
I've copied the ERROR-behavior that was already done
in postgresGetAnalyzeInfoForForeignTable(), which I assume will be to your
liking.
Structural error checks (how many columns does the result set have, etc)
are now elog errors, bad PQresultStatus-es are now errors as well.
The warnings when the query ran fine but no data was found are now NOTICE
level.
> I forgot to mention this, but when we have reltuples = 0 for v14 or
> later, the patch tries to import both relstats and attstats, but in
> that case I think it would be OK to do so only for the former for the
> consistency with the normal processing. What do you think about that?
>
I've update the logic that we don't try to fetch attrstats if the reltuples
is 0 or -1, and though the comments still mention the difference in server
version, the code behaves the same in new versions and old. My thinking is
that either value means "you are not going to find attstats" and our
reaction is the same either way.
I've also moved the column matching - finding which rows of the attstats
result set match to which columns in the local table - up into the fetch
portion, something you had mentioned wanting to see as well. This resulted
in some significant refactoring, but overall I think you will find the
changes for the better.
Attachments: download all (3 files, .tar.gz)
v14-0001-Add-FDW-functions-for-importing-optimizer-statis.patch (text/x-patch, 5.0K) download
From aff24e106b88de903f4a1b563485a7adee9438ad Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 16:39:45 -0500
Subject: [PATCH v14 1/3] Add FDW functions for importing optimizer statistics.
Add the the function StatisticsAreImportable which is used as a
lightweight preliminary scan to determine if the remote table could
potentially have statistics that could be imported instead of fetching a
row sample from the remote table, which can be expensive.
Also add the function ImportStatistics which attempts to actually fetch
those statistics from the remote server, and if successful import them
into the local statistics catalog.
---
src/include/foreign/fdwapi.h | 8 ++++
src/backend/commands/analyze.c | 68 ++++++++++++++++++++++++----------
2 files changed, 56 insertions(+), 20 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..59beeae4f45 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef bool (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +261,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 53adac9139b..f175c0d8ed7 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -113,6 +113,9 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool can_import_stats = false;
+ bool stats_imported = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -195,27 +198,16 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
- {
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
- }
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ can_import_stats = true;
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
{
@@ -247,10 +239,46 @@ analyze_rel(Oid relid, RangeVar *relation,
PROGRESS_ANALYZE_STARTED_BY_MANUAL);
/*
- * Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * If this table can import statistics, attempt to do so.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (can_import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ stats_imported = fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+
+ /*
+ * Foreign tables that were not able to import stats will resort to
+ * regular sampling.
+ */
+ if ((onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
+ && !stats_imported)
+ {
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
+ }
+
+ /*
+ * Do the normal non-recursive ANALYZE. We can skip this for partitioned
+ * tables and foreign tables that successfully imported statistics.
+ */
+ if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ && !stats_imported)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
base-commit: 0123ce131fca454009439dfa3b2266d1d40737d7
--
2.53.0
v14-0002-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 37.3K) download
From 3178ba57a67ce9f63718f16fd9272866f42405b7 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:06:05 -0500
Subject: [PATCH v14 2/3] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via a new option, fetch_stats, which is available at the
server level and table level. The global default is true, but this can
be overriden by at the server level, which in turn can be overridden at
the table level.
If fetch_stats is true, and the remote table is an actual table or
materialized view that can hold statistics, and the local table does not
have any extended statistics objects built upon it, then the remote
database will first be queried for relation statistics and attribute
statistics similar to the method used in pg_dump.
If there are remote statistics for all of the columns in the local
table, then those statistics will be imported using
pg_restore_relation_statistics and pg_restore_attribute_statistics
functions similar to the way pg_restore uses them.
If fetch_stats is false, or if the fetched statistics were missing or
otherwise inadequate, then the ANALYZE operation will issue a WARNING
and then fall back to regular table sampling to generate local
statistics.
---
src/backend/commands/analyze.c | 3 +-
doc/src/sgml/postgres-fdw.sgml | 25 +-
.../postgres_fdw/expected/postgres_fdw.out | 17 +-
contrib/postgres_fdw/option.c | 5 +
contrib/postgres_fdw/postgres_fdw.c | 910 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 13 +-
6 files changed, 969 insertions(+), 4 deletions(-)
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index f175c0d8ed7..3128485578d 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -239,7 +239,8 @@ analyze_rel(Oid relid, RangeVar *relation,
PROGRESS_ANALYZE_STARTED_BY_MANUAL);
/*
- * If this table can import statistics, attempt to do so.
+ * If this table can import statistics, attempt to do so. If statistics
+ * import fails, then we will fall back to table sampling.
*/
if (can_import_stats)
{
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index de69ddcdebc..d7c0dc8ed14 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,29 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</function> and
+ <function>pg_restore_attribute_stats</function>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views). If the foreign table is a partition
+ of a partitioned table, analyzing the partitioned table will still
+ result in row sampling on the foreign table regardless of this setting,
+ though direct analysis of the foreign table would have attempted to
+ fetch remote statistics first.
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 0f5271d476e..a76f1278538 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4559,7 +4560,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11481,6 +11483,13 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+NOTICE: remote table public.base_tbl2 has no statistics to import
+HINT: Falling back to ANALYZE with regular row sampling.
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11587,6 +11596,12 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+NOTICE: remote table public.base_tbl3 has no statistics to import
+HINT: Falling back to ANALYZE with regular row sampling.
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..5b7726800d0 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +279,10 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 60d90329a65..c76ca2fc69b 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -18,10 +18,13 @@
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_opfamily.h"
+#include "catalog/pg_statistic_ext.h"
#include "commands/defrem.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -42,12 +45,14 @@
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
+#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
+#include "utils/syscache.h"
PG_MODULE_MAGIC_EXT(
.name = "postgres_fdw",
@@ -317,6 +322,21 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ char remote_attname[NAMEDATALEN];
+ AttrNumber local_attnum;
+ int res_index;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -402,6 +422,10 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresStatisticsAreImportable(Relation relation);
+static bool postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +570,188 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns
+{
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_NUM_FIELDS,
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+static const char *attstats_query_default =
+"SELECT s.attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\"";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns
+{
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS,
+};
+
+static const char *relimport_sql =
+"SELECT pg_catalog.pg_restore_relation_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'relpages', $4::integer,\n"
+"\t'reltuples', $5::real)";
+
+enum RelImportSqlArgs
+{
+ RELIMPORT_SQL_VERSION = 0,
+ RELIMPORT_SQL_SCHEMANAME,
+ RELIMPORT_SQL_RELNAME,
+ RELIMPORT_SQL_RELPAGES,
+ RELIMPORT_SQL_RELTUPLES,
+ RELIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid relimport_argtypes[RELIMPORT_SQL_NUM_FIELDS] = {
+INT4OID, TEXTOID, TEXTOID, TEXTOID, TEXTOID,};
+
+static const char *attimport_sql =
+"SELECT pg_catalog.pg_restore_attribute_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'attnum', $4,\n"
+"\t'inherited', false::boolean,\n"
+"\t'null_frac', $5::real,\n"
+"\t'avg_width', $6::integer,\n"
+"\t'n_distinct', $7::real,\n"
+"\t'most_common_vals', $8,\n"
+"\t'most_common_freqs', $9::real[],\n"
+"\t'histogram_bounds', $10,\n"
+"\t'correlation', $11::real,\n"
+"\t'most_common_elems', $12,\n"
+"\t'most_common_elem_freqs', $13::real[],\n"
+"\t'elem_count_histogram', $14::real[],\n"
+"\t'range_length_histogram', $15,\n"
+"\t'range_empty_frac', $16::real,\n"
+"\t'range_bounds_histogram', $17)";
+
+enum AttImportSqlArgs
+{
+ ATTIMPORT_SQL_VERSION = 0,
+ ATTIMPORT_SQL_SCHEMANAME,
+ ATTIMPORT_SQL_RELNAME,
+ ATTIMPORT_SQL_ATTNUM,
+ ATTIMPORT_SQL_NULL_FRAC,
+ ATTIMPORT_SQL_AVG_WIDTH,
+ ATTIMPORT_SQL_N_DISTINCT,
+ ATTIMPORT_SQL_MOST_COMMON_VALS,
+ ATTIMPORT_SQL_MOST_COMMON_FREQS,
+ ATTIMPORT_SQL_HISTOGRAM_BOUNDS,
+ ATTIMPORT_SQL_CORRELATION,
+ ATTIMPORT_SQL_MOST_COMMON_ELEMS,
+ ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS,
+ ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_EMPTY_FRAC,
+ ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM,
+ ATTIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid attimport_argtypes[ATTIMPORT_SQL_NUM_FIELDS] = {
+ INT4OID, TEXTOID, TEXTOID, INT2OID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+TEXTOID,};
+
+/* Pairs AttStatsColumns:AttImportSqlArgs Map */
+typedef struct
+{
+ enum AttStatsColumns res_field;
+ enum AttImportSqlArgs arg_num;
+} AttrResultArgMap;
+
+/*
+ * The mapping of attribute stats query columns to the positional arguments in
+ * the prepared pg_restore_attribute_stats() statement.
+ */
+#define NUM_MAPPED_ATTIMPORT_ARGS 13
+static const AttrResultArgMap attr_result_arg_map[NUM_MAPPED_ATTIMPORT_ARGS] = {
+ {ATTSTATS_NULL_FRAC, ATTIMPORT_SQL_NULL_FRAC},
+ {ATTSTATS_AVG_WIDTH, ATTIMPORT_SQL_AVG_WIDTH},
+ {ATTSTATS_N_DISTINCT, ATTIMPORT_SQL_N_DISTINCT},
+ {ATTSTATS_MOST_COMMON_VALS, ATTIMPORT_SQL_MOST_COMMON_VALS},
+ {ATTSTATS_MOST_COMMON_FREQS, ATTIMPORT_SQL_MOST_COMMON_FREQS},
+ {ATTSTATS_HISTOGRAM_BOUNDS, ATTIMPORT_SQL_HISTOGRAM_BOUNDS},
+ {ATTSTATS_CORRELATION, ATTIMPORT_SQL_CORRELATION},
+ {ATTSTATS_MOST_COMMON_ELEMS, ATTIMPORT_SQL_MOST_COMMON_ELEMS},
+ {ATTSTATS_MOST_COMMON_ELEM_FREQS, ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS},
+ {ATTSTATS_ELEM_COUNT_HISTOGRAM, ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM},
+ {ATTSTATS_RANGE_LENGTH_HISTOGRAM, ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM},
+ {ATTSTATS_RANGE_EMPTY_FRAC, ATTIMPORT_SQL_RANGE_EMPTY_FRAC},
+ {ATTSTATS_RANGE_BOUNDS_HISTOGRAM, ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM},
+};
+
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +801,8 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->StatisticsAreImportable = postgresStatisticsAreImportable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5143,708 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Move a string value from a result set to a Text value of a Datum array.
+ */
+static void
+map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls)
+{
+ if (PQgetisnull(res, row, field))
+ {
+ values[arg] = (Datum) 0;
+ nulls[arg] = 'n';
+ }
+ else
+ {
+ const char *s = PQgetvalue(res, row, field);
+
+ values[arg] = CStringGetTextDatum(s);
+ nulls[arg] = ' ';
+ }
+}
+
+/*
+ * Check the 1x1 result set of a pg_restore_*_stats() command for success.
+ */
+static bool
+import_spi_query_ok(int spirc)
+{
+ char *s;
+ bool ok;
+
+ if (spirc != SPI_OK_SELECT
+ || SPI_tuptable == NULL
+ || SPI_processed != 1)
+ return false;
+
+ s = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
+
+ ok = (s != NULL && s[0] == 't' && s[1] == '\0');
+ pfree(s);
+
+ return ok;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static bool
+import_fetched_statistics(const char *schemaname, const char *relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping * remattrmap,
+ RemoteStatsResults * remstats)
+{
+ SPIPlanPtr plan = NULL;
+ PGresult *res = remstats->att;
+ int spirc;
+ Datum values[ATTIMPORT_SQL_NUM_FIELDS];
+ char nulls[ATTIMPORT_SQL_NUM_FIELDS];
+ bool ok = false;
+
+ /* Assign all the invariant parameters */
+ values[ATTIMPORT_SQL_VERSION] = Int32GetDatum(server_version_num);
+ nulls[ATTIMPORT_SQL_VERSION] = ' ';
+
+ values[ATTIMPORT_SQL_SCHEMANAME] = CStringGetTextDatum(schemaname);
+ nulls[ATTIMPORT_SQL_SCHEMANAME] = ' ';
+
+ values[ATTIMPORT_SQL_RELNAME] = CStringGetTextDatum(relname);
+ nulls[ATTIMPORT_SQL_RELNAME] = ' ';
+
+ nulls[ATTIMPORT_SQL_ATTNUM] = ' ';
+
+ SPI_connect();
+
+ plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+
+ if (plan == NULL || SPI_result < 0)
+ {
+ ereport(WARNING,
+ errmsg("import attribute statistics prepare failed %s "
+ "with error code %d",
+ attimport_sql, SPI_result));
+ goto import_cleanup;
+ }
+
+ /*
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ for (int mapidx = 0; mapidx < natts; mapidx++)
+ {
+ int row = remattrmap[mapidx].res_index;
+
+ /* All mappings should have been assigned a result set row. */
+ Assert(row >= 0);
+
+ values[ATTIMPORT_SQL_ATTNUM] =
+ Int16GetDatum(remattrmap[mapidx].local_attnum);
+
+ /* Loop through all mappable columns->arguments */
+ for (int i = 0; i < NUM_MAPPED_ATTIMPORT_ARGS; i++)
+ map_field_to_arg(res, row,
+ attr_result_arg_map[i].res_field,
+ attr_result_arg_map[i].arg_num,
+ values, nulls);
+
+ spirc = SPI_execute_plan(plan, values, nulls, false, 0);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("attribute statistics import failed %s",
+ attimport_sql));
+ goto import_cleanup;
+ }
+ }
+
+ /*
+ * Import relstats.
+ *
+ * Import relation stats. We only perform this once, so there is no point
+ * in preparing the statement.
+ *
+ * We can re-use the values/nulls because the number of parameters is less
+ * and the first three params are the same as attstats_import.
+ */
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELPAGES,
+ RELIMPORT_SQL_RELPAGES, values, nulls);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELTUPLES,
+ RELIMPORT_SQL_RELTUPLES, values, nulls);
+
+ spirc = SPI_execute_with_args(relimport_sql, RELIMPORT_SQL_NUM_FIELDS,
+ (Oid *) relimport_argtypes,
+ values, nulls, false, 1);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("relation statistics import failed %s",
+ relimport_sql));
+ goto import_cleanup;
+ }
+
+ ok = true;
+
+import_cleanup:
+ if (plan)
+ SPI_freeplan(plan);
+ SPI_finish();
+ return ok;
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname)
+{
+ const char *params[2] = {remote_schemaname, remote_relname};
+
+ const char *sql = "SELECT c.relkind, c.relpages, c.reltuples "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n "
+ "ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+ PGresult *res = NULL;
+
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(NULL, conn, sql);
+
+ if (PQntuples(res) != 1 ||
+ PQnfields(res) != RELSTATS_NUM_FIELDS ||
+ PQgetisnull(res, 0, RELSTATS_RELKIND))
+ elog(ERROR, "unexpected result from fetch_relstats query");
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list)
+{
+ const char *params[3] = {remote_schemaname, remote_relname, column_list};
+ const char *sql;
+ PGresult *res;
+
+ if (server_version_num >= 170000)
+ sql = attstats_query_17;
+ else if (server_version_num >= 90200)
+ sql = attstats_query_9_2;
+ else if (server_version_num >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(NULL, conn, sql);
+
+ if (PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ return res;
+}
+
+/*
+ * Match result set rows to local attnums.
+ *
+ * Every row of the result should be an attribute that we specifically
+ * filtered for, so every row should have at least one match in the
+ * RemoteAttributeMapping, which is also ordered by attname, so we only
+ * need to walk that array once.
+ */
+static
+bool
+match_attrmap(PGresult *res, const char *remote_schemaname,
+ const char *remote_relname, int natts,
+ RemoteAttributeMapping * remattrmap)
+{
+ int mapidx = 0;
+
+ for (int row = 0; row < PQntuples(res); row++)
+ {
+ char *remote_attname;
+ bool match_found = false;
+ int cmp = 0;
+
+ if (PQgetisnull(res, row, ATTSTATS_ATTNAME))
+ elog(ERROR,
+ "remote statistics returned a row with NULL attribute name");
+
+ remote_attname = PQgetvalue(res, row, ATTSTATS_ATTNAME);
+
+ /*
+ * Scan the remote attribute map for matching names. The first one
+ * should be a match but there may also be others. For each match,
+ * assign the result set row number to that entry.
+ *
+ * Remember the type of comparison (< or >) that caused us to break
+ * out of the loop.
+ */
+ for (; mapidx < natts; mapidx++)
+ {
+ cmp = strcmp(remote_attname, remattrmap[mapidx].remote_attname);
+
+ /* Stop scanning on the first non-match */
+ if (cmp != 0)
+ break;
+
+ match_found = true;
+ remattrmap[mapidx].res_index = row;
+ }
+
+ /*
+ * If we found at least one match, move onto the next result.
+ */
+ if (match_found)
+ continue;
+
+ /*
+ * If we didn't find a match, then either the list is out of order,
+ * either the map is out of order or we got a row that we didn't ask
+ * for.
+ */
+ if (cmp > 0)
+ {
+ /* We expected a stats for a column, but found none. */
+ ereport(LOG,
+ errmsg("no remote statistics found for %s of %s.%s",
+ remattrmap[mapidx].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+ else
+ {
+ /*
+ * We got a stat row that we didn't expect. This is a sign that
+ * the query was flawed, which is concerning but not a reason to
+ * block fallback to regular sampling.
+ */
+ ereport(WARNING,
+ errmsg("extra remote statistics found for %s of %s.%s",
+ remote_attname, remote_schemaname, remote_relname));
+ return false;
+ }
+ }
+
+ if (mapidx < natts)
+ {
+ /* We exhausted the result set before mapping all attributes. */
+ ereport(LOG,
+ errmsg("no remote statistics found for %s of %s.%s",
+ remattrmap[mapidx].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ return true;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static bool
+fetch_remote_statistics(PGconn *conn,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int server_version_num, int natts,
+ RemoteAttributeMapping * remattrmap,
+ const char *column_list,
+ RemoteStatsResults * remstats)
+{
+ PGresult *attstats = NULL;
+ PGresult *relstats = NULL;
+
+ char relkind;
+ char *reltuples;
+
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
+ * can't support a foreign table.
+ */
+ relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
+
+ switch (relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ ereport(WARNING,
+ errmsg("remote table %s.%s is of relkind %c which cannot have statistics",
+ remote_schemaname, remote_relname, relkind),
+ errhint("Falling back to ANALYZE with regular row sampling."));
+ goto cleanup;
+ }
+
+ /*
+ * If the reltuples value > 0, then then we can expect to find attribute
+ * stats for the table.
+ *
+ * A reltuples value of -1 means the table has never been analyzed (v14+).
+ *
+ * In versions prior to v14, a value of 0 was ambiguous, it could mean
+ * that the table had never been analyzed, or that it was empty at the
+ * time that it was analyzed. Either way, we wouldn't expect to find
+ * attstats for the relation.
+ */
+ reltuples = PQgetvalue(relstats, 0, RELSTATS_RELTUPLES);
+ if ((strcmp(reltuples, "0") == 0) ||
+ (strcmp(reltuples, "-1") == 0))
+ goto notfound;
+
+ /* See if it actually has any attribute stats. */
+ attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
+ remote_relname, column_list);
+
+ if (PQntuples(attstats) == 0)
+ goto notfound;
+
+ /* Reject the stats if any are missing or in excess. */
+ if (!match_attrmap(attstats, remote_schemaname, remote_relname, natts,
+ remattrmap))
+ goto cleanup;
+
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+
+notfound:
+ ereport(NOTICE,
+ errmsg("remote table %s.%s has no statistics to import",
+ remote_schemaname, remote_relname),
+ errhint("Falling back to ANALYZE with regular row sampling."));
+cleanup:
+ PQclear(attstats);
+ PQclear(relstats);
+ return false;
+}
+
+/*
+ * Test if the relation has extended statistics objects.
+ */
+static bool
+table_has_extended_stats(Relation relation)
+{
+ Relation pg_statext;
+ SysScanDesc scan;
+ ScanKeyData skey;
+ bool found;
+
+ pg_statext = table_open(StatisticExtRelationId, RowExclusiveLock);
+
+ /*
+ * Prepare to scan pg_statistic_ext for entries having stxrelid = this
+ * rel.
+ */
+ ScanKeyInit(&skey,
+ Anum_pg_statistic_ext_stxrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(relation)));
+
+ scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
+ NULL, 1, &skey);
+
+ found = (systable_getnext(scan) != NULL);
+
+ systable_endscan(scan);
+
+ table_close(pg_statext, RowExclusiveLock);
+
+ return found;
+}
+
+static bool
+postgresStatisticsAreImportable(Relation relation)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ ListCell *lc;
+ bool fetch_stats = true;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ /*
+ * Additional checks that can disqualify a table from importing stats.
+ */
+ if (fetch_stats)
+ {
+ /*
+ * We can't compute extended stats from the column stats, for that we
+ * need a table sample.
+ */
+ if (table_has_extended_stats(relation))
+ {
+ ereport(WARNING,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("cannot import statistics for foreign table \"%s\" "
+ "because it has extended statistics objects.",
+ RelationGetRelationName(relation)));
+ fetch_stats = false;
+ }
+ }
+
+ return fetch_stats;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Fetch attstattarget from a pg_attribute tuple.
+ */
+static int16
+get_attstattarget(Relation relation, AttrNumber attnum)
+{
+ HeapTuple atttuple;
+ bool isnull;
+ Datum dat;
+ int16 attstattarget;
+ Oid relid = RelationGetRelid(relation);
+
+ atttuple = SearchSysCache2(ATTNUM,
+ ObjectIdGetDatum(relid),
+ Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, relid);
+ dat = SysCacheGetAttr(ATTNUM, atttuple,
+ Anum_pg_attribute_attstattarget,
+ &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ return attstattarget;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static bool
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+
+ ForeignTable *table;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int natts = 0;
+ bool ok = false;
+
+ RemoteAttributeMapping *remattrmap;
+ StringInfoData column_list;
+
+ RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ }
+
+ /*
+ * Assume the relation/schema names are the same as the local name unless
+ * the options tell us otherwise.
+ */
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ /*
+ * Build attnum/remote-attname map and column list.
+ */
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ initStringInfo(&column_list);
+ appendStringInfoChar(&column_list, '{');
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *attname;
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+
+ /* Ignore dropped columns. */
+ if (attr->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (attr->attgenerated)
+ continue;
+
+ attname = NameStr(attr->attname);
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ attnum = attr->attnum;
+
+ /* Ignore if attstatarget is 0 */
+ if (get_attstattarget(relation, attnum) == 0)
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_colname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ if (i > 0)
+ appendStringInfoChar(&column_list, ',');
+ appendStringInfoString(&column_list, quote_identifier(remote_colname));
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].remote_attname, remote_colname, NAMEDATALEN);
+ remattrmap[natts].res_index = -1;
+ natts++;
+ }
+ appendStringInfoChar(&column_list, '}');
+
+ /* Sort mapping by remote attribute name */
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
+ server_version_num, natts, remattrmap,
+ column_list.data, &remstats);
+
+ ReleaseConnection(conn);
+ pfree(column_list.data);
+
+ if (ok)
+ {
+ Assert(remstats.rel != NULL);
+ Assert(PQnfields(remstats.rel) == RELSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.rel) == 1);
+ Assert(remstats.att != NULL);
+ Assert(PQnfields(remstats.att) == ATTSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.att) >= 1);
+ ok = import_fetched_statistics(schemaname, relname, server_version_num,
+ natts, remattrmap, &remstats);
+ }
+
+ pfree(remattrmap);
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+ return ok;
+}
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 49ed797e8ef..a0f52e57dbc 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1293,7 +1294,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3917,6 +3919,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3954,6 +3961,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
--
2.53.0
v14-0003-Add-remote_analyze-to-postgres_fdw-remote-statis.patch (text/x-patch, 13.3K) download
From f05cfecc37b3a8ac687fe862b3f096c088e4e31a Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:33:53 -0500
Subject: [PATCH v14 3/3] Add remote_analyze to postgres_fdw remote statistics
fetching.
This is accomplished through a new option, remote_analyze, which is
available at the server level and table level. The default value is
false.
If remote_analyze is enabled, and if the first attempt to fetch remote
statistics did not fetch attribute statistics for every local table
column, then an attempt will be made to ANALYZE the remote table. If
that remote ANALYZE succeeds, then a second and final attempt will be
made to fetch remote statistics. If the statistics found are still
insufficient, then the local ANALYZE command will fall back to regular
row sampling and computing the statistics locally.
---
doc/src/sgml/postgres-fdw.sgml | 16 ++
.../postgres_fdw/expected/postgres_fdw.out | 38 +++++
contrib/postgres_fdw/option.c | 5 +
contrib/postgres_fdw/postgres_fdw.c | 150 ++++++++++++++----
contrib/postgres_fdw/sql/postgres_fdw.sql | 34 ++++
5 files changed, 214 insertions(+), 29 deletions(-)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index d7c0dc8ed14..4c7559dad6f 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -387,6 +387,22 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ has no meaning if the foreign table has <literal>fetch_stats</literal>
+ disabled.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index a76f1278538..f7a578d267d 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -12699,6 +12699,44 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 5b7726800d0..2941ecbfb87 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -121,6 +121,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -283,6 +284,10 @@ InitPgFdwOptions(void)
{"fetch_stats", ForeignServerRelationId, false},
{"fetch_stats", ForeignTableRelationId, false},
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index c76ca2fc69b..5f79ea57e73 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -5319,6 +5319,36 @@ import_cleanup:
return ok;
}
+/*
+ * Analyze a remote table.
+ */
+static bool
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+ bool ok = true;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s",
+ quote_qualified_identifier(remote_schemaname, remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL ||
+ PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ pgfdw_report(WARNING, res, conn, buf.data);
+ ok = false;
+ }
+
+ PQclear(res);
+ pfree(buf.data);
+ return ok;
+}
+
/*
* Attempt to fetch remote relations stats.
*/
@@ -5482,6 +5512,33 @@ match_attrmap(PGresult *res, const char *remote_schemaname,
return true;
}
+/*
+ * Convenience routine to test if the relstats result set shows that the
+ * relation has tuples.
+ */
+static
+bool
+has_tuples(PGresult *relstats)
+{
+ char *reltuples;
+
+ reltuples = PQgetvalue(relstats, 0, RELSTATS_RELTUPLES);
+
+ /*
+ * If the reltuples value > 0, then then we can expect to find attribute
+ * stats for the table.
+ *
+ * A reltuples value of -1 means the table has never been analyzed (v14+).
+ *
+ * In versions prior to v14, a value of 0 was ambiguous, it could mean
+ * that the table had never been analyzed, or that it was empty at the
+ * time that it was analyzed. Either way, we wouldn't expect to find
+ * attstats for the relation.
+ */
+ return ((strcmp(reltuples, "0") != 0) &&
+ (strcmp(reltuples, "-1") != 0));
+}
+
/*
* Attempt to fetch statistics from a remote server.
*/
@@ -5492,13 +5549,13 @@ fetch_remote_statistics(PGconn *conn,
int server_version_num, int natts,
RemoteAttributeMapping * remattrmap,
const char *column_list,
- RemoteStatsResults * remstats)
+ bool remote_analyze, RemoteStatsResults * remstats)
{
PGresult *attstats = NULL;
PGresult *relstats = NULL;
char relkind;
- char *reltuples;
+ bool has_stats = false;
relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
@@ -5527,34 +5584,51 @@ fetch_remote_statistics(PGconn *conn,
goto cleanup;
}
+ if (has_tuples(relstats))
+ {
+ /* See if the table actually has attribute stats. */
+ attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
+ remote_relname, column_list);
+
+ if ((PQntuples(attstats) > 0) &&
+ match_attrmap(attstats, remote_schemaname, remote_relname,
+ natts, remattrmap))
+ has_stats = true;
+ }
+
+ if (!has_stats)
+ {
+ /* If no second chance, skip to reporting no stats found */
+ if (!remote_analyze)
+ goto notfound;
+
+ ereport(LOG,
+ errmsg("attempting remote analyze of table %s.%s",
+ remote_schemaname, remote_relname));
+ PQclear(attstats);
+ PQclear(relstats);
+
+ if (!analyze_remote_table(conn, remote_schemaname, remote_relname))
+ goto cleanup;
+
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+ if (!has_tuples(relstats))
+ goto notfound;
+
+ attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
+ remote_relname, column_list);
+
+ if (PQntuples(attstats) == 0)
+ goto notfound;
+
+ if (!match_attrmap(attstats, remote_schemaname, remote_relname,
+ natts, remattrmap))
+ goto cleanup;
+ }
+
/*
- * If the reltuples value > 0, then then we can expect to find attribute
- * stats for the table.
- *
- * A reltuples value of -1 means the table has never been analyzed (v14+).
- *
- * In versions prior to v14, a value of 0 was ambiguous, it could mean
- * that the table had never been analyzed, or that it was empty at the
- * time that it was analyzed. Either way, we wouldn't expect to find
- * attstats for the relation.
+ * We found stats, on either the first try or the second.
*/
- reltuples = PQgetvalue(relstats, 0, RELSTATS_RELTUPLES);
- if ((strcmp(reltuples, "0") == 0) ||
- (strcmp(reltuples, "-1") == 0))
- goto notfound;
-
- /* See if it actually has any attribute stats. */
- attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
- remote_relname, column_list);
-
- if (PQntuples(attstats) == 0)
- goto notfound;
-
- /* Reject the stats if any are missing or in excess. */
- if (!match_attrmap(attstats, remote_schemaname, remote_relname, natts,
- remattrmap))
- goto cleanup;
-
remstats->rel = relstats;
remstats->att = attstats;
return true;
@@ -5712,9 +5786,11 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
{
ForeignTable *table;
+ ForeignServer *server;
UserMapping *user;
PGconn *conn;
ListCell *lc;
+ bool remote_analyze = false;
int server_version_num = 0;
const char *schemaname = NULL;
const char *relname = NULL;
@@ -5730,12 +5806,25 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
user = GetUserMapping(GetUserId(), table->serverid);
conn = GetConnection(user, false, NULL);
server_version_num = PQserverVersion(conn);
schemaname = get_namespace_name(RelationGetNamespace(relation));
relname = RelationGetRelationName(relation);
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
foreach(lc, table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
@@ -5744,6 +5833,8 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
remote_schemaname = defGetString(def);
else if (strcmp(def->defname, "table_name") == 0)
remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
}
/*
@@ -5822,7 +5913,8 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
server_version_num, natts, remattrmap,
- column_list.data, &remstats);
+ column_list.data, remote_analyze,
+ &remstats);
ReleaseConnection(conn);
pfree(column_list.data);
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index a0f52e57dbc..3390f6e5ec1 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -4412,6 +4412,40 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
--
2.53.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-14 20:05 Corey Huinker <corey.huinker@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
2 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-03-14 20:05 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
>
> I've also moved the column matching - finding which rows of the attstats
> result set match to which columns in the local table - up into the fetch
> portion, something you had mentioned wanting to see as well. This resulted
> in some significant refactoring, but overall I think you will find the
> changes for the better.
>
I've added a reset of the result set indexes. Probably not necessary given
that we only keep the result set if all the columns found homes, but good
for peace of mind.
Attachments: download all (3 files, .tar.gz)
v15-0001-Add-FDW-functions-for-importing-optimizer-statis.patch (text/x-patch, 5.0K) download
From aff24e106b88de903f4a1b563485a7adee9438ad Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 16:39:45 -0500
Subject: [PATCH v15 1/3] Add FDW functions for importing optimizer statistics.
Add the the function StatisticsAreImportable which is used as a
lightweight preliminary scan to determine if the remote table could
potentially have statistics that could be imported instead of fetching a
row sample from the remote table, which can be expensive.
Also add the function ImportStatistics which attempts to actually fetch
those statistics from the remote server, and if successful import them
into the local statistics catalog.
---
src/include/foreign/fdwapi.h | 8 ++++
src/backend/commands/analyze.c | 68 ++++++++++++++++++++++++----------
2 files changed, 56 insertions(+), 20 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..59beeae4f45 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef bool (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +261,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 53adac9139b..f175c0d8ed7 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -113,6 +113,9 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool can_import_stats = false;
+ bool stats_imported = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -195,27 +198,16 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
- {
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
- }
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ can_import_stats = true;
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
{
@@ -247,10 +239,46 @@ analyze_rel(Oid relid, RangeVar *relation,
PROGRESS_ANALYZE_STARTED_BY_MANUAL);
/*
- * Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * If this table can import statistics, attempt to do so.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (can_import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ stats_imported = fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+
+ /*
+ * Foreign tables that were not able to import stats will resort to
+ * regular sampling.
+ */
+ if ((onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
+ && !stats_imported)
+ {
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
+ }
+
+ /*
+ * Do the normal non-recursive ANALYZE. We can skip this for partitioned
+ * tables and foreign tables that successfully imported statistics.
+ */
+ if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ && !stats_imported)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
base-commit: 0123ce131fca454009439dfa3b2266d1d40737d7
--
2.53.0
v15-0002-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 37.3K) download
From 3178ba57a67ce9f63718f16fd9272866f42405b7 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:06:05 -0500
Subject: [PATCH v15 2/3] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via a new option, fetch_stats, which is available at the
server level and table level. The global default is true, but this can
be overriden by at the server level, which in turn can be overridden at
the table level.
If fetch_stats is true, and the remote table is an actual table or
materialized view that can hold statistics, and the local table does not
have any extended statistics objects built upon it, then the remote
database will first be queried for relation statistics and attribute
statistics similar to the method used in pg_dump.
If there are remote statistics for all of the columns in the local
table, then those statistics will be imported using
pg_restore_relation_statistics and pg_restore_attribute_statistics
functions similar to the way pg_restore uses them.
If fetch_stats is false, or if the fetched statistics were missing or
otherwise inadequate, then the ANALYZE operation will issue a WARNING
and then fall back to regular table sampling to generate local
statistics.
---
src/backend/commands/analyze.c | 3 +-
doc/src/sgml/postgres-fdw.sgml | 25 +-
.../postgres_fdw/expected/postgres_fdw.out | 17 +-
contrib/postgres_fdw/option.c | 5 +
contrib/postgres_fdw/postgres_fdw.c | 910 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 13 +-
6 files changed, 969 insertions(+), 4 deletions(-)
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index f175c0d8ed7..3128485578d 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -239,7 +239,8 @@ analyze_rel(Oid relid, RangeVar *relation,
PROGRESS_ANALYZE_STARTED_BY_MANUAL);
/*
- * If this table can import statistics, attempt to do so.
+ * If this table can import statistics, attempt to do so. If statistics
+ * import fails, then we will fall back to table sampling.
*/
if (can_import_stats)
{
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index de69ddcdebc..d7c0dc8ed14 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,29 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</function> and
+ <function>pg_restore_attribute_stats</function>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views). If the foreign table is a partition
+ of a partitioned table, analyzing the partitioned table will still
+ result in row sampling on the foreign table regardless of this setting,
+ though direct analysis of the foreign table would have attempted to
+ fetch remote statistics first.
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 0f5271d476e..a76f1278538 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4559,7 +4560,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11481,6 +11483,13 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+NOTICE: remote table public.base_tbl2 has no statistics to import
+HINT: Falling back to ANALYZE with regular row sampling.
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11587,6 +11596,12 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+NOTICE: remote table public.base_tbl3 has no statistics to import
+HINT: Falling back to ANALYZE with regular row sampling.
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..5b7726800d0 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +279,10 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 60d90329a65..c76ca2fc69b 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -18,10 +18,13 @@
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_opfamily.h"
+#include "catalog/pg_statistic_ext.h"
#include "commands/defrem.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -42,12 +45,14 @@
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
+#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
+#include "utils/syscache.h"
PG_MODULE_MAGIC_EXT(
.name = "postgres_fdw",
@@ -317,6 +322,21 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ char remote_attname[NAMEDATALEN];
+ AttrNumber local_attnum;
+ int res_index;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -402,6 +422,10 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresStatisticsAreImportable(Relation relation);
+static bool postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -546,6 +570,188 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns
+{
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_NUM_FIELDS,
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+static const char *attstats_query_default =
+"SELECT s.attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\"";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns
+{
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS,
+};
+
+static const char *relimport_sql =
+"SELECT pg_catalog.pg_restore_relation_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'relpages', $4::integer,\n"
+"\t'reltuples', $5::real)";
+
+enum RelImportSqlArgs
+{
+ RELIMPORT_SQL_VERSION = 0,
+ RELIMPORT_SQL_SCHEMANAME,
+ RELIMPORT_SQL_RELNAME,
+ RELIMPORT_SQL_RELPAGES,
+ RELIMPORT_SQL_RELTUPLES,
+ RELIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid relimport_argtypes[RELIMPORT_SQL_NUM_FIELDS] = {
+INT4OID, TEXTOID, TEXTOID, TEXTOID, TEXTOID,};
+
+static const char *attimport_sql =
+"SELECT pg_catalog.pg_restore_attribute_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'attnum', $4,\n"
+"\t'inherited', false::boolean,\n"
+"\t'null_frac', $5::real,\n"
+"\t'avg_width', $6::integer,\n"
+"\t'n_distinct', $7::real,\n"
+"\t'most_common_vals', $8,\n"
+"\t'most_common_freqs', $9::real[],\n"
+"\t'histogram_bounds', $10,\n"
+"\t'correlation', $11::real,\n"
+"\t'most_common_elems', $12,\n"
+"\t'most_common_elem_freqs', $13::real[],\n"
+"\t'elem_count_histogram', $14::real[],\n"
+"\t'range_length_histogram', $15,\n"
+"\t'range_empty_frac', $16::real,\n"
+"\t'range_bounds_histogram', $17)";
+
+enum AttImportSqlArgs
+{
+ ATTIMPORT_SQL_VERSION = 0,
+ ATTIMPORT_SQL_SCHEMANAME,
+ ATTIMPORT_SQL_RELNAME,
+ ATTIMPORT_SQL_ATTNUM,
+ ATTIMPORT_SQL_NULL_FRAC,
+ ATTIMPORT_SQL_AVG_WIDTH,
+ ATTIMPORT_SQL_N_DISTINCT,
+ ATTIMPORT_SQL_MOST_COMMON_VALS,
+ ATTIMPORT_SQL_MOST_COMMON_FREQS,
+ ATTIMPORT_SQL_HISTOGRAM_BOUNDS,
+ ATTIMPORT_SQL_CORRELATION,
+ ATTIMPORT_SQL_MOST_COMMON_ELEMS,
+ ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS,
+ ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_EMPTY_FRAC,
+ ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM,
+ ATTIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid attimport_argtypes[ATTIMPORT_SQL_NUM_FIELDS] = {
+ INT4OID, TEXTOID, TEXTOID, INT2OID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+TEXTOID,};
+
+/* Pairs AttStatsColumns:AttImportSqlArgs Map */
+typedef struct
+{
+ enum AttStatsColumns res_field;
+ enum AttImportSqlArgs arg_num;
+} AttrResultArgMap;
+
+/*
+ * The mapping of attribute stats query columns to the positional arguments in
+ * the prepared pg_restore_attribute_stats() statement.
+ */
+#define NUM_MAPPED_ATTIMPORT_ARGS 13
+static const AttrResultArgMap attr_result_arg_map[NUM_MAPPED_ATTIMPORT_ARGS] = {
+ {ATTSTATS_NULL_FRAC, ATTIMPORT_SQL_NULL_FRAC},
+ {ATTSTATS_AVG_WIDTH, ATTIMPORT_SQL_AVG_WIDTH},
+ {ATTSTATS_N_DISTINCT, ATTIMPORT_SQL_N_DISTINCT},
+ {ATTSTATS_MOST_COMMON_VALS, ATTIMPORT_SQL_MOST_COMMON_VALS},
+ {ATTSTATS_MOST_COMMON_FREQS, ATTIMPORT_SQL_MOST_COMMON_FREQS},
+ {ATTSTATS_HISTOGRAM_BOUNDS, ATTIMPORT_SQL_HISTOGRAM_BOUNDS},
+ {ATTSTATS_CORRELATION, ATTIMPORT_SQL_CORRELATION},
+ {ATTSTATS_MOST_COMMON_ELEMS, ATTIMPORT_SQL_MOST_COMMON_ELEMS},
+ {ATTSTATS_MOST_COMMON_ELEM_FREQS, ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS},
+ {ATTSTATS_ELEM_COUNT_HISTOGRAM, ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM},
+ {ATTSTATS_RANGE_LENGTH_HISTOGRAM, ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM},
+ {ATTSTATS_RANGE_EMPTY_FRAC, ATTIMPORT_SQL_RANGE_EMPTY_FRAC},
+ {ATTSTATS_RANGE_BOUNDS_HISTOGRAM, ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM},
+};
+
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -595,6 +801,8 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->StatisticsAreImportable = postgresStatisticsAreImportable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4935,6 +5143,708 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Move a string value from a result set to a Text value of a Datum array.
+ */
+static void
+map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls)
+{
+ if (PQgetisnull(res, row, field))
+ {
+ values[arg] = (Datum) 0;
+ nulls[arg] = 'n';
+ }
+ else
+ {
+ const char *s = PQgetvalue(res, row, field);
+
+ values[arg] = CStringGetTextDatum(s);
+ nulls[arg] = ' ';
+ }
+}
+
+/*
+ * Check the 1x1 result set of a pg_restore_*_stats() command for success.
+ */
+static bool
+import_spi_query_ok(int spirc)
+{
+ char *s;
+ bool ok;
+
+ if (spirc != SPI_OK_SELECT
+ || SPI_tuptable == NULL
+ || SPI_processed != 1)
+ return false;
+
+ s = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
+
+ ok = (s != NULL && s[0] == 't' && s[1] == '\0');
+ pfree(s);
+
+ return ok;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static bool
+import_fetched_statistics(const char *schemaname, const char *relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping * remattrmap,
+ RemoteStatsResults * remstats)
+{
+ SPIPlanPtr plan = NULL;
+ PGresult *res = remstats->att;
+ int spirc;
+ Datum values[ATTIMPORT_SQL_NUM_FIELDS];
+ char nulls[ATTIMPORT_SQL_NUM_FIELDS];
+ bool ok = false;
+
+ /* Assign all the invariant parameters */
+ values[ATTIMPORT_SQL_VERSION] = Int32GetDatum(server_version_num);
+ nulls[ATTIMPORT_SQL_VERSION] = ' ';
+
+ values[ATTIMPORT_SQL_SCHEMANAME] = CStringGetTextDatum(schemaname);
+ nulls[ATTIMPORT_SQL_SCHEMANAME] = ' ';
+
+ values[ATTIMPORT_SQL_RELNAME] = CStringGetTextDatum(relname);
+ nulls[ATTIMPORT_SQL_RELNAME] = ' ';
+
+ nulls[ATTIMPORT_SQL_ATTNUM] = ' ';
+
+ SPI_connect();
+
+ plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+
+ if (plan == NULL || SPI_result < 0)
+ {
+ ereport(WARNING,
+ errmsg("import attribute statistics prepare failed %s "
+ "with error code %d",
+ attimport_sql, SPI_result));
+ goto import_cleanup;
+ }
+
+ /*
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ for (int mapidx = 0; mapidx < natts; mapidx++)
+ {
+ int row = remattrmap[mapidx].res_index;
+
+ /* All mappings should have been assigned a result set row. */
+ Assert(row >= 0);
+
+ values[ATTIMPORT_SQL_ATTNUM] =
+ Int16GetDatum(remattrmap[mapidx].local_attnum);
+
+ /* Loop through all mappable columns->arguments */
+ for (int i = 0; i < NUM_MAPPED_ATTIMPORT_ARGS; i++)
+ map_field_to_arg(res, row,
+ attr_result_arg_map[i].res_field,
+ attr_result_arg_map[i].arg_num,
+ values, nulls);
+
+ spirc = SPI_execute_plan(plan, values, nulls, false, 0);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("attribute statistics import failed %s",
+ attimport_sql));
+ goto import_cleanup;
+ }
+ }
+
+ /*
+ * Import relstats.
+ *
+ * Import relation stats. We only perform this once, so there is no point
+ * in preparing the statement.
+ *
+ * We can re-use the values/nulls because the number of parameters is less
+ * and the first three params are the same as attstats_import.
+ */
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELPAGES,
+ RELIMPORT_SQL_RELPAGES, values, nulls);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELTUPLES,
+ RELIMPORT_SQL_RELTUPLES, values, nulls);
+
+ spirc = SPI_execute_with_args(relimport_sql, RELIMPORT_SQL_NUM_FIELDS,
+ (Oid *) relimport_argtypes,
+ values, nulls, false, 1);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("relation statistics import failed %s",
+ relimport_sql));
+ goto import_cleanup;
+ }
+
+ ok = true;
+
+import_cleanup:
+ if (plan)
+ SPI_freeplan(plan);
+ SPI_finish();
+ return ok;
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname)
+{
+ const char *params[2] = {remote_schemaname, remote_relname};
+
+ const char *sql = "SELECT c.relkind, c.relpages, c.reltuples "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n "
+ "ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+ PGresult *res = NULL;
+
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(NULL, conn, sql);
+
+ if (PQntuples(res) != 1 ||
+ PQnfields(res) != RELSTATS_NUM_FIELDS ||
+ PQgetisnull(res, 0, RELSTATS_RELKIND))
+ elog(ERROR, "unexpected result from fetch_relstats query");
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list)
+{
+ const char *params[3] = {remote_schemaname, remote_relname, column_list};
+ const char *sql;
+ PGresult *res;
+
+ if (server_version_num >= 170000)
+ sql = attstats_query_17;
+ else if (server_version_num >= 90200)
+ sql = attstats_query_9_2;
+ else if (server_version_num >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(NULL, conn, sql);
+
+ if (PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ return res;
+}
+
+/*
+ * Match result set rows to local attnums.
+ *
+ * Every row of the result should be an attribute that we specifically
+ * filtered for, so every row should have at least one match in the
+ * RemoteAttributeMapping, which is also ordered by attname, so we only
+ * need to walk that array once.
+ */
+static
+bool
+match_attrmap(PGresult *res, const char *remote_schemaname,
+ const char *remote_relname, int natts,
+ RemoteAttributeMapping * remattrmap)
+{
+ int mapidx = 0;
+
+ for (int row = 0; row < PQntuples(res); row++)
+ {
+ char *remote_attname;
+ bool match_found = false;
+ int cmp = 0;
+
+ if (PQgetisnull(res, row, ATTSTATS_ATTNAME))
+ elog(ERROR,
+ "remote statistics returned a row with NULL attribute name");
+
+ remote_attname = PQgetvalue(res, row, ATTSTATS_ATTNAME);
+
+ /*
+ * Scan the remote attribute map for matching names. The first one
+ * should be a match but there may also be others. For each match,
+ * assign the result set row number to that entry.
+ *
+ * Remember the type of comparison (< or >) that caused us to break
+ * out of the loop.
+ */
+ for (; mapidx < natts; mapidx++)
+ {
+ cmp = strcmp(remote_attname, remattrmap[mapidx].remote_attname);
+
+ /* Stop scanning on the first non-match */
+ if (cmp != 0)
+ break;
+
+ match_found = true;
+ remattrmap[mapidx].res_index = row;
+ }
+
+ /*
+ * If we found at least one match, move onto the next result.
+ */
+ if (match_found)
+ continue;
+
+ /*
+ * If we didn't find a match, then either the list is out of order,
+ * either the map is out of order or we got a row that we didn't ask
+ * for.
+ */
+ if (cmp > 0)
+ {
+ /* We expected a stats for a column, but found none. */
+ ereport(LOG,
+ errmsg("no remote statistics found for %s of %s.%s",
+ remattrmap[mapidx].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+ else
+ {
+ /*
+ * We got a stat row that we didn't expect. This is a sign that
+ * the query was flawed, which is concerning but not a reason to
+ * block fallback to regular sampling.
+ */
+ ereport(WARNING,
+ errmsg("extra remote statistics found for %s of %s.%s",
+ remote_attname, remote_schemaname, remote_relname));
+ return false;
+ }
+ }
+
+ if (mapidx < natts)
+ {
+ /* We exhausted the result set before mapping all attributes. */
+ ereport(LOG,
+ errmsg("no remote statistics found for %s of %s.%s",
+ remattrmap[mapidx].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ return true;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static bool
+fetch_remote_statistics(PGconn *conn,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int server_version_num, int natts,
+ RemoteAttributeMapping * remattrmap,
+ const char *column_list,
+ RemoteStatsResults * remstats)
+{
+ PGresult *attstats = NULL;
+ PGresult *relstats = NULL;
+
+ char relkind;
+ char *reltuples;
+
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
+ * can't support a foreign table.
+ */
+ relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
+
+ switch (relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ ereport(WARNING,
+ errmsg("remote table %s.%s is of relkind %c which cannot have statistics",
+ remote_schemaname, remote_relname, relkind),
+ errhint("Falling back to ANALYZE with regular row sampling."));
+ goto cleanup;
+ }
+
+ /*
+ * If the reltuples value > 0, then then we can expect to find attribute
+ * stats for the table.
+ *
+ * A reltuples value of -1 means the table has never been analyzed (v14+).
+ *
+ * In versions prior to v14, a value of 0 was ambiguous, it could mean
+ * that the table had never been analyzed, or that it was empty at the
+ * time that it was analyzed. Either way, we wouldn't expect to find
+ * attstats for the relation.
+ */
+ reltuples = PQgetvalue(relstats, 0, RELSTATS_RELTUPLES);
+ if ((strcmp(reltuples, "0") == 0) ||
+ (strcmp(reltuples, "-1") == 0))
+ goto notfound;
+
+ /* See if it actually has any attribute stats. */
+ attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
+ remote_relname, column_list);
+
+ if (PQntuples(attstats) == 0)
+ goto notfound;
+
+ /* Reject the stats if any are missing or in excess. */
+ if (!match_attrmap(attstats, remote_schemaname, remote_relname, natts,
+ remattrmap))
+ goto cleanup;
+
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+
+notfound:
+ ereport(NOTICE,
+ errmsg("remote table %s.%s has no statistics to import",
+ remote_schemaname, remote_relname),
+ errhint("Falling back to ANALYZE with regular row sampling."));
+cleanup:
+ PQclear(attstats);
+ PQclear(relstats);
+ return false;
+}
+
+/*
+ * Test if the relation has extended statistics objects.
+ */
+static bool
+table_has_extended_stats(Relation relation)
+{
+ Relation pg_statext;
+ SysScanDesc scan;
+ ScanKeyData skey;
+ bool found;
+
+ pg_statext = table_open(StatisticExtRelationId, RowExclusiveLock);
+
+ /*
+ * Prepare to scan pg_statistic_ext for entries having stxrelid = this
+ * rel.
+ */
+ ScanKeyInit(&skey,
+ Anum_pg_statistic_ext_stxrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(relation)));
+
+ scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
+ NULL, 1, &skey);
+
+ found = (systable_getnext(scan) != NULL);
+
+ systable_endscan(scan);
+
+ table_close(pg_statext, RowExclusiveLock);
+
+ return found;
+}
+
+static bool
+postgresStatisticsAreImportable(Relation relation)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ ListCell *lc;
+ bool fetch_stats = true;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ /*
+ * Additional checks that can disqualify a table from importing stats.
+ */
+ if (fetch_stats)
+ {
+ /*
+ * We can't compute extended stats from the column stats, for that we
+ * need a table sample.
+ */
+ if (table_has_extended_stats(relation))
+ {
+ ereport(WARNING,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("cannot import statistics for foreign table \"%s\" "
+ "because it has extended statistics objects.",
+ RelationGetRelationName(relation)));
+ fetch_stats = false;
+ }
+ }
+
+ return fetch_stats;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Fetch attstattarget from a pg_attribute tuple.
+ */
+static int16
+get_attstattarget(Relation relation, AttrNumber attnum)
+{
+ HeapTuple atttuple;
+ bool isnull;
+ Datum dat;
+ int16 attstattarget;
+ Oid relid = RelationGetRelid(relation);
+
+ atttuple = SearchSysCache2(ATTNUM,
+ ObjectIdGetDatum(relid),
+ Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, relid);
+ dat = SysCacheGetAttr(ATTNUM, atttuple,
+ Anum_pg_attribute_attstattarget,
+ &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ return attstattarget;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static bool
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+
+ ForeignTable *table;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int natts = 0;
+ bool ok = false;
+
+ RemoteAttributeMapping *remattrmap;
+ StringInfoData column_list;
+
+ RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ }
+
+ /*
+ * Assume the relation/schema names are the same as the local name unless
+ * the options tell us otherwise.
+ */
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ /*
+ * Build attnum/remote-attname map and column list.
+ */
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ initStringInfo(&column_list);
+ appendStringInfoChar(&column_list, '{');
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *attname;
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+
+ /* Ignore dropped columns. */
+ if (attr->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (attr->attgenerated)
+ continue;
+
+ attname = NameStr(attr->attname);
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ attnum = attr->attnum;
+
+ /* Ignore if attstatarget is 0 */
+ if (get_attstattarget(relation, attnum) == 0)
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_colname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ if (i > 0)
+ appendStringInfoChar(&column_list, ',');
+ appendStringInfoString(&column_list, quote_identifier(remote_colname));
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].remote_attname, remote_colname, NAMEDATALEN);
+ remattrmap[natts].res_index = -1;
+ natts++;
+ }
+ appendStringInfoChar(&column_list, '}');
+
+ /* Sort mapping by remote attribute name */
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
+ server_version_num, natts, remattrmap,
+ column_list.data, &remstats);
+
+ ReleaseConnection(conn);
+ pfree(column_list.data);
+
+ if (ok)
+ {
+ Assert(remstats.rel != NULL);
+ Assert(PQnfields(remstats.rel) == RELSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.rel) == 1);
+ Assert(remstats.att != NULL);
+ Assert(PQnfields(remstats.att) == ATTSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.att) >= 1);
+ ok = import_fetched_statistics(schemaname, relname, server_version_num,
+ natts, remattrmap, &remstats);
+ }
+
+ pfree(remattrmap);
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+ return ok;
+}
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 49ed797e8ef..a0f52e57dbc 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1293,7 +1294,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3917,6 +3919,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3954,6 +3961,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
--
2.53.0
v15-0003-Add-remote_analyze-to-postgres_fdw-remote-statis.patch (text/x-patch, 13.4K) download
From 6c441ef265ab8df576303f3117daf43c97c2678b Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:33:53 -0500
Subject: [PATCH v15 3/3] Add remote_analyze to postgres_fdw remote statistics
fetching.
This is accomplished through a new option, remote_analyze, which is
available at the server level and table level. The default value is
false.
If remote_analyze is enabled, and if the first attempt to fetch remote
statistics did not fetch attribute statistics for every local table
column, then an attempt will be made to ANALYZE the remote table. If
that remote ANALYZE succeeds, then a second and final attempt will be
made to fetch remote statistics. If the statistics found are still
insufficient, then the local ANALYZE command will fall back to regular
row sampling and computing the statistics locally.
---
doc/src/sgml/postgres-fdw.sgml | 16 ++
.../postgres_fdw/expected/postgres_fdw.out | 38 +++++
contrib/postgres_fdw/option.c | 5 +
contrib/postgres_fdw/postgres_fdw.c | 154 ++++++++++++++----
contrib/postgres_fdw/sql/postgres_fdw.sql | 34 ++++
5 files changed, 218 insertions(+), 29 deletions(-)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index d7c0dc8ed14..4c7559dad6f 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -387,6 +387,22 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ has no meaning if the foreign table has <literal>fetch_stats</literal>
+ disabled.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index a76f1278538..f7a578d267d 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -12699,6 +12699,44 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 5b7726800d0..2941ecbfb87 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -121,6 +121,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -283,6 +284,10 @@ InitPgFdwOptions(void)
{"fetch_stats", ForeignServerRelationId, false},
{"fetch_stats", ForeignTableRelationId, false},
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index c76ca2fc69b..8c04cb60007 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -5319,6 +5319,36 @@ import_cleanup:
return ok;
}
+/*
+ * Analyze a remote table.
+ */
+static bool
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+ bool ok = true;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s",
+ quote_qualified_identifier(remote_schemaname, remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL ||
+ PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ pgfdw_report(WARNING, res, conn, buf.data);
+ ok = false;
+ }
+
+ PQclear(res);
+ pfree(buf.data);
+ return ok;
+}
+
/*
* Attempt to fetch remote relations stats.
*/
@@ -5482,6 +5512,33 @@ match_attrmap(PGresult *res, const char *remote_schemaname,
return true;
}
+/*
+ * Convenience routine to test if the relstats result set shows that the
+ * relation has tuples.
+ */
+static
+bool
+has_tuples(PGresult *relstats)
+{
+ char *reltuples;
+
+ reltuples = PQgetvalue(relstats, 0, RELSTATS_RELTUPLES);
+
+ /*
+ * If the reltuples value > 0, then then we can expect to find attribute
+ * stats for the table.
+ *
+ * A reltuples value of -1 means the table has never been analyzed (v14+).
+ *
+ * In versions prior to v14, a value of 0 was ambiguous, it could mean
+ * that the table had never been analyzed, or that it was empty at the
+ * time that it was analyzed. Either way, we wouldn't expect to find
+ * attstats for the relation.
+ */
+ return ((strcmp(reltuples, "0") != 0) &&
+ (strcmp(reltuples, "-1") != 0));
+}
+
/*
* Attempt to fetch statistics from a remote server.
*/
@@ -5492,13 +5549,13 @@ fetch_remote_statistics(PGconn *conn,
int server_version_num, int natts,
RemoteAttributeMapping * remattrmap,
const char *column_list,
- RemoteStatsResults * remstats)
+ bool remote_analyze, RemoteStatsResults * remstats)
{
PGresult *attstats = NULL;
PGresult *relstats = NULL;
char relkind;
- char *reltuples;
+ bool has_stats = false;
relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
@@ -5527,34 +5584,55 @@ fetch_remote_statistics(PGconn *conn,
goto cleanup;
}
+ if (has_tuples(relstats))
+ {
+ /* See if the table actually has attribute stats. */
+ attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
+ remote_relname, column_list);
+
+ if ((PQntuples(attstats) > 0) &&
+ match_attrmap(attstats, remote_schemaname, remote_relname,
+ natts, remattrmap))
+ has_stats = true;
+ }
+
+ if (!has_stats)
+ {
+ /* If no second chance, skip to reporting no stats found */
+ if (!remote_analyze)
+ goto notfound;
+
+ ereport(LOG,
+ errmsg("attempting remote analyze of table %s.%s",
+ remote_schemaname, remote_relname));
+ PQclear(attstats);
+ PQclear(relstats);
+
+ /* reset result set indexes in the attr map */
+ for (int i = 0; i < natts; i++)
+ remattrmap[i].res_index = -1;
+
+ if (!analyze_remote_table(conn, remote_schemaname, remote_relname))
+ goto cleanup;
+
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+ if (!has_tuples(relstats))
+ goto notfound;
+
+ attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
+ remote_relname, column_list);
+
+ if (PQntuples(attstats) == 0)
+ goto notfound;
+
+ if (!match_attrmap(attstats, remote_schemaname, remote_relname,
+ natts, remattrmap))
+ goto cleanup;
+ }
+
/*
- * If the reltuples value > 0, then then we can expect to find attribute
- * stats for the table.
- *
- * A reltuples value of -1 means the table has never been analyzed (v14+).
- *
- * In versions prior to v14, a value of 0 was ambiguous, it could mean
- * that the table had never been analyzed, or that it was empty at the
- * time that it was analyzed. Either way, we wouldn't expect to find
- * attstats for the relation.
+ * We found stats, on either the first try or the second.
*/
- reltuples = PQgetvalue(relstats, 0, RELSTATS_RELTUPLES);
- if ((strcmp(reltuples, "0") == 0) ||
- (strcmp(reltuples, "-1") == 0))
- goto notfound;
-
- /* See if it actually has any attribute stats. */
- attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
- remote_relname, column_list);
-
- if (PQntuples(attstats) == 0)
- goto notfound;
-
- /* Reject the stats if any are missing or in excess. */
- if (!match_attrmap(attstats, remote_schemaname, remote_relname, natts,
- remattrmap))
- goto cleanup;
-
remstats->rel = relstats;
remstats->att = attstats;
return true;
@@ -5712,9 +5790,11 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
{
ForeignTable *table;
+ ForeignServer *server;
UserMapping *user;
PGconn *conn;
ListCell *lc;
+ bool remote_analyze = false;
int server_version_num = 0;
const char *schemaname = NULL;
const char *relname = NULL;
@@ -5730,12 +5810,25 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
user = GetUserMapping(GetUserId(), table->serverid);
conn = GetConnection(user, false, NULL);
server_version_num = PQserverVersion(conn);
schemaname = get_namespace_name(RelationGetNamespace(relation));
relname = RelationGetRelationName(relation);
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
foreach(lc, table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
@@ -5744,6 +5837,8 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
remote_schemaname = defGetString(def);
else if (strcmp(def->defname, "table_name") == 0)
remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
}
/*
@@ -5822,7 +5917,8 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
server_version_num, natts, remattrmap,
- column_list.data, &remstats);
+ column_list.data, remote_analyze,
+ &remstats);
ReleaseConnection(conn);
pfree(column_list.data);
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index a0f52e57dbc..3390f6e5ec1 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -4412,6 +4412,40 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
--
2.53.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-18 01:56 Corey Huinker <corey.huinker@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-03-18 01:56 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Sat, Mar 14, 2026 at 4:05 PM Corey Huinker <corey.huinker@gmail.com>
wrote:
>
>> I've also moved the column matching - finding which rows of the attstats
>> result set match to which columns in the local table - up into the fetch
>> portion, something you had mentioned wanting to see as well. This resulted
>> in some significant refactoring, but overall I think you will find the
>> changes for the better.
>>
>
> I've added a reset of the result set indexes. Probably not necessary given
> that we only keep the result set if all the columns found homes, but good
> for peace of mind.
>
And rebased to make the CI happy.
Attachments: download all (3 files, .tar.gz)
v16-0001-Add-FDW-functions-for-importing-optimizer-statis.patch (text/x-patch, 5.0K) download
From 3aff9ca0887944fac79f484c82c1354634d43a70 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 16:39:45 -0500
Subject: [PATCH v16 1/3] Add FDW functions for importing optimizer statistics.
Add the the function StatisticsAreImportable which is used as a
lightweight preliminary scan to determine if the remote table could
potentially have statistics that could be imported instead of fetching a
row sample from the remote table, which can be expensive.
Also add the function ImportStatistics which attempts to actually fetch
those statistics from the remote server, and if successful import them
into the local statistics catalog.
---
src/include/foreign/fdwapi.h | 8 ++++
src/backend/commands/analyze.c | 68 ++++++++++++++++++++++++----------
2 files changed, 56 insertions(+), 20 deletions(-)
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..59beeae4f45 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,12 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*StatisticsAreImportable_function) (Relation relation);
+
+typedef bool (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +261,8 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ StatisticsAreImportable_function StatisticsAreImportable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index eeed91be266..a11067ed31e 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -114,6 +114,9 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ FdwRoutine *fdwroutine = NULL;
+ bool can_import_stats = false;
+ bool stats_imported = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -196,27 +199,16 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
- FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
- {
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
- }
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->StatisticsAreImportable != NULL &&
+ fdwroutine->StatisticsAreImportable(onerel))
+ can_import_stats = true;
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
{
@@ -248,10 +240,46 @@ analyze_rel(Oid relid, RangeVar *relation,
PROGRESS_ANALYZE_STARTED_BY_MANUAL);
/*
- * Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * If this table can import statistics, attempt to do so.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if (can_import_stats)
+ {
+ Assert(onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE);
+ Assert(fdwroutine != NULL);
+ Assert(fdwroutine->ImportStatistics != NULL);
+ stats_imported = fdwroutine->ImportStatistics(onerel, va_cols, elevel);
+ }
+
+ /*
+ * Foreign tables that were not able to import stats will resort to
+ * regular sampling.
+ */
+ if ((onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
+ && !stats_imported)
+ {
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ return;
+ }
+ }
+
+ /*
+ * Do the normal non-recursive ANALYZE. We can skip this for partitioned
+ * tables and foreign tables that successfully imported statistics.
+ */
+ if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ && !stats_imported)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
base-commit: 3b4c2b9db25ee1c51e5133da529668a37aa02fc3
--
2.53.0
v16-0002-Add-remote-statistics-fetching-to-postgres_fdw.patch (text/x-patch, 37.4K) download
From 19c3413f37b6e4017ede08dbeeedb274b2eb9060 Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:06:05 -0500
Subject: [PATCH v16 2/3] Add remote statistics fetching to postgres_fdw.
This adds the ability to fetch and import statistics from a remote
server table table rather than fetching the data or data sample from
that table.
This is managed via a new option, fetch_stats, which is available at the
server level and table level. The global default is true, but this can
be overriden by at the server level, which in turn can be overridden at
the table level.
If fetch_stats is true, and the remote table is an actual table or
materialized view that can hold statistics, and the local table does not
have any extended statistics objects built upon it, then the remote
database will first be queried for relation statistics and attribute
statistics similar to the method used in pg_dump.
If there are remote statistics for all of the columns in the local
table, then those statistics will be imported using
pg_restore_relation_statistics and pg_restore_attribute_statistics
functions similar to the way pg_restore uses them.
If fetch_stats is false, or if the fetched statistics were missing or
otherwise inadequate, then the ANALYZE operation will issue a WARNING
and then fall back to regular table sampling to generate local
statistics.
---
src/backend/commands/analyze.c | 3 +-
doc/src/sgml/postgres-fdw.sgml | 25 +-
.../postgres_fdw/expected/postgres_fdw.out | 17 +-
contrib/postgres_fdw/option.c | 5 +
contrib/postgres_fdw/postgres_fdw.c | 910 ++++++++++++++++++
contrib/postgres_fdw/sql/postgres_fdw.sql | 13 +-
6 files changed, 969 insertions(+), 4 deletions(-)
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index a11067ed31e..254908495ee 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -240,7 +240,8 @@ analyze_rel(Oid relid, RangeVar *relation,
PROGRESS_ANALYZE_STARTED_BY_MANUAL);
/*
- * If this table can import statistics, attempt to do so.
+ * If this table can import statistics, attempt to do so. If statistics
+ * import fails, then we will fall back to table sampling.
*/
if (can_import_stats)
{
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index de69ddcdebc..d7c0dc8ed14 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,29 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</function> and
+ <function>pg_restore_attribute_stats</function>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views). If the foreign table is a partition
+ of a partitioned table, analyzing the partitioned table will still
+ result in row sampling on the foreign table regardless of this setting,
+ though direct analysis of the foreign table would have attempted to
+ fetch remote statistics first.
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 0f5271d476e..a76f1278538 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4559,7 +4560,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11481,6 +11483,13 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+NOTICE: remote table public.base_tbl2 has no statistics to import
+HINT: Falling back to ANALYZE with regular row sampling.
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11587,6 +11596,12 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+NOTICE: remote table public.base_tbl3 has no statistics to import
+HINT: Falling back to ANALYZE with regular row sampling.
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..5b7726800d0 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +279,10 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 41e47cc795b..b1354bcf6a1 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -18,11 +18,14 @@
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_opfamily.h"
+#include "catalog/pg_statistic_ext.h"
#include "commands/defrem.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
#include "executor/execAsync.h"
#include "executor/instrument.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -43,12 +46,14 @@
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
+#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
+#include "utils/syscache.h"
PG_MODULE_MAGIC_EXT(
.name = "postgres_fdw",
@@ -318,6 +323,21 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ char remote_attname[NAMEDATALEN];
+ AttrNumber local_attnum;
+ int res_index;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -403,6 +423,10 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresStatisticsAreImportable(Relation relation);
+static bool postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -547,6 +571,188 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns
+{
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_NUM_FIELDS,
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+static const char *attstats_query_default =
+"SELECT s.attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\"";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns
+{
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS,
+};
+
+static const char *relimport_sql =
+"SELECT pg_catalog.pg_restore_relation_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'relpages', $4::integer,\n"
+"\t'reltuples', $5::real)";
+
+enum RelImportSqlArgs
+{
+ RELIMPORT_SQL_VERSION = 0,
+ RELIMPORT_SQL_SCHEMANAME,
+ RELIMPORT_SQL_RELNAME,
+ RELIMPORT_SQL_RELPAGES,
+ RELIMPORT_SQL_RELTUPLES,
+ RELIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid relimport_argtypes[RELIMPORT_SQL_NUM_FIELDS] = {
+INT4OID, TEXTOID, TEXTOID, TEXTOID, TEXTOID,};
+
+static const char *attimport_sql =
+"SELECT pg_catalog.pg_restore_attribute_stats(\n"
+"\t'version', $1,\n"
+"\t'schemaname', $2,\n"
+"\t'relname', $3,\n"
+"\t'attnum', $4,\n"
+"\t'inherited', false::boolean,\n"
+"\t'null_frac', $5::real,\n"
+"\t'avg_width', $6::integer,\n"
+"\t'n_distinct', $7::real,\n"
+"\t'most_common_vals', $8,\n"
+"\t'most_common_freqs', $9::real[],\n"
+"\t'histogram_bounds', $10,\n"
+"\t'correlation', $11::real,\n"
+"\t'most_common_elems', $12,\n"
+"\t'most_common_elem_freqs', $13::real[],\n"
+"\t'elem_count_histogram', $14::real[],\n"
+"\t'range_length_histogram', $15,\n"
+"\t'range_empty_frac', $16::real,\n"
+"\t'range_bounds_histogram', $17)";
+
+enum AttImportSqlArgs
+{
+ ATTIMPORT_SQL_VERSION = 0,
+ ATTIMPORT_SQL_SCHEMANAME,
+ ATTIMPORT_SQL_RELNAME,
+ ATTIMPORT_SQL_ATTNUM,
+ ATTIMPORT_SQL_NULL_FRAC,
+ ATTIMPORT_SQL_AVG_WIDTH,
+ ATTIMPORT_SQL_N_DISTINCT,
+ ATTIMPORT_SQL_MOST_COMMON_VALS,
+ ATTIMPORT_SQL_MOST_COMMON_FREQS,
+ ATTIMPORT_SQL_HISTOGRAM_BOUNDS,
+ ATTIMPORT_SQL_CORRELATION,
+ ATTIMPORT_SQL_MOST_COMMON_ELEMS,
+ ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS,
+ ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_EMPTY_FRAC,
+ ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM,
+ ATTIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid attimport_argtypes[ATTIMPORT_SQL_NUM_FIELDS] = {
+ INT4OID, TEXTOID, TEXTOID, INT2OID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+TEXTOID,};
+
+/* Pairs AttStatsColumns:AttImportSqlArgs Map */
+typedef struct
+{
+ enum AttStatsColumns res_field;
+ enum AttImportSqlArgs arg_num;
+} AttrResultArgMap;
+
+/*
+ * The mapping of attribute stats query columns to the positional arguments in
+ * the prepared pg_restore_attribute_stats() statement.
+ */
+#define NUM_MAPPED_ATTIMPORT_ARGS 13
+static const AttrResultArgMap attr_result_arg_map[NUM_MAPPED_ATTIMPORT_ARGS] = {
+ {ATTSTATS_NULL_FRAC, ATTIMPORT_SQL_NULL_FRAC},
+ {ATTSTATS_AVG_WIDTH, ATTIMPORT_SQL_AVG_WIDTH},
+ {ATTSTATS_N_DISTINCT, ATTIMPORT_SQL_N_DISTINCT},
+ {ATTSTATS_MOST_COMMON_VALS, ATTIMPORT_SQL_MOST_COMMON_VALS},
+ {ATTSTATS_MOST_COMMON_FREQS, ATTIMPORT_SQL_MOST_COMMON_FREQS},
+ {ATTSTATS_HISTOGRAM_BOUNDS, ATTIMPORT_SQL_HISTOGRAM_BOUNDS},
+ {ATTSTATS_CORRELATION, ATTIMPORT_SQL_CORRELATION},
+ {ATTSTATS_MOST_COMMON_ELEMS, ATTIMPORT_SQL_MOST_COMMON_ELEMS},
+ {ATTSTATS_MOST_COMMON_ELEM_FREQS, ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS},
+ {ATTSTATS_ELEM_COUNT_HISTOGRAM, ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM},
+ {ATTSTATS_RANGE_LENGTH_HISTOGRAM, ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM},
+ {ATTSTATS_RANGE_EMPTY_FRAC, ATTIMPORT_SQL_RANGE_EMPTY_FRAC},
+ {ATTSTATS_RANGE_BOUNDS_HISTOGRAM, ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM},
+};
+
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -596,6 +802,8 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->StatisticsAreImportable = postgresStatisticsAreImportable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4936,6 +5144,708 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Move a string value from a result set to a Text value of a Datum array.
+ */
+static void
+map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls)
+{
+ if (PQgetisnull(res, row, field))
+ {
+ values[arg] = (Datum) 0;
+ nulls[arg] = 'n';
+ }
+ else
+ {
+ const char *s = PQgetvalue(res, row, field);
+
+ values[arg] = CStringGetTextDatum(s);
+ nulls[arg] = ' ';
+ }
+}
+
+/*
+ * Check the 1x1 result set of a pg_restore_*_stats() command for success.
+ */
+static bool
+import_spi_query_ok(int spirc)
+{
+ char *s;
+ bool ok;
+
+ if (spirc != SPI_OK_SELECT
+ || SPI_tuptable == NULL
+ || SPI_processed != 1)
+ return false;
+
+ s = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
+
+ ok = (s != NULL && s[0] == 't' && s[1] == '\0');
+ pfree(s);
+
+ return ok;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static bool
+import_fetched_statistics(const char *schemaname, const char *relname,
+ int server_version_num, int natts,
+ const RemoteAttributeMapping * remattrmap,
+ RemoteStatsResults * remstats)
+{
+ SPIPlanPtr plan = NULL;
+ PGresult *res = remstats->att;
+ int spirc;
+ Datum values[ATTIMPORT_SQL_NUM_FIELDS];
+ char nulls[ATTIMPORT_SQL_NUM_FIELDS];
+ bool ok = false;
+
+ /* Assign all the invariant parameters */
+ values[ATTIMPORT_SQL_VERSION] = Int32GetDatum(server_version_num);
+ nulls[ATTIMPORT_SQL_VERSION] = ' ';
+
+ values[ATTIMPORT_SQL_SCHEMANAME] = CStringGetTextDatum(schemaname);
+ nulls[ATTIMPORT_SQL_SCHEMANAME] = ' ';
+
+ values[ATTIMPORT_SQL_RELNAME] = CStringGetTextDatum(relname);
+ nulls[ATTIMPORT_SQL_RELNAME] = ' ';
+
+ nulls[ATTIMPORT_SQL_ATTNUM] = ' ';
+
+ SPI_connect();
+
+ plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+
+ if (plan == NULL || SPI_result < 0)
+ {
+ ereport(WARNING,
+ errmsg("import attribute statistics prepare failed %s "
+ "with error code %d",
+ attimport_sql, SPI_result));
+ goto import_cleanup;
+ }
+
+ /*
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ for (int mapidx = 0; mapidx < natts; mapidx++)
+ {
+ int row = remattrmap[mapidx].res_index;
+
+ /* All mappings should have been assigned a result set row. */
+ Assert(row >= 0);
+
+ values[ATTIMPORT_SQL_ATTNUM] =
+ Int16GetDatum(remattrmap[mapidx].local_attnum);
+
+ /* Loop through all mappable columns->arguments */
+ for (int i = 0; i < NUM_MAPPED_ATTIMPORT_ARGS; i++)
+ map_field_to_arg(res, row,
+ attr_result_arg_map[i].res_field,
+ attr_result_arg_map[i].arg_num,
+ values, nulls);
+
+ spirc = SPI_execute_plan(plan, values, nulls, false, 0);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("attribute statistics import failed %s",
+ attimport_sql));
+ goto import_cleanup;
+ }
+ }
+
+ /*
+ * Import relstats.
+ *
+ * Import relation stats. We only perform this once, so there is no point
+ * in preparing the statement.
+ *
+ * We can re-use the values/nulls because the number of parameters is less
+ * and the first three params are the same as attstats_import.
+ */
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELPAGES,
+ RELIMPORT_SQL_RELPAGES, values, nulls);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELTUPLES,
+ RELIMPORT_SQL_RELTUPLES, values, nulls);
+
+ spirc = SPI_execute_with_args(relimport_sql, RELIMPORT_SQL_NUM_FIELDS,
+ (Oid *) relimport_argtypes,
+ values, nulls, false, 1);
+
+ if (!import_spi_query_ok(spirc))
+ {
+ ereport(WARNING,
+ errmsg("relation statistics import failed %s",
+ relimport_sql));
+ goto import_cleanup;
+ }
+
+ ok = true;
+
+import_cleanup:
+ if (plan)
+ SPI_freeplan(plan);
+ SPI_finish();
+ return ok;
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname)
+{
+ const char *params[2] = {remote_schemaname, remote_relname};
+
+ const char *sql = "SELECT c.relkind, c.relpages, c.reltuples "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n "
+ "ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+
+ PGresult *res = NULL;
+
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(NULL, conn, sql);
+
+ if (PQntuples(res) != 1 ||
+ PQnfields(res) != RELSTATS_NUM_FIELDS ||
+ PQgetisnull(res, 0, RELSTATS_RELKIND))
+ elog(ERROR, "unexpected result from fetch_relstats query");
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list)
+{
+ const char *params[3] = {remote_schemaname, remote_relname, column_list};
+ const char *sql;
+ PGresult *res;
+
+ if (server_version_num >= 170000)
+ sql = attstats_query_17;
+ else if (server_version_num >= 90200)
+ sql = attstats_query_9_2;
+ else if (server_version_num >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(NULL, conn, sql);
+
+ if (PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ return res;
+}
+
+/*
+ * Match result set rows to local attnums.
+ *
+ * Every row of the result should be an attribute that we specifically
+ * filtered for, so every row should have at least one match in the
+ * RemoteAttributeMapping, which is also ordered by attname, so we only
+ * need to walk that array once.
+ */
+static
+bool
+match_attrmap(PGresult *res, const char *remote_schemaname,
+ const char *remote_relname, int natts,
+ RemoteAttributeMapping * remattrmap)
+{
+ int mapidx = 0;
+
+ for (int row = 0; row < PQntuples(res); row++)
+ {
+ char *remote_attname;
+ bool match_found = false;
+ int cmp = 0;
+
+ if (PQgetisnull(res, row, ATTSTATS_ATTNAME))
+ elog(ERROR,
+ "remote statistics returned a row with NULL attribute name");
+
+ remote_attname = PQgetvalue(res, row, ATTSTATS_ATTNAME);
+
+ /*
+ * Scan the remote attribute map for matching names. The first one
+ * should be a match but there may also be others. For each match,
+ * assign the result set row number to that entry.
+ *
+ * Remember the type of comparison (< or >) that caused us to break
+ * out of the loop.
+ */
+ for (; mapidx < natts; mapidx++)
+ {
+ cmp = strcmp(remote_attname, remattrmap[mapidx].remote_attname);
+
+ /* Stop scanning on the first non-match */
+ if (cmp != 0)
+ break;
+
+ match_found = true;
+ remattrmap[mapidx].res_index = row;
+ }
+
+ /*
+ * If we found at least one match, move onto the next result.
+ */
+ if (match_found)
+ continue;
+
+ /*
+ * If we didn't find a match, then either the list is out of order,
+ * either the map is out of order or we got a row that we didn't ask
+ * for.
+ */
+ if (cmp > 0)
+ {
+ /* We expected a stats for a column, but found none. */
+ ereport(LOG,
+ errmsg("no remote statistics found for %s of %s.%s",
+ remattrmap[mapidx].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+ else
+ {
+ /*
+ * We got a stat row that we didn't expect. This is a sign that
+ * the query was flawed, which is concerning but not a reason to
+ * block fallback to regular sampling.
+ */
+ ereport(WARNING,
+ errmsg("extra remote statistics found for %s of %s.%s",
+ remote_attname, remote_schemaname, remote_relname));
+ return false;
+ }
+ }
+
+ if (mapidx < natts)
+ {
+ /* We exhausted the result set before mapping all attributes. */
+ ereport(LOG,
+ errmsg("no remote statistics found for %s of %s.%s",
+ remattrmap[mapidx].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ return true;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static bool
+fetch_remote_statistics(PGconn *conn,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int server_version_num, int natts,
+ RemoteAttributeMapping * remattrmap,
+ const char *column_list,
+ RemoteStatsResults * remstats)
+{
+ PGresult *attstats = NULL;
+ PGresult *relstats = NULL;
+
+ char relkind;
+ char *reltuples;
+
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
+ * can't support a foreign table.
+ */
+ relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
+
+ switch (relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_PARTITIONED_TABLE:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ break;
+ default:
+ ereport(WARNING,
+ errmsg("remote table %s.%s is of relkind %c which cannot have statistics",
+ remote_schemaname, remote_relname, relkind),
+ errhint("Falling back to ANALYZE with regular row sampling."));
+ goto cleanup;
+ }
+
+ /*
+ * If the reltuples value > 0, then then we can expect to find attribute
+ * stats for the table.
+ *
+ * A reltuples value of -1 means the table has never been analyzed (v14+).
+ *
+ * In versions prior to v14, a value of 0 was ambiguous, it could mean
+ * that the table had never been analyzed, or that it was empty at the
+ * time that it was analyzed. Either way, we wouldn't expect to find
+ * attstats for the relation.
+ */
+ reltuples = PQgetvalue(relstats, 0, RELSTATS_RELTUPLES);
+ if ((strcmp(reltuples, "0") == 0) ||
+ (strcmp(reltuples, "-1") == 0))
+ goto notfound;
+
+ /* See if it actually has any attribute stats. */
+ attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
+ remote_relname, column_list);
+
+ if (PQntuples(attstats) == 0)
+ goto notfound;
+
+ /* Reject the stats if any are missing or in excess. */
+ if (!match_attrmap(attstats, remote_schemaname, remote_relname, natts,
+ remattrmap))
+ goto cleanup;
+
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+
+notfound:
+ ereport(NOTICE,
+ errmsg("remote table %s.%s has no statistics to import",
+ remote_schemaname, remote_relname),
+ errhint("Falling back to ANALYZE with regular row sampling."));
+cleanup:
+ PQclear(attstats);
+ PQclear(relstats);
+ return false;
+}
+
+/*
+ * Test if the relation has extended statistics objects.
+ */
+static bool
+table_has_extended_stats(Relation relation)
+{
+ Relation pg_statext;
+ SysScanDesc scan;
+ ScanKeyData skey;
+ bool found;
+
+ pg_statext = table_open(StatisticExtRelationId, RowExclusiveLock);
+
+ /*
+ * Prepare to scan pg_statistic_ext for entries having stxrelid = this
+ * rel.
+ */
+ ScanKeyInit(&skey,
+ Anum_pg_statistic_ext_stxrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(relation)));
+
+ scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
+ NULL, 1, &skey);
+
+ found = (systable_getnext(scan) != NULL);
+
+ systable_endscan(scan);
+
+ table_close(pg_statext, RowExclusiveLock);
+
+ return found;
+}
+
+static bool
+postgresStatisticsAreImportable(Relation relation)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ ListCell *lc;
+ bool fetch_stats = true;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+
+ /*
+ * Additional checks that can disqualify a table from importing stats.
+ */
+ if (fetch_stats)
+ {
+ /*
+ * We can't compute extended stats from the column stats, for that we
+ * need a table sample.
+ */
+ if (table_has_extended_stats(relation))
+ {
+ ereport(WARNING,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("cannot import statistics for foreign table \"%s\" "
+ "because it has extended statistics objects.",
+ RelationGetRelationName(relation)));
+ fetch_stats = false;
+ }
+ }
+
+ return fetch_stats;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Fetch attstattarget from a pg_attribute tuple.
+ */
+static int16
+get_attstattarget(Relation relation, AttrNumber attnum)
+{
+ HeapTuple atttuple;
+ bool isnull;
+ Datum dat;
+ int16 attstattarget;
+ Oid relid = RelationGetRelid(relation);
+
+ atttuple = SearchSysCache2(ATTNUM,
+ ObjectIdGetDatum(relid),
+ Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, relid);
+ dat = SysCacheGetAttr(ATTNUM, atttuple,
+ Anum_pg_attribute_attstattarget,
+ &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ return attstattarget;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static bool
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+
+ ForeignTable *table;
+ UserMapping *user;
+ PGconn *conn;
+ ListCell *lc;
+ int server_version_num = 0;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ int natts = 0;
+ bool ok = false;
+
+ RemoteAttributeMapping *remattrmap;
+ StringInfoData column_list;
+
+ RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ }
+
+ /*
+ * Assume the relation/schema names are the same as the local name unless
+ * the options tell us otherwise.
+ */
+ if (remote_schemaname == NULL)
+ remote_schemaname = schemaname;
+ if (remote_relname == NULL)
+ remote_relname = relname;
+
+ /*
+ * Build attnum/remote-attname map and column list.
+ */
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ initStringInfo(&column_list);
+ appendStringInfoChar(&column_list, '{');
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ char *attname;
+ char *remote_colname;
+ List *fc_options;
+ ListCell *fc_lc;
+ AttrNumber attnum;
+
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+
+ /* Ignore dropped columns. */
+ if (attr->attisdropped)
+ continue;
+
+ /* Ignore generated columns. */
+ if (attr->attgenerated)
+ continue;
+
+ attname = NameStr(attr->attname);
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ attnum = attr->attnum;
+
+ /* Ignore if attstatarget is 0 */
+ if (get_attstattarget(relation, attnum) == 0)
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_colname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+
+ foreach(fc_lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(fc_lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_colname = defGetString(def);
+ break;
+ }
+ }
+
+ if (i > 0)
+ appendStringInfoChar(&column_list, ',');
+ appendStringInfoString(&column_list, quote_identifier(remote_colname));
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].remote_attname, remote_colname, NAMEDATALEN);
+ remattrmap[natts].res_index = -1;
+ natts++;
+ }
+ appendStringInfoChar(&column_list, '}');
+
+ /* Sort mapping by remote attribute name */
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
+ server_version_num, natts, remattrmap,
+ column_list.data, &remstats);
+
+ ReleaseConnection(conn);
+ pfree(column_list.data);
+
+ if (ok)
+ {
+ Assert(remstats.rel != NULL);
+ Assert(PQnfields(remstats.rel) == RELSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.rel) == 1);
+ Assert(remstats.att != NULL);
+ Assert(PQnfields(remstats.att) == ATTSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats.att) >= 1);
+ ok = import_fetched_statistics(schemaname, relname, server_version_num,
+ natts, remattrmap, &remstats);
+ }
+
+ pfree(remattrmap);
+ PQclear(remstats.att);
+ PQclear(remstats.rel);
+ return ok;
+}
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 49ed797e8ef..a0f52e57dbc 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1293,7 +1294,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3917,6 +3919,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3954,6 +3961,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
--
2.53.0
v16-0003-Add-remote_analyze-to-postgres_fdw-remote-statis.patch (text/x-patch, 13.4K) download
From 04f88abca3824532f76035796d5ec3a30bd12d5c Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Sat, 17 Jan 2026 19:33:53 -0500
Subject: [PATCH v16 3/3] Add remote_analyze to postgres_fdw remote statistics
fetching.
This is accomplished through a new option, remote_analyze, which is
available at the server level and table level. The default value is
false.
If remote_analyze is enabled, and if the first attempt to fetch remote
statistics did not fetch attribute statistics for every local table
column, then an attempt will be made to ANALYZE the remote table. If
that remote ANALYZE succeeds, then a second and final attempt will be
made to fetch remote statistics. If the statistics found are still
insufficient, then the local ANALYZE command will fall back to regular
row sampling and computing the statistics locally.
---
doc/src/sgml/postgres-fdw.sgml | 16 ++
.../postgres_fdw/expected/postgres_fdw.out | 38 +++++
contrib/postgres_fdw/option.c | 5 +
contrib/postgres_fdw/postgres_fdw.c | 154 ++++++++++++++----
contrib/postgres_fdw/sql/postgres_fdw.sql | 34 ++++
5 files changed, 218 insertions(+), 29 deletions(-)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index d7c0dc8ed14..4c7559dad6f 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -387,6 +387,22 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>remote_analyze</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines whether an <command>ANALYZE</command> on a foreign
+ table will attempt to <command>ANALYZE</command> the remote table if
+ the first attempt to fetch remote statistics fails, and will then
+ make a second and final attempt to fetch remote statistics. This option
+ has no meaning if the foreign table has <literal>fetch_stats</literal>
+ disabled.
+ The default is <literal>false</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index a76f1278538..f7a578d267d 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -12699,6 +12699,44 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------+-----------
+(0 rows)
+
+ANALYZE remote_analyze_ftable;
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+ tablename | num_stats
+-----------------------+-----------
+ remote_analyze_ftable | 3
+ remote_analyze_table | 3
+(2 rows)
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 5b7726800d0..2941ecbfb87 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -121,6 +121,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
strcmp(def->defname, "fetch_stats") == 0 ||
+ strcmp(def->defname, "remote_analyze") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -283,6 +284,10 @@ InitPgFdwOptions(void)
{"fetch_stats", ForeignServerRelationId, false},
{"fetch_stats", ForeignTableRelationId, false},
+ /* remote_analyze is available on both server and table */
+ {"remote_analyze", ForeignServerRelationId, false},
+ {"remote_analyze", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index b1354bcf6a1..446a0d7d75e 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -5320,6 +5320,36 @@ import_cleanup:
return ok;
}
+/*
+ * Analyze a remote table.
+ */
+static bool
+analyze_remote_table(PGconn *conn, const char *remote_schemaname,
+ const char *remote_relname)
+{
+ StringInfoData buf;
+ PGresult *res;
+ bool ok = true;
+
+ initStringInfo(&buf);
+
+ appendStringInfo(&buf, "ANALYZE %s",
+ quote_qualified_identifier(remote_schemaname, remote_relname));
+
+ res = pgfdw_exec_query(conn, buf.data, NULL);
+
+ if (res == NULL ||
+ PQresultStatus(res) != PGRES_COMMAND_OK)
+ {
+ pgfdw_report(WARNING, res, conn, buf.data);
+ ok = false;
+ }
+
+ PQclear(res);
+ pfree(buf.data);
+ return ok;
+}
+
/*
* Attempt to fetch remote relations stats.
*/
@@ -5483,6 +5513,33 @@ match_attrmap(PGresult *res, const char *remote_schemaname,
return true;
}
+/*
+ * Convenience routine to test if the relstats result set shows that the
+ * relation has tuples.
+ */
+static
+bool
+has_tuples(PGresult *relstats)
+{
+ char *reltuples;
+
+ reltuples = PQgetvalue(relstats, 0, RELSTATS_RELTUPLES);
+
+ /*
+ * If the reltuples value > 0, then then we can expect to find attribute
+ * stats for the table.
+ *
+ * A reltuples value of -1 means the table has never been analyzed (v14+).
+ *
+ * In versions prior to v14, a value of 0 was ambiguous, it could mean
+ * that the table had never been analyzed, or that it was empty at the
+ * time that it was analyzed. Either way, we wouldn't expect to find
+ * attstats for the relation.
+ */
+ return ((strcmp(reltuples, "0") != 0) &&
+ (strcmp(reltuples, "-1") != 0));
+}
+
/*
* Attempt to fetch statistics from a remote server.
*/
@@ -5493,13 +5550,13 @@ fetch_remote_statistics(PGconn *conn,
int server_version_num, int natts,
RemoteAttributeMapping * remattrmap,
const char *column_list,
- RemoteStatsResults * remstats)
+ bool remote_analyze, RemoteStatsResults * remstats)
{
PGresult *attstats = NULL;
PGresult *relstats = NULL;
char relkind;
- char *reltuples;
+ bool has_stats = false;
relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
@@ -5528,34 +5585,55 @@ fetch_remote_statistics(PGconn *conn,
goto cleanup;
}
+ if (has_tuples(relstats))
+ {
+ /* See if the table actually has attribute stats. */
+ attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
+ remote_relname, column_list);
+
+ if ((PQntuples(attstats) > 0) &&
+ match_attrmap(attstats, remote_schemaname, remote_relname,
+ natts, remattrmap))
+ has_stats = true;
+ }
+
+ if (!has_stats)
+ {
+ /* If no second chance, skip to reporting no stats found */
+ if (!remote_analyze)
+ goto notfound;
+
+ ereport(LOG,
+ errmsg("attempting remote analyze of table %s.%s",
+ remote_schemaname, remote_relname));
+ PQclear(attstats);
+ PQclear(relstats);
+
+ /* reset result set indexes in the attr map */
+ for (int i = 0; i < natts; i++)
+ remattrmap[i].res_index = -1;
+
+ if (!analyze_remote_table(conn, remote_schemaname, remote_relname))
+ goto cleanup;
+
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+ if (!has_tuples(relstats))
+ goto notfound;
+
+ attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
+ remote_relname, column_list);
+
+ if (PQntuples(attstats) == 0)
+ goto notfound;
+
+ if (!match_attrmap(attstats, remote_schemaname, remote_relname,
+ natts, remattrmap))
+ goto cleanup;
+ }
+
/*
- * If the reltuples value > 0, then then we can expect to find attribute
- * stats for the table.
- *
- * A reltuples value of -1 means the table has never been analyzed (v14+).
- *
- * In versions prior to v14, a value of 0 was ambiguous, it could mean
- * that the table had never been analyzed, or that it was empty at the
- * time that it was analyzed. Either way, we wouldn't expect to find
- * attstats for the relation.
+ * We found stats, on either the first try or the second.
*/
- reltuples = PQgetvalue(relstats, 0, RELSTATS_RELTUPLES);
- if ((strcmp(reltuples, "0") == 0) ||
- (strcmp(reltuples, "-1") == 0))
- goto notfound;
-
- /* See if it actually has any attribute stats. */
- attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
- remote_relname, column_list);
-
- if (PQntuples(attstats) == 0)
- goto notfound;
-
- /* Reject the stats if any are missing or in excess. */
- if (!match_attrmap(attstats, remote_schemaname, remote_relname, natts,
- remattrmap))
- goto cleanup;
-
remstats->rel = relstats;
remstats->att = attstats;
return true;
@@ -5713,9 +5791,11 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
{
ForeignTable *table;
+ ForeignServer *server;
UserMapping *user;
PGconn *conn;
ListCell *lc;
+ bool remote_analyze = false;
int server_version_num = 0;
const char *schemaname = NULL;
const char *relname = NULL;
@@ -5731,12 +5811,25 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
RemoteStatsResults remstats = {.rel = NULL,.att = NULL};
table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
user = GetUserMapping(GetUserId(), table->serverid);
conn = GetConnection(user, false, NULL);
server_version_num = PQserverVersion(conn);
schemaname = get_namespace_name(RelationGetNamespace(relation));
relname = RelationGetRelationName(relation);
+ /*
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
+ }
+
foreach(lc, table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
@@ -5745,6 +5838,8 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
remote_schemaname = defGetString(def);
else if (strcmp(def->defname, "table_name") == 0)
remote_relname = defGetString(def);
+ else if (strcmp(def->defname, "remote_analyze") == 0)
+ remote_analyze = defGetBoolean(def);
}
/*
@@ -5823,7 +5918,8 @@ postgresImportStatistics(Relation relation, List *va_cols, int elevel)
ok = fetch_remote_statistics(conn, remote_schemaname, remote_relname,
server_version_num, natts, remattrmap,
- column_list.data, &remstats);
+ column_list.data, remote_analyze,
+ &remstats);
ReleaseConnection(conn);
pfree(column_list.data);
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index a0f52e57dbc..3390f6e5ec1 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -4412,6 +4412,40 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test remote analyze
+-- ===================================================================
+CREATE TABLE remote_analyze_table (id int, a text, b bigint);
+INSERT INTO remote_analyze_table (SELECT x FROM generate_series(1,1000) x);
+
+CREATE FOREIGN TABLE remote_analyze_ftable (id int, a text, b bigint)
+ SERVER loopback
+ OPTIONS (table_name 'remote_analyze_table',
+ fetch_stats 'true',
+ remote_analyze 'true');
+
+-- no stats before
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+ANALYZE remote_analyze_ftable;
+
+-- both stats after
+SELECT s.tablename, COUNT(*) AS num_stats
+FROM pg_stats AS s
+WHERE s.schemaname = 'public'
+AND s.tablename IN ('remote_analyze_table', 'remote_analyze_ftable')
+GROUP BY s.tablename
+ORDER BY s.tablename;
+
+-- cleanup
+DROP FOREIGN TABLE remote_analyze_ftable;
+DROP TABLE remote_analyze_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
--
2.53.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-30 09:32 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-03-30 09:32 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Wed, Mar 18, 2026 at 10:57 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> On Sat, Mar 14, 2026 at 4:05 PM Corey Huinker <corey.huinker@gmail.com> wrote:
>>> I've also moved the column matching - finding which rows of the attstats result set match to which columns in the local table - up into the fetch portion, something you had mentioned wanting to see as well. This resulted in some significant refactoring, but overall I think you will find the changes for the better.
>> I've added a reset of the result set indexes. Probably not necessary given that we only keep the result set if all the columns found homes, but good for peace of mind.
> And rebased to make the CI happy.
Thanks for updating patches!
I have been reviewing 0001 and 0002. Here are my comments/proposals I
have for now:
Core side:
* I proposed the StatisticsAreImportable callback function, but the
ImportStatistics callback function is now allowed to fall back to
analyzing, so I don't think StatisticsAreImportable has much value
anymore. I'll withdraw my proposal. Attached is an updated patch
removing it, in which 0001 is merged into 0002 for ease of review
(0001 can't be tested without 0002).
* I modified analyze.c to start progress monitor a bit earlier to
monitor the work of ImportStatistics (and AnalyzeForeignTable) as part
of initialization.
* I noticed this odd behavior:
create table t1 (id int, data text);
create foreign table ft1 (id int, data text) server loopback options
(table_name 't1');
alter foreign table ft1 options (add fetch_stats 'false');
analyze ft1 (ctid);
ERROR: column "ctid" of relation "ft1" does not exist
Looks good, but:
alter foreign table ft1 options (set fetch_stats 'true');
analyze ft1 (ctid);
NOTICE: remote table public.t1 has no statistics to import
HINT: Falling back to ANALYZE with regular row sampling.
ERROR: column "ctid" of relation "ft1" does not exist
postgres_fdw is doing the remote access without any need to do so,
which isn't good.
The cause is that the patches fail to validate the va_cols list given
to analyze_rel before importing stats. To fix, I modified analyze.c
to do so before calling ImportStatistics. I think this is also useful
when analyzing inheritance trees, as it avoids validating the list
repeatedly in that case.
* I separated a bit of code in examine_attribute that checks whether
the given column is analyzable into a new extern function so that FDWs
can use it.
postgres_fdw side:
* In fetch_remote_statistics, if we get reltuples=0 for v14 or later,
I think we should update only the relation stats with that info, and
avoid resorting to analyzing, for efficiency, as I proposed before. I
modified that function (and import_fetched_statistics) that way.
* I noticed that importing stats for a foreign table repeatedly like
this leads to incorrect attribute stats:
insert into t1 values ('aaa'), ('bbb'), ('ccc');
analyze t1;
analyze ft1;
select histogram_bounds from pg_stats where tablename = 'ft1';
histogram_bounds
------------------
{aaa,bbb,ccc}
(1 row)
delete from t1;
insert into t1 values ('foo'), ('foo'), ('foo');
analyze t1;
analyze ft1;
select histogram_bounds from pg_stats where tablename = 'ft1';
histogram_bounds
------------------
{aaa,bbb,ccc}
(1 row)
Old stats are remaining.
The root cause is that passing NULL to pg_restore_attribute_stats
leaves the stats unchanged. To fix, I modified
import_fetched_statistics to do pg_clear_attribute_stats before the
restore function.
* I don't think the error handling in import_fetched_statistics (and
match_attrmap) is safe:
+ plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+
+ if (plan == NULL || SPI_result < 0)
+ {
+ ereport(WARNING,
+ errmsg("import attribute statistics prepare failed %s "
+ "with error code %d",
+ attimport_sql, SPI_result));
+ goto import_cleanup;
+ }
In general, I think that if an error that should not happen happens,
continuing the processing isn't safe anymore; in such a case we should
throw an error to give the user a chance to decide what to do (eg,
retry after fixing issues or retry after setting the fetch_size option
to false if that's considered safe or ...). I think this is
consistent with the error handling of libpq functions we discussed
before. So I modified the handling in both functions to throw an
error in such cases.
* The matching logic in match_attrmap seems correct to me, but I think
it's still complicated than necessary: you are doing a merge join of
the RemoteAttributeMapping array and the attstats set by placing the
latter in the outer side, but it makes it simpler to do the join the
opposite way (ie, the former in the outer side), like the attached,
which doesn't need an inner for-loop anymore, as the inner side (ie,
the attstats set) consists of *distinct* columns.
* I moved table_has_extended_stats to extended_stats.c and renamed it
to match other functions in it so that other FDWs too can use it.
* The 0002 patch is using different levels (LOG, NOTICE, and WARNING)
for logging in postgresImportStatisitcs, but I think it's appropriate
to use elevel or WARNING for it. So I modified the patch to use
WARNING. I modified the wording as well to match analyze.c.
* I added at the top/end of postgresImportStatisitcs log messages that
show the start/end of importing stats.
That's it.
Best regards,
Etsuro Fujita
Attachments:
v17-Add-remote-statistics-fetching-to-postgres_fdw.patch (application/octet-stream, 49.2K) download
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 0f5271d476e..002c0a4ede5 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4559,7 +4560,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11481,6 +11483,12 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+WARNING: could not import statistics for foreign table "public.async_p2" --- remote table "public.base_tbl2" has no relation statistics to import
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11587,6 +11595,11 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+WARNING: could not import statistics for foreign table "public.async_p3" --- remote table "public.base_tbl3" has no relation statistics to import
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..5b7726800d0 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +279,10 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 41e47cc795b..f4c70ef8dd3 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -21,8 +21,11 @@
#include "commands/defrem.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
+#include "commands/vacuum.h"
#include "executor/execAsync.h"
#include "executor/instrument.h"
+#include "executor/spi.h"
+#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -40,9 +43,11 @@
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "postgres_fdw.h"
+#include "statistics/statistics.h"
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
+#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
@@ -318,6 +323,22 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ AttrNumber local_attnum;
+ char local_attname[NAMEDATALEN];
+ char remote_attname[NAMEDATALEN];
+ int res_index;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -403,6 +424,9 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -547,6 +571,210 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns
+{
+ RELSTATS_RELKIND = 0,
+ RELSTATS_RELPAGES,
+ RELSTATS_RELTUPLES,
+ RELSTATS_NUM_FIELDS,
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+static const char *attstats_query_default =
+"SELECT s.attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\"";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns
+{
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS,
+};
+
+static const char *relimport_sql =
+ "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', $1,\n"
+ "\t'schemaname', $2,\n"
+ "\t'relname', $3,\n"
+ "\t'relpages', $4::integer,\n"
+ "\t'reltuples', $5::real)";
+
+enum RelImportSqlArgs
+{
+ RELIMPORT_SQL_VERSION = 0,
+ RELIMPORT_SQL_SCHEMANAME,
+ RELIMPORT_SQL_RELNAME,
+ RELIMPORT_SQL_RELPAGES,
+ RELIMPORT_SQL_RELTUPLES,
+ RELIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid relimport_argtypes[RELIMPORT_SQL_NUM_FIELDS] =
+{
+ INT4OID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID,
+};
+
+static const char *attimport_sql =
+ "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', $1,\n"
+ "\t'schemaname', $2,\n"
+ "\t'relname', $3,\n"
+ "\t'attnum', $4,\n"
+ "\t'inherited', false::boolean,\n"
+ "\t'null_frac', $5::real,\n"
+ "\t'avg_width', $6::integer,\n"
+ "\t'n_distinct', $7::real,\n"
+ "\t'most_common_vals', $8,\n"
+ "\t'most_common_freqs', $9::real[],\n"
+ "\t'histogram_bounds', $10,\n"
+ "\t'correlation', $11::real,\n"
+ "\t'most_common_elems', $12,\n"
+ "\t'most_common_elem_freqs', $13::real[],\n"
+ "\t'elem_count_histogram', $14::real[],\n"
+ "\t'range_length_histogram', $15,\n"
+ "\t'range_empty_frac', $16::real,\n"
+ "\t'range_bounds_histogram', $17)";
+
+enum AttImportSqlArgs
+{
+ ATTIMPORT_SQL_VERSION = 0,
+ ATTIMPORT_SQL_SCHEMANAME,
+ ATTIMPORT_SQL_RELNAME,
+ ATTIMPORT_SQL_ATTNUM,
+ ATTIMPORT_SQL_NULL_FRAC,
+ ATTIMPORT_SQL_AVG_WIDTH,
+ ATTIMPORT_SQL_N_DISTINCT,
+ ATTIMPORT_SQL_MOST_COMMON_VALS,
+ ATTIMPORT_SQL_MOST_COMMON_FREQS,
+ ATTIMPORT_SQL_HISTOGRAM_BOUNDS,
+ ATTIMPORT_SQL_CORRELATION,
+ ATTIMPORT_SQL_MOST_COMMON_ELEMS,
+ ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS,
+ ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_EMPTY_FRAC,
+ ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM,
+ ATTIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid attimport_argtypes[ATTIMPORT_SQL_NUM_FIELDS] =
+{
+ INT4OID, TEXTOID, TEXTOID, INT2OID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID,
+};
+
+/* Pairs AttStatsColumns:AttImportSqlArgs Map */
+typedef struct
+{
+ enum AttStatsColumns res_field;
+ enum AttImportSqlArgs arg_num;
+} AttrResultArgMap;
+
+/*
+ * The mapping of attribute stats query columns to the positional arguments in
+ * the prepared pg_restore_attribute_stats() statement.
+ */
+#define NUM_MAPPED_ATTIMPORT_ARGS 13
+static const AttrResultArgMap attr_result_arg_map[NUM_MAPPED_ATTIMPORT_ARGS] =
+{
+ {ATTSTATS_NULL_FRAC, ATTIMPORT_SQL_NULL_FRAC},
+ {ATTSTATS_AVG_WIDTH, ATTIMPORT_SQL_AVG_WIDTH},
+ {ATTSTATS_N_DISTINCT, ATTIMPORT_SQL_N_DISTINCT},
+ {ATTSTATS_MOST_COMMON_VALS, ATTIMPORT_SQL_MOST_COMMON_VALS},
+ {ATTSTATS_MOST_COMMON_FREQS, ATTIMPORT_SQL_MOST_COMMON_FREQS},
+ {ATTSTATS_HISTOGRAM_BOUNDS, ATTIMPORT_SQL_HISTOGRAM_BOUNDS},
+ {ATTSTATS_CORRELATION, ATTIMPORT_SQL_CORRELATION},
+ {ATTSTATS_MOST_COMMON_ELEMS, ATTIMPORT_SQL_MOST_COMMON_ELEMS},
+ {ATTSTATS_MOST_COMMON_ELEM_FREQS, ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS},
+ {ATTSTATS_ELEM_COUNT_HISTOGRAM, ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM},
+ {ATTSTATS_RANGE_LENGTH_HISTOGRAM, ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM},
+ {ATTSTATS_RANGE_EMPTY_FRAC, ATTIMPORT_SQL_RANGE_EMPTY_FRAC},
+ {ATTSTATS_RANGE_BOUNDS_HISTOGRAM, ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM},
+};
+
+static const char *attclear_sql =
+ "SELECT pg_catalog.pg_clear_attribute_stats($1, $2, $3, false)";
+
+enum AttClearSqlArgs
+{
+ ATTCLEAR_SQL_SCHEMANAME = 0,
+ ATTCLEAR_SQL_RELNAME,
+ ATTCLEAR_SQL_ATTNAME,
+ ATTCLEAR_SQL_NUM_FIELDS
+};
+
+static const Oid attclear_argtypes[ATTCLEAR_SQL_NUM_FIELDS] =
+{
+ TEXTOID, TEXTOID, TEXTOID,
+};
+
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -596,6 +824,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4936,6 +5165,660 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Move a string value from a result set to a Text value of a Datum array.
+ */
+static void
+map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls)
+{
+ if (PQgetisnull(res, row, field))
+ {
+ values[arg] = (Datum) 0;
+ nulls[arg] = 'n';
+ }
+ else
+ {
+ const char *s = PQgetvalue(res, row, field);
+
+ values[arg] = CStringGetTextDatum(s);
+ nulls[arg] = ' ';
+ }
+}
+
+/*
+ * Check the 1x1 result set of a pg_restore_*_stats() command for success.
+ */
+static bool
+import_spi_query_ok(void)
+{
+ char *s;
+ bool ok;
+
+ Assert(SPI_tuptable != NULL);
+ Assert(SPI_processed == 1);
+ s = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
+ ok = (s != NULL && s[0] == 't' && s[1] == '\0');
+ pfree(s);
+
+ return ok;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static bool
+import_fetched_statistics(const char *schemaname,
+ const char *relname,
+ int server_version_num,
+ int natts,
+ const RemoteAttributeMapping *remattrmap,
+ RemoteStatsResults *remstats)
+{
+ SPIPlanPtr attimport_plan = NULL;
+ SPIPlanPtr attclear_plan = NULL;
+ Datum values[ATTIMPORT_SQL_NUM_FIELDS];
+ char nulls[ATTIMPORT_SQL_NUM_FIELDS];
+ int spirc;
+ bool ok = false;
+
+ /* Assign all the invariant parameters */
+ values[ATTIMPORT_SQL_VERSION] = Int32GetDatum(server_version_num);
+ nulls[ATTIMPORT_SQL_VERSION] = ' ';
+
+ values[ATTIMPORT_SQL_SCHEMANAME] = CStringGetTextDatum(schemaname);
+ nulls[ATTIMPORT_SQL_SCHEMANAME] = ' ';
+
+ values[ATTIMPORT_SQL_RELNAME] = CStringGetTextDatum(relname);
+ nulls[ATTIMPORT_SQL_RELNAME] = ' ';
+
+ SPI_connect();
+
+ /*
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ if (remstats->att != NULL)
+ {
+ Assert(PQnfields(remstats->att) == ATTSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats->att) >= 1);
+
+ attimport_plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+ if (attimport_plan == NULL)
+ elog(ERROR, "failed to prepare attimport_sql query");
+
+ attclear_plan = SPI_prepare(attclear_sql, ATTCLEAR_SQL_NUM_FIELDS,
+ (Oid *) attclear_argtypes);
+ if (attclear_plan == NULL)
+ elog(ERROR, "failed to prepare attclear_sql query");
+
+ nulls[ATTIMPORT_SQL_ATTNUM] = ' ';
+
+ for (int mapidx = 0; mapidx < natts; mapidx++)
+ {
+ int row = remattrmap[mapidx].res_index;
+ Datum *values2 = values + 1;
+ char *nulls2 = nulls + 1;
+
+ /* All mappings should have been assigned a result set row. */
+ Assert(row >= 0);
+
+ /*
+ * Check for user-requested abort.
+ */
+ CHECK_FOR_INTERRUPTS();
+
+ /*
+ * First, clear existing attribute stats.
+ *
+ * We can re-use the values/nulls because the number of parameters
+ * is less and the first two params are the same as the second and
+ * third ones in attimport_sql.
+ */
+ values2[ATTCLEAR_SQL_ATTNAME] =
+ CStringGetTextDatum(remattrmap[mapidx].local_attname);
+
+ spirc = SPI_execute_plan(attclear_plan, values2, nulls2, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute attclear_sql query for column \"%s\" of foreign table \"%s.%s\"",
+ remattrmap[mapidx].local_attname, schemaname, relname);
+
+ values[ATTIMPORT_SQL_ATTNUM] =
+ Int16GetDatum(remattrmap[mapidx].local_attnum);
+
+ /* Loop through all mappable columns to set remaining arguments */
+ for (int i = 0; i < NUM_MAPPED_ATTIMPORT_ARGS; i++)
+ map_field_to_arg(remstats->att, row,
+ attr_result_arg_map[i].res_field,
+ attr_result_arg_map[i].arg_num,
+ values, nulls);
+
+ spirc = SPI_execute_plan(attimport_plan, values, nulls, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute attimport_sql query for column \"%s\" of foreign table \"%s.%s\"",
+ remattrmap[mapidx].local_attname, schemaname, relname);
+
+ if (!import_spi_query_ok())
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- attribute statistics import failed for column \"%s\" of this foreign table",
+ schemaname, relname,
+ remattrmap[mapidx].local_attname));
+ goto import_cleanup;
+ }
+ }
+ }
+
+ /*
+ * Import relstats.
+ *
+ * Import relation stats. We only perform this once, so there is no point
+ * in preparing the statement.
+ *
+ * We can re-use the values/nulls because the number of parameters is less
+ * and the first three params are the same as attimport_sql.
+ */
+ Assert(remstats->rel != NULL);
+ Assert(PQnfields(remstats->rel) == RELSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats->rel) == 1);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELPAGES,
+ RELIMPORT_SQL_RELPAGES, values, nulls);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELTUPLES,
+ RELIMPORT_SQL_RELTUPLES, values, nulls);
+
+ spirc = SPI_execute_with_args(relimport_sql,
+ RELIMPORT_SQL_NUM_FIELDS,
+ (Oid *) relimport_argtypes,
+ values, nulls, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute relimport_sql query for foreign table \"%s.%s\"",
+ schemaname, relname);
+
+ if (!import_spi_query_ok())
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- relation statistics import failed for this foreign table",
+ schemaname, relname));
+ goto import_cleanup;
+ }
+
+ ok = true;
+
+import_cleanup:
+ if (attimport_plan)
+ SPI_freeplan(attimport_plan);
+ if (attclear_plan)
+ SPI_freeplan(attclear_plan);
+ SPI_finish();
+ return ok;
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn,
+ const char *remote_schemaname, const char *remote_relname)
+{
+ const char *params[2] = {remote_schemaname, remote_relname};
+ const char *sql = "SELECT c.relkind, c.relpages, c.reltuples "
+ "FROM pg_catalog.pg_class AS c "
+ "JOIN pg_catalog.pg_namespace AS n "
+ "ON n.oid = c.relnamespace "
+ "WHERE n.nspname = $1 AND c.relname = $2";
+ PGresult *res = NULL;
+
+ if (!PQsendQueryParams(conn, sql, 2, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, sql);
+
+ if (PQntuples(res) != 1 ||
+ PQnfields(res) != RELSTATS_NUM_FIELDS ||
+ PQgetisnull(res, 0, RELSTATS_RELKIND))
+ elog(ERROR, "unexpected result from fetch_relstats query");
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list)
+{
+ const char *params[3] = {remote_schemaname, remote_relname, column_list};
+ const char *sql;
+ PGresult *res;
+
+ if (server_version_num >= 170000)
+ sql = attstats_query_17;
+ else if (server_version_num >= 90200)
+ sql = attstats_query_9_2;
+ else if (server_version_num >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, sql);
+
+ if (PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ return res;
+}
+
+/*
+ * Match local columns to result set rows.
+ *
+ * As the result set consists of the attribute stats for some/all of distinct
+ * mapped remote columns in the RemoteAttributeMapping, every entry in it
+ * should have at most one match in the result set; which is also ordered by
+ * attname, so we find such pairs by doing a merge join.
+ *
+ * Returns true if every entry in it has a match, and false if not.
+ */
+static bool
+match_attrmap(PGresult *res,
+ const char *schemaname,
+ const char *relname,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int natts,
+ RemoteAttributeMapping *remattrmap)
+{
+ int numrows = PQntuples(res);
+ int row = -1;
+
+ /* No work if there are no stats rows. */
+ if (numrows == 0)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" has no attribute statistics to import",
+ schemaname, relname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* Scan all entries in the RemoteAttributeMapping. */
+ for (int i = 0; i < natts; i++)
+ {
+ /*
+ * First, check whether the entry matches the current stats row, if it
+ * is set.
+ */
+ if (row >= 0 &&
+ strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) == 0)
+ {
+ remattrmap[i].res_index = row;
+ continue;
+ }
+
+ /*
+ * If we've exhausted all stats rows, it means the stats for the entry
+ * are missing.
+ */
+ if (row >= numrows - 1)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- no attribute statistics found for column \"%s\" of remote table \"%s.%s\"",
+ schemaname, relname,
+ remattrmap[i].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* Advance to the next stats row. */
+ row += 1;
+
+ /*
+ * If the attname in the entry is less than that in the next stats row,
+ * it means the stats for the entry are missing.
+ */
+ if (strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) < 0)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- no attribute statistics found for column \"%s\" of remote table \"%s.%s\"",
+ schemaname, relname,
+ remattrmap[i].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* We should not get a stats row we didn't expect. */
+ if (strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) > 0)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ /* We found a match. */
+ Assert(strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) == 0);
+ remattrmap[i].res_index = row;
+ }
+
+ /* We should have exhausted all stats rows. */
+ if (row < numrows - 1)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ return true;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static bool
+fetch_remote_statistics(PGconn *conn,
+ const char *schemaname,
+ const char *relname,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int server_version_num,
+ int natts,
+ RemoteAttributeMapping *remattrmap,
+ const char *column_list,
+ RemoteStatsResults *remstats)
+{
+ PGresult *relstats = NULL;
+ PGresult *attstats = NULL;
+ char relkind;
+ double reltuples;
+
+ relstats = fetch_relstats(conn, remote_schemaname, remote_relname);
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
+ * can't support a foreign table.
+ */
+ relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
+ switch (relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ case RELKIND_PARTITIONED_TABLE:
+ break;
+ default:
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" is of relkind \"%c\" which cannot have statistics",
+ schemaname, relname,
+ remote_schemaname, remote_relname, relkind));
+ goto fetch_cleanup;
+ }
+
+ /*
+ * If the reltuples value > 0, then then we can expect to find attribute
+ * stats for the table.
+ *
+ * A reltuples value of -1 means the table has never been analyzed (v14+).
+ *
+ * In versions prior to v14, a value of 0 was ambiguous, it could mean
+ * that the table had never been analyzed, or that it was empty at the
+ * time that it was analyzed. Either way, we wouldn't expect to find
+ * attstats for the relation.
+ */
+ reltuples = strtod(PQgetvalue(relstats, 0, RELSTATS_RELTUPLES), NULL);
+ if (((server_version_num < 140000) && (reltuples == 0)) ||
+ ((server_version_num >= 140000) && (reltuples == -1)))
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" has no relation statistics to import",
+ schemaname, relname,
+ remote_schemaname, remote_relname));
+ goto fetch_cleanup;
+ }
+
+ if (reltuples > 0)
+ {
+ attstats = fetch_attstats(conn, server_version_num, remote_schemaname,
+ remote_relname, column_list);
+
+ /* Reject the stats if any are missing or in excess. */
+ if (!match_attrmap(attstats, schemaname, relname,
+ remote_schemaname, remote_relname,
+ natts, remattrmap))
+ goto fetch_cleanup;
+ }
+
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+
+fetch_cleanup:
+ PQclear(attstats);
+ PQclear(relstats);
+ return false;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static bool
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ UserMapping *user;
+ PGconn *conn;
+ int server_version_num;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ TupleDesc tupdesc;
+ RemoteStatsResults remstats = {.rel = NULL, .att = NULL};
+ RemoteAttributeMapping *remattrmap;
+ StringInfoData column_list;
+ int natts = 0;
+ bool fetch_stats = true;
+ bool ok = false;
+ ListCell *lc;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+
+ /*
+ * Check whether the fetch_stats option is enabled on the foreign table.
+ * If not, silently ignore the foreign table.
+ *
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+ if (!fetch_stats)
+ return false;
+
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ /*
+ * We don't currently support statistics import for foreign tables with
+ * extended statistics objects.
+ */
+ if (HasRelationExtStatistics(relation))
+ {
+ ereport(WARNING,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("cannot import statistics for foreign table \"%s.%s\" --- this foreign table has extended statistics objects",
+ schemaname, relname));
+ return false;
+ }
+
+ /*
+ * OK, let's do it.
+ */
+ ereport(elevel,
+ (errmsg("importing statistics for foreign table \"%s.%s\"",
+ schemaname, relname)));
+
+ /*
+ * Get connection to the foreign server. Connection manager will
+ * establish new connection if necessary.
+ */
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+
+ /*
+ * Assume the remote schema/relation names are the same as the local name
+ * unless the foreign table's options tell us otherwise.
+ */
+ remote_schemaname = schemaname;
+ remote_relname = relname;
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ }
+
+ /*
+ * Build local-attnum/remote-attname map and column list.
+ */
+ tupdesc = RelationGetDescr(relation);
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ initStringInfo(&column_list);
+ appendStringInfoChar(&column_list, '{');
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+ char *attname = NameStr(attr->attname);
+ AttrNumber attnum = attr->attnum;
+ char *remote_attname;
+ List *fc_options;
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ if (!attribute_is_analyzable(relation, attnum, attr, NULL))
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_attname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+ foreach(lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_attname = defGetString(def);
+ break;
+ }
+ }
+
+ if (i > 0)
+ appendStringInfoChar(&column_list, ',');
+ appendStringInfoString(&column_list, quote_identifier(remote_attname));
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].local_attname, attname, NAMEDATALEN);
+ strncpy(remattrmap[natts].remote_attname, remote_attname, NAMEDATALEN);
+ remattrmap[natts].res_index = -1;
+ natts++;
+ }
+ appendStringInfoChar(&column_list, '}');
+
+ /* Sort mapping by remote attribute name. */
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ ok = fetch_remote_statistics(conn, schemaname, relname,
+ remote_schemaname, remote_relname,
+ server_version_num, natts, remattrmap,
+ column_list.data, &remstats);
+
+ if (ok)
+ ok = import_fetched_statistics(schemaname, relname, server_version_num,
+ natts, remattrmap, &remstats);
+
+ if (ok)
+ ereport(elevel,
+ (errmsg("finished importing statistics for foreign table \"%s.%s\"",
+ schemaname, relname)));
+
+ pfree(remattrmap);
+ PQclear(remstats.rel);
+ PQclear(remstats.att);
+ ReleaseConnection(conn);
+
+ return ok;
+}
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 49ed797e8ef..a0f52e57dbc 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1293,7 +1294,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3917,6 +3919,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3954,6 +3961,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index de69ddcdebc..d7c0dc8ed14 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,29 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</function> and
+ <function>pg_restore_attribute_stats</function>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views). If the foreign table is a partition
+ of a partitioned table, analyzing the partitioned table will still
+ result in row sampling on the foreign table regardless of this setting,
+ though direct analysis of the foreign table would have attempted to
+ fetch remote statistics first.
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index eeed91be266..417a510e007 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -83,6 +83,7 @@ static void compute_index_stats(Relation onerel, double totalrows,
AnlIndexData *indexdata, int nindexes,
HeapTuple *rows, int numrows,
MemoryContext col_context);
+static void validate_va_cols_list(Relation onerel, List *va_cols);
static VacAttrStats *examine_attribute(Relation onerel, int attnum,
Node *index_expr);
static int acquire_sample_rows(Relation onerel, int elevel,
@@ -114,6 +115,7 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ bool stats_imported = false;
/* Select logging level */
if (params.options & VACOPT_VERBOSE)
@@ -182,6 +184,27 @@ analyze_rel(Oid relid, RangeVar *relation,
return;
}
+ /*
+ * Check the given list of columns
+ */
+ if (va_cols != NIL)
+ validate_va_cols_list(onerel, va_cols);
+
+ /*
+ * Initialize progress reporting before setup for regular/foreign tables.
+ * (For the former, the time spent on it would be negligible, but for the
+ * latter, if FDWs support statistics import or analysis, they'd do some
+ * work that needs the remote access, so the time can be non-negligible.)
+ */
+ pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
+ RelationGetRelid(onerel));
+ if (AmAutoVacuumWorkerProcess())
+ pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
+ PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
+ else
+ pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
+ PROGRESS_ANALYZE_STARTED_BY_MANUAL);
+
/*
* Check that it's of an analyzable relkind, and set up appropriately.
*/
@@ -196,26 +219,33 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->ImportStatistics(onerel, va_cols, elevel))
+ stats_imported = true;
+ else
{
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ goto out;
+ }
}
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
@@ -232,26 +262,16 @@ analyze_rel(Oid relid, RangeVar *relation,
(errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
RelationGetRelationName(onerel))));
relation_close(onerel, ShareUpdateExclusiveLock);
- return;
+ goto out;
}
- /*
- * OK, let's do it. First, initialize progress reporting.
- */
- pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
- RelationGetRelid(onerel));
- if (AmAutoVacuumWorkerProcess())
- pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
- PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
- else
- pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
- PROGRESS_ANALYZE_STARTED_BY_MANUAL);
-
/*
* Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * tables, which don't contain any rows, and foreign tables that
+ * successfully imported statistics.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ && !stats_imported)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
@@ -270,6 +290,7 @@ analyze_rel(Oid relid, RangeVar *relation,
*/
relation_close(onerel, NoLock);
+out:
pgstat_progress_end_command();
}
@@ -368,16 +389,10 @@ do_analyze_rel(Relation onerel, const VacuumParams params,
starttime = GetCurrentTimestamp();
/*
- * Determine which columns to analyze
- *
- * Note that system attributes are never analyzed, so we just reject them
- * at the lookup stage. We also reject duplicate column mentions. (We
- * could alternatively ignore duplicates, but analyzing a column twice
- * won't work; we'd end up making a conflicting update in pg_statistic.)
+ * Determine which columns to analyze.
*/
if (va_cols != NIL)
{
- Bitmapset *unique_cols = NULL;
ListCell *le;
vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
@@ -388,18 +403,7 @@ do_analyze_rel(Relation onerel, const VacuumParams params,
char *col = strVal(lfirst(le));
i = attnameAttNum(onerel, col, false);
- if (i == InvalidAttrNumber)
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_COLUMN),
- errmsg("column \"%s\" of relation \"%s\" does not exist",
- col, RelationGetRelationName(onerel))));
- if (bms_is_member(i, unique_cols))
- ereport(ERROR,
- (errcode(ERRCODE_DUPLICATE_COLUMN),
- errmsg("column \"%s\" of relation \"%s\" appears more than once",
- col, RelationGetRelationName(onerel))));
- unique_cols = bms_add_member(unique_cols, i);
-
+ Assert(i != InvalidAttrNumber);
vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
if (vacattrstats[tcnt] != NULL)
tcnt++;
@@ -1030,6 +1034,40 @@ compute_index_stats(Relation onerel, double totalrows,
MemoryContextDelete(ind_context);
}
+/*
+ * validate_va_cols_list -- validate the columns list given to analyze_rel
+ *
+ * Note that system attributes are never analyzed, so we just reject them at
+ * the lookup stage. We also reject duplicate column mentions. (We could
+ * alternatively ignore duplicates, but analyzing a column twice won't work;
+ * we'd end up making a conflicting update in pg_statistic.)
+ */
+static void
+validate_va_cols_list(Relation onerel, List *va_cols)
+{
+ Bitmapset *unique_cols = NULL;
+ ListCell *le;
+
+ Assert(va_cols != NIL);
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+ int i = attnameAttNum(onerel, col, false);
+
+ if (i == InvalidAttrNumber)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_COLUMN),
+ errmsg("column \"%s\" of relation \"%s\" does not exist",
+ col, RelationGetRelationName(onerel))));
+ if (bms_is_member(i, unique_cols))
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_COLUMN),
+ errmsg("column \"%s\" of relation \"%s\" appears more than once",
+ col, RelationGetRelationName(onerel))));
+ unique_cols = bms_add_member(unique_cols, i);
+ }
+}
+
/*
* examine_attribute -- pre-analysis of a single column
*
@@ -1044,37 +1082,15 @@ examine_attribute(Relation onerel, int attnum, Node *index_expr)
{
Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
int attstattarget;
- HeapTuple atttuple;
- Datum dat;
- bool isnull;
HeapTuple typtuple;
VacAttrStats *stats;
int i;
bool ok;
- /* Never analyze dropped columns */
- if (attr->attisdropped)
- return NULL;
-
- /* Don't analyze virtual generated columns */
- if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
- return NULL;
-
/*
- * Get attstattarget value. Set to -1 if null. (Analyze functions expect
- * -1 to mean use default_statistics_target; see for example
- * std_typanalyze.)
+ * Check if the column is analyzable.
*/
- atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
- if (!HeapTupleIsValid(atttuple))
- elog(ERROR, "cache lookup failed for attribute %d of relation %u",
- attnum, RelationGetRelid(onerel));
- dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
- attstattarget = isnull ? -1 : DatumGetInt16(dat);
- ReleaseSysCache(atttuple);
-
- /* Don't analyze column if user has specified not to */
- if (attstattarget == 0)
+ if (!attribute_is_analyzable(onerel, attnum, attr, &attstattarget))
return NULL;
/*
@@ -1155,6 +1171,45 @@ examine_attribute(Relation onerel, int attnum, Node *index_expr)
return stats;
}
+bool
+attribute_is_analyzable(Relation onerel, int attnum, Form_pg_attribute attr,
+ int *p_attstattarget)
+{
+ int attstattarget;
+ HeapTuple atttuple;
+ Datum dat;
+ bool isnull;
+
+ /* Never analyze dropped columns */
+ if (attr->attisdropped)
+ return false;
+
+ /* Don't analyze virtual generated columns */
+ if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
+ return false;
+
+ /*
+ * Get attstattarget value. Set to -1 if null. (Analyze functions expect
+ * -1 to mean use default_statistics_target; see for example
+ * std_typanalyze.)
+ */
+ atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, RelationGetRelid(onerel));
+ dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ /* Don't analyze column if user has specified not to */
+ if (attstattarget == 0)
+ return false;
+
+ if (p_attstattarget)
+ *p_attstattarget = attstattarget;
+ return true;
+}
+
/*
* Read stream callback returning the next BlockNumber as chosen by the
* BlockSampling algorithm.
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index 334c6498581..a546f377f44 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -245,6 +245,40 @@ BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows,
table_close(pg_stext, RowExclusiveLock);
}
+/*
+ * Test if the given relation has extended statistics objects.
+ */
+bool
+HasRelationExtStatistics(Relation onerel)
+{
+ Relation pg_statext;
+ SysScanDesc scan;
+ ScanKeyData skey;
+ bool found;
+
+ pg_statext = table_open(StatisticExtRelationId, RowExclusiveLock);
+
+ /*
+ * Prepare to scan pg_statistic_ext for entries having stxrelid = this
+ * rel.
+ */
+ ScanKeyInit(&skey,
+ Anum_pg_statistic_ext_stxrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(onerel)));
+
+ scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
+ NULL, 1, &skey);
+
+ found = HeapTupleIsValid(systable_getnext(scan));
+
+ systable_endscan(scan);
+
+ table_close(pg_statext, RowExclusiveLock);
+
+ return found;
+}
+
/*
* ComputeExtStatisticsRows
* Compute number of rows required by extended statistics on a table.
diff --git a/src/include/commands/vacuum.h b/src/include/commands/vacuum.h
index 1f45bca015c..f34c6bf9d5e 100644
--- a/src/include/commands/vacuum.h
+++ b/src/include/commands/vacuum.h
@@ -428,6 +428,8 @@ extern void parallel_vacuum_main(dsm_segment *seg, shm_toc *toc);
extern void analyze_rel(Oid relid, RangeVar *relation,
const VacuumParams params, List *va_cols, bool in_outer_xact,
BufferAccessStrategy bstrategy);
+extern bool attribute_is_analyzable(Relation onerel, int attnum, Form_pg_attribute attr,
+ int *p_attstattarget);
extern bool std_typanalyze(VacAttrStats *stats);
/* in utils/misc/sampling.c --- duplicate of declarations in utils/sampling.h */
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..ad0107b2549 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,10 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +259,7 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/include/statistics/statistics.h b/src/include/statistics/statistics.h
index 38a56f6ccb3..8f9b9d237fd 100644
--- a/src/include/statistics/statistics.h
+++ b/src/include/statistics/statistics.h
@@ -101,6 +101,7 @@ extern MCVList *statext_mcv_load(Oid mvoid, bool inh);
extern void BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows,
int numrows, HeapTuple *rows,
int natts, VacAttrStats **vacattrstats);
+extern bool HasRelationExtStatistics(Relation onerel);
extern int ComputeExtStatisticsRows(Relation onerel,
int natts, VacAttrStats **vacattrstats);
extern bool statext_is_kind_built(HeapTuple htup, char type);
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-30 09:42 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
2 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-03-30 09:42 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Sun, Mar 15, 2026 at 4:51 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>> I too was thinking of network timeouts (and in such a case I thought
>> that even if PQsendQuery was run successfully, the following
>> PQgetResult would have to block for a long time). And yes, that
>> situation can occur for normal queries, but in such a query, the extra
>> functions call is done only when aborting the remote transaction, in a
>> way libpq functions don't have to wait for a network timeout.
> I've copied the ERROR-behavior that was already done in postgresGetAnalyzeInfoForForeignTable(), which I assume will be to your liking.
>
> Structural error checks (how many columns does the result set have, etc) are now elog errors, bad PQresultStatus-es are now errors as well.
The patch looks good to me other than this bit in fetch_relstats/fetch_attstats:
+ res = pgfdw_get_result(conn);
+
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(NULL, conn, sql);
You forgot to pass the res to pgfdw_report_error for proper logging.
I fixed this in the patch I posted just before.
>> I forgot to mention this, but when we have reltuples = 0 for v14 or
>> later, the patch tries to import both relstats and attstats, but in
>> that case I think it would be OK to do so only for the former for the
>> consistency with the normal processing. What do you think about that?
> I've update the logic that we don't try to fetch attrstats if the reltuples is 0 or -1, and though the comments still mention the difference in server version, the code behaves the same in new versions and old. My thinking is that either value means "you are not going to find attstats" and our reaction is the same either way.
OK, but I modified this further in the patch. Please check it.
Thanks again!
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-30 20:04 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-03-30 20:04 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> * I proposed the StatisticsAreImportable callback function, but the
> ImportStatistics callback function is now allowed to fall back to
> analyzing, so I don't think StatisticsAreImportable has much value
> anymore. I'll withdraw my proposal. Attached is an updated patch
> removing it, in which 0001 is merged into 0002 for ease of review
> (0001 can't be tested without 0002).
>
Thanks.
> * I modified analyze.c to start progress monitor a bit earlier to
> monitor the work of ImportStatistics (and AnalyzeForeignTable) as part
> of initialization.
>
> * I noticed this odd behavior:
>
> create table t1 (id int, data text);
> create foreign table ft1 (id int, data text) server loopback options
> (table_name 't1');
>
> alter foreign table ft1 options (add fetch_stats 'false');
> analyze ft1 (ctid);
> ERROR: column "ctid" of relation "ft1" does not exist
>
> Looks good, but:
>
> alter foreign table ft1 options (set fetch_stats 'true');
> analyze ft1 (ctid);
> NOTICE: remote table public.t1 has no statistics to import
> HINT: Falling back to ANALYZE with regular row sampling.
> ERROR: column "ctid" of relation "ft1" does not exist
>
> postgres_fdw is doing the remote access without any need to do so,
> which isn't good.
>
> The cause is that the patches fail to validate the va_cols list given
> to analyze_rel before importing stats. To fix, I modified analyze.c
> to do so before calling ImportStatistics. I think this is also useful
> when analyzing inheritance trees, as it avoids validating the list
> repeatedly in that case.
>
I see this change and I like it.
> * I separated a bit of code in examine_attribute that checks whether
> the given column is analyzable into a new extern function so that FDWs
> can use it.
>
Interesting. I wouldn't have dared make a change that affected regular
analyze, but it makes sense.
postgres_fdw side:
>
> * In fetch_remote_statistics, if we get reltuples=0 for v14 or later,
> I think we should update only the relation stats with that info, and
> avoid resorting to analyzing, for efficiency, as I proposed before. I
> modified that function (and import_fetched_statistics) that way.
>
This will miss out on the case where the remote table did get analyzed
once, when empty, but now isn't empty. I realize that shouldn't happen very
often, but the cost of rowsampling a table that is empty is very low.
> The root cause is that passing NULL to pg_restore_attribute_stats
> leaves the stats unchanged. To fix, I modified
> import_fetched_statistics to do pg_clear_attribute_stats before the
> restore function.
>
+1
> * The matching logic in match_attrmap seems correct to me, but I think
> it's still complicated than necessary: you are doing a merge join of
> the RemoteAttributeMapping array and the attstats set by placing the
> latter in the outer side, but it makes it simpler to do the join the
> opposite way (ie, the former in the outer side), like the attached,
> which doesn't need an inner for-loop anymore, as the inner side (ie,
> the attstats set) consists of *distinct* columns.
>
The new match_attrmap seems reasonable.
> * I moved table_has_extended_stats to extended_stats.c and renamed it
> to match other functions in it so that other FDWs too can use it.
>
+1
> * The 0002 patch is using different levels (LOG, NOTICE, and WARNING)
> for logging in postgresImportStatisitcs, but I think it's appropriate
> to use elevel or WARNING for it. So I modified the patch to use
> WARNING. I modified the wording as well to match analyze.c.
>
+1
> * I added at the top/end of postgresImportStatisitcs log messages that
> show the start/end of importing stats.
>
+1
> That's it.
>
I see that remote_analyze didn't make it as a part of this patch. Is that
something you'd repackaged as a follow-on patch, or are you just done with
it?
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-03-30 20:05 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 0 replies; 89+ messages in thread
From: Corey Huinker @ 2026-03-30 20:05 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> You forgot to pass the res to pgfdw_report_error for proper logging.
> I fixed this in the patch I posted just before.
>
+1
>
> > I've update the logic that we don't try to fetch attrstats if the
> reltuples is 0 or -1, and though the comments still mention the difference
> in server version, the code behaves the same in new versions and old. My
> thinking is that either value means "you are not going to find attstats"
> and our reaction is the same either way.
>
Agree.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-01 11:39 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-04-01 11:39 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Tue, Mar 31, 2026 at 5:04 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>> postgres_fdw side:
>>
>> * In fetch_remote_statistics, if we get reltuples=0 for v14 or later,
>> I think we should update only the relation stats with that info, and
>> avoid resorting to analyzing, for efficiency, as I proposed before. I
>> modified that function (and import_fetched_statistics) that way.
>
> This will miss out on the case where the remote table did get analyzed once, when empty, but now isn't empty. I realize that shouldn't happen very often, but the cost of rowsampling a table that is empty is very low.
I think that that would be the user's fault, as it's the user's
responsibility to ensure that the existing stats for the remote table
are up-to-date. From another perspective, not all users will be able
to operate in such a way, so I'm thinking of disabling this feature by
default.
> I see that remote_analyze didn't make it as a part of this patch. Is that something you'd repackaged as a follow-on patch, or are you just done with it?
As just reviewing/polishing the 0001/0002 patches is a lot of work, I
didn't have time to look at the remote_analyze patch. We are running
out of time, so I'm afraid that I won't be able to have time for that.
I modified the patch further:
* Modified postgresImportStatistics to create RemoteAttributeMapping if needed.
* The query executed in fetch_relstats is almost the same as the one
executed in postgresGetAnalyzeInfoForForeignTable. To avoid code
duplication, I modified it to use the latter query. I also changed it
to use PQsendQuery, not PQsendQueryParams, for efficiency.
* Modified import_spi_query_ok to get the result of an import query by
using SPI_getbinval, not SPI_getvalue, for efficiency.
Attached is a new version of the patch.
Thanks for reviewing!
Best regards,
Etsuro Fujita
Attachments:
v18-Add-remote-statistics-fetching-to-postgres_fdw.patch (application/octet-stream, 51.1K) download
diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c
index c159ecd1558..2dcc6c8af1b 100644
--- a/contrib/postgres_fdw/deparse.c
+++ b/contrib/postgres_fdw/deparse.c
@@ -2541,8 +2541,8 @@ deparseAnalyzeSizeSql(StringInfo buf, Relation rel)
}
/*
- * Construct SELECT statement to acquire the number of rows and the relkind of
- * a relation.
+ * Construct SELECT statement to acquire the number of pages, the number of
+ * rows, and the relkind of a relation.
*
* Note: we just return the remote server's reltuples value, which might
* be off a good deal, but it doesn't seem worth working harder. See
@@ -2557,7 +2557,7 @@ deparseAnalyzeInfoSql(StringInfo buf, Relation rel)
initStringInfo(&relname);
deparseRelation(&relname, rel);
- appendStringInfoString(buf, "SELECT reltuples, relkind FROM pg_catalog.pg_class WHERE oid = ");
+ appendStringInfoString(buf, "SELECT relpages, reltuples, relkind FROM pg_catalog.pg_class WHERE oid = ");
deparseStringLiteral(buf, relname.data);
appendStringInfoString(buf, "::pg_catalog.regclass");
}
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 0f5271d476e..002c0a4ede5 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -252,6 +252,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
-- ===================================================================
@@ -4559,7 +4560,8 @@ REINDEX TABLE reind_fdw_parent; -- ok
REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -11481,6 +11483,12 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+WARNING: could not import statistics for foreign table "public.async_p2" --- remote table "public.base_tbl2" has no relation statistics to import
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
CREATE TABLE result_tbl (a int, b int, c text);
@@ -11587,6 +11595,11 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+WARNING: could not import statistics for foreign table "public.async_p3" --- remote table "public.base_tbl3" has no relation statistics to import
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505;
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..5b7726800d0 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +279,10 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 41e47cc795b..57cbf7c5126 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -21,8 +21,10 @@
#include "commands/defrem.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
+#include "commands/vacuum.h"
#include "executor/execAsync.h"
#include "executor/instrument.h"
+#include "executor/spi.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -40,6 +42,7 @@
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "postgres_fdw.h"
+#include "statistics/statistics.h"
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
@@ -318,6 +321,22 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ AttrNumber local_attnum;
+ char local_attname[NAMEDATALEN];
+ char remote_attname[NAMEDATALEN];
+ int res_index;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -403,6 +422,9 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -547,6 +569,210 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/*
+ * Static queries for querying remote statistics.
+ */
+
+/* All static relstats queries have the same column order */
+enum RelStatsColumns
+{
+ RELSTATS_RELPAGES = 0,
+ RELSTATS_RELTUPLES,
+ RELSTATS_RELKIND,
+ RELSTATS_NUM_FIELDS,
+};
+
+/* range stats introduced in v17 */
+static const char *attstats_query_17 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"s.range_length_histogram, s.range_empty_frac, s.range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* elements stats introduced in 9.2 */
+static const char *attstats_query_9_2 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, s.most_common_elems, "
+"s.most_common_elem_freqs, s.elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+/* inherited introduced in 9.0 */
+static const char *attstats_query_9_0 =
+"SELECT DISTINCT ON (s.attname COLLATE \"C\") attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\", s.inherited DESC";
+
+static const char *attstats_query_default =
+"SELECT s.attname, s.null_frac, s.avg_width, "
+"s.n_distinct, s.most_common_vals, s.most_common_freqs, "
+"s.histogram_bounds, s.correlation, NULL AS most_common_elems, "
+"NULL AS most_common_elem_freqs, NULL AS elem_count_histogram, "
+"NULL AS range_length_histogram, NULL AS range_empty_frac, "
+"NULL AS range_bounds_histogram "
+"FROM pg_catalog.pg_stats AS s "
+"WHERE s.schemaname = $1 AND s.tablename = $2 "
+"AND s.attname = ANY($3::text[]) "
+"ORDER BY s.attname COLLATE \"C\"";
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns
+{
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS,
+};
+
+static const char *relimport_sql =
+ "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', $1,\n"
+ "\t'schemaname', $2,\n"
+ "\t'relname', $3,\n"
+ "\t'relpages', $4::integer,\n"
+ "\t'reltuples', $5::real)";
+
+enum RelImportSqlArgs
+{
+ RELIMPORT_SQL_VERSION = 0,
+ RELIMPORT_SQL_SCHEMANAME,
+ RELIMPORT_SQL_RELNAME,
+ RELIMPORT_SQL_RELPAGES,
+ RELIMPORT_SQL_RELTUPLES,
+ RELIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid relimport_argtypes[RELIMPORT_SQL_NUM_FIELDS] =
+{
+ INT4OID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID,
+};
+
+static const char *attimport_sql =
+ "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', $1,\n"
+ "\t'schemaname', $2,\n"
+ "\t'relname', $3,\n"
+ "\t'attnum', $4,\n"
+ "\t'inherited', false::boolean,\n"
+ "\t'null_frac', $5::real,\n"
+ "\t'avg_width', $6::integer,\n"
+ "\t'n_distinct', $7::real,\n"
+ "\t'most_common_vals', $8,\n"
+ "\t'most_common_freqs', $9::real[],\n"
+ "\t'histogram_bounds', $10,\n"
+ "\t'correlation', $11::real,\n"
+ "\t'most_common_elems', $12,\n"
+ "\t'most_common_elem_freqs', $13::real[],\n"
+ "\t'elem_count_histogram', $14::real[],\n"
+ "\t'range_length_histogram', $15,\n"
+ "\t'range_empty_frac', $16::real,\n"
+ "\t'range_bounds_histogram', $17)";
+
+enum AttImportSqlArgs
+{
+ ATTIMPORT_SQL_VERSION = 0,
+ ATTIMPORT_SQL_SCHEMANAME,
+ ATTIMPORT_SQL_RELNAME,
+ ATTIMPORT_SQL_ATTNUM,
+ ATTIMPORT_SQL_NULL_FRAC,
+ ATTIMPORT_SQL_AVG_WIDTH,
+ ATTIMPORT_SQL_N_DISTINCT,
+ ATTIMPORT_SQL_MOST_COMMON_VALS,
+ ATTIMPORT_SQL_MOST_COMMON_FREQS,
+ ATTIMPORT_SQL_HISTOGRAM_BOUNDS,
+ ATTIMPORT_SQL_CORRELATION,
+ ATTIMPORT_SQL_MOST_COMMON_ELEMS,
+ ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS,
+ ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_EMPTY_FRAC,
+ ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM,
+ ATTIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid attimport_argtypes[ATTIMPORT_SQL_NUM_FIELDS] =
+{
+ INT4OID, TEXTOID, TEXTOID, INT2OID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID,
+};
+
+/* Pairs AttStatsColumns:AttImportSqlArgs Map */
+typedef struct
+{
+ enum AttStatsColumns res_field;
+ enum AttImportSqlArgs arg_num;
+} AttrResultArgMap;
+
+/*
+ * The mapping of attribute stats query columns to the positional arguments in
+ * the prepared pg_restore_attribute_stats() statement.
+ */
+#define NUM_MAPPED_ATTIMPORT_ARGS 13
+static const AttrResultArgMap attr_result_arg_map[NUM_MAPPED_ATTIMPORT_ARGS] =
+{
+ {ATTSTATS_NULL_FRAC, ATTIMPORT_SQL_NULL_FRAC},
+ {ATTSTATS_AVG_WIDTH, ATTIMPORT_SQL_AVG_WIDTH},
+ {ATTSTATS_N_DISTINCT, ATTIMPORT_SQL_N_DISTINCT},
+ {ATTSTATS_MOST_COMMON_VALS, ATTIMPORT_SQL_MOST_COMMON_VALS},
+ {ATTSTATS_MOST_COMMON_FREQS, ATTIMPORT_SQL_MOST_COMMON_FREQS},
+ {ATTSTATS_HISTOGRAM_BOUNDS, ATTIMPORT_SQL_HISTOGRAM_BOUNDS},
+ {ATTSTATS_CORRELATION, ATTIMPORT_SQL_CORRELATION},
+ {ATTSTATS_MOST_COMMON_ELEMS, ATTIMPORT_SQL_MOST_COMMON_ELEMS},
+ {ATTSTATS_MOST_COMMON_ELEM_FREQS, ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS},
+ {ATTSTATS_ELEM_COUNT_HISTOGRAM, ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM},
+ {ATTSTATS_RANGE_LENGTH_HISTOGRAM, ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM},
+ {ATTSTATS_RANGE_EMPTY_FRAC, ATTIMPORT_SQL_RANGE_EMPTY_FRAC},
+ {ATTSTATS_RANGE_BOUNDS_HISTOGRAM, ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM},
+};
+
+static const char *attclear_sql =
+ "SELECT pg_catalog.pg_clear_attribute_stats($1, $2, $3, false)";
+
+enum AttClearSqlArgs
+{
+ ATTCLEAR_SQL_SCHEMANAME = 0,
+ ATTCLEAR_SQL_RELNAME,
+ ATTCLEAR_SQL_ATTNAME,
+ ATTCLEAR_SQL_NUM_FIELDS
+};
+
+static const Oid attclear_argtypes[ATTCLEAR_SQL_NUM_FIELDS] =
+{
+ TEXTOID, TEXTOID, TEXTOID,
+};
+
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -596,6 +822,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4936,6 +5163,683 @@ postgresAnalyzeForeignTable(Relation relation,
return true;
}
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Move a string value from a result set to a Text value of a Datum array.
+ */
+static void
+map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls)
+{
+ if (PQgetisnull(res, row, field))
+ {
+ values[arg] = (Datum) 0;
+ nulls[arg] = 'n';
+ }
+ else
+ {
+ const char *s = PQgetvalue(res, row, field);
+
+ values[arg] = CStringGetTextDatum(s);
+ nulls[arg] = ' ';
+ }
+}
+
+/*
+ * Check the 1x1 result set of a pg_restore_*_stats() command for success.
+ */
+static bool
+import_spi_query_ok(void)
+{
+ TupleDesc tupdesc;
+ Datum dat;
+ bool isnull;
+
+ Assert(SPI_tuptable != NULL);
+ Assert(SPI_processed == 1);
+
+ tupdesc = SPI_tuptable->tupdesc;
+ Assert(tupdesc->natts == 1);
+ Assert(TupleDescAttr(tupdesc, 0)->atttypid == BOOLOID);
+ dat = SPI_getbinval(SPI_tuptable->vals[0], tupdesc, 1, &isnull);
+ Assert(!isnull);
+
+ return DatumGetBool(dat);
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static bool
+import_fetched_statistics(const char *schemaname,
+ const char *relname,
+ int server_version_num,
+ int natts,
+ const RemoteAttributeMapping *remattrmap,
+ RemoteStatsResults *remstats)
+{
+ SPIPlanPtr attimport_plan = NULL;
+ SPIPlanPtr attclear_plan = NULL;
+ Datum values[ATTIMPORT_SQL_NUM_FIELDS];
+ char nulls[ATTIMPORT_SQL_NUM_FIELDS];
+ int spirc;
+ bool ok = false;
+
+ /* Assign all the invariant parameters */
+ values[ATTIMPORT_SQL_VERSION] = Int32GetDatum(server_version_num);
+ nulls[ATTIMPORT_SQL_VERSION] = ' ';
+
+ values[ATTIMPORT_SQL_SCHEMANAME] = CStringGetTextDatum(schemaname);
+ nulls[ATTIMPORT_SQL_SCHEMANAME] = ' ';
+
+ values[ATTIMPORT_SQL_RELNAME] = CStringGetTextDatum(relname);
+ nulls[ATTIMPORT_SQL_RELNAME] = ' ';
+
+ SPI_connect();
+
+ /*
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ if (remstats->att != NULL)
+ {
+ Assert(PQnfields(remstats->att) == ATTSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats->att) >= 1);
+
+ attimport_plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+ if (attimport_plan == NULL)
+ elog(ERROR, "failed to prepare attimport_sql query");
+
+ attclear_plan = SPI_prepare(attclear_sql, ATTCLEAR_SQL_NUM_FIELDS,
+ (Oid *) attclear_argtypes);
+ if (attclear_plan == NULL)
+ elog(ERROR, "failed to prepare attclear_sql query");
+
+ nulls[ATTIMPORT_SQL_ATTNUM] = ' ';
+
+ for (int mapidx = 0; mapidx < natts; mapidx++)
+ {
+ int row = remattrmap[mapidx].res_index;
+ Datum *values2 = values + 1;
+ char *nulls2 = nulls + 1;
+
+ /* All mappings should have been assigned a result set row. */
+ Assert(row >= 0);
+
+ /*
+ * Check for user-requested abort.
+ */
+ CHECK_FOR_INTERRUPTS();
+
+ /*
+ * First, clear existing attribute stats.
+ *
+ * We can re-use the values/nulls because the number of parameters
+ * is less and the first two params are the same as the second and
+ * third ones in attimport_sql.
+ */
+ values2[ATTCLEAR_SQL_ATTNAME] =
+ CStringGetTextDatum(remattrmap[mapidx].local_attname);
+
+ spirc = SPI_execute_plan(attclear_plan, values2, nulls2, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute attclear_sql query for column \"%s\" of foreign table \"%s.%s\"",
+ remattrmap[mapidx].local_attname, schemaname, relname);
+
+ values[ATTIMPORT_SQL_ATTNUM] =
+ Int16GetDatum(remattrmap[mapidx].local_attnum);
+
+ /* Loop through all mappable columns to set remaining arguments */
+ for (int i = 0; i < NUM_MAPPED_ATTIMPORT_ARGS; i++)
+ map_field_to_arg(remstats->att, row,
+ attr_result_arg_map[i].res_field,
+ attr_result_arg_map[i].arg_num,
+ values, nulls);
+
+ spirc = SPI_execute_plan(attimport_plan, values, nulls, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute attimport_sql query for column \"%s\" of foreign table \"%s.%s\"",
+ remattrmap[mapidx].local_attname, schemaname, relname);
+
+ if (!import_spi_query_ok())
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- attribute statistics import failed for column \"%s\" of this foreign table",
+ schemaname, relname,
+ remattrmap[mapidx].local_attname));
+ goto import_cleanup;
+ }
+ }
+ }
+
+ /*
+ * Import relstats.
+ *
+ * Import relation stats. We only perform this once, so there is no point
+ * in preparing the statement.
+ *
+ * We can re-use the values/nulls because the number of parameters is less
+ * and the first three params are the same as attimport_sql.
+ */
+ Assert(remstats->rel != NULL);
+ Assert(PQnfields(remstats->rel) == RELSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats->rel) == 1);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELPAGES,
+ RELIMPORT_SQL_RELPAGES, values, nulls);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELTUPLES,
+ RELIMPORT_SQL_RELTUPLES, values, nulls);
+
+ spirc = SPI_execute_with_args(relimport_sql,
+ RELIMPORT_SQL_NUM_FIELDS,
+ (Oid *) relimport_argtypes,
+ values, nulls, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute relimport_sql query for foreign table \"%s.%s\"",
+ schemaname, relname);
+
+ if (!import_spi_query_ok())
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- relation statistics import failed for this foreign table",
+ schemaname, relname));
+ goto import_cleanup;
+ }
+
+ ok = true;
+
+import_cleanup:
+ if (attimport_plan)
+ SPI_freeplan(attimport_plan);
+ if (attclear_plan)
+ SPI_freeplan(attclear_plan);
+ SPI_finish();
+ return ok;
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn, Relation relation)
+{
+ StringInfoData sql;
+ PGresult *res;
+
+ initStringInfo(&sql);
+ deparseAnalyzeInfoSql(&sql, relation);
+
+ res = pgfdw_exec_query(conn, sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, sql.data);
+
+ if (PQntuples(res) != 1 || PQnfields(res) != RELSTATS_NUM_FIELDS)
+ elog(ERROR, "unexpected result from deparseAnalyzeInfoSql query");
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list)
+{
+ const char *params[3] = {remote_schemaname, remote_relname, column_list};
+ const char *sql;
+ PGresult *res;
+
+ if (server_version_num >= 170000)
+ sql = attstats_query_17;
+ else if (server_version_num >= 90200)
+ sql = attstats_query_9_2;
+ else if (server_version_num >= 90000)
+ sql = attstats_query_9_0;
+ else
+ sql = attstats_query_default;
+
+ if (!PQsendQueryParams(conn, sql, 3, NULL, params, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, sql);
+
+ res = pgfdw_get_result(conn);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, sql);
+
+ if (PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ return res;
+}
+
+/*
+ * Match local columns to result set rows.
+ *
+ * As the result set consists of the attribute stats for some/all of distinct
+ * mapped remote columns in the RemoteAttributeMapping, every entry in it
+ * should have at most one match in the result set; which is also ordered by
+ * attname, so we find such pairs by doing a merge join.
+ *
+ * Returns true if every entry in it has a match, and false if not.
+ */
+static bool
+match_attrmap(PGresult *res,
+ const char *schemaname,
+ const char *relname,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int natts,
+ RemoteAttributeMapping *remattrmap)
+{
+ int numrows = PQntuples(res);
+ int row = -1;
+
+ /* No work if there are no stats rows. */
+ if (numrows == 0)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" has no attribute statistics to import",
+ schemaname, relname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* Scan all entries in the RemoteAttributeMapping. */
+ for (int i = 0; i < natts; i++)
+ {
+ /*
+ * First, check whether the entry matches the current stats row, if it
+ * is set.
+ */
+ if (row >= 0 &&
+ strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) == 0)
+ {
+ remattrmap[i].res_index = row;
+ continue;
+ }
+
+ /*
+ * If we've exhausted all stats rows, it means the stats for the entry
+ * are missing.
+ */
+ if (row >= numrows - 1)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- no attribute statistics found for column \"%s\" of remote table \"%s.%s\"",
+ schemaname, relname,
+ remattrmap[i].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* Advance to the next stats row. */
+ row += 1;
+
+ /*
+ * If the attname in the entry is less than that in the next stats row,
+ * it means the stats for the entry are missing.
+ */
+ if (strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) < 0)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- no attribute statistics found for column \"%s\" of remote table \"%s.%s\"",
+ schemaname, relname,
+ remattrmap[i].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* We should not have got a stats row we didn't expect. */
+ if (strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) > 0)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ /* We found a match. */
+ Assert(strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) == 0);
+ remattrmap[i].res_index = row;
+ }
+
+ /* We should have exhausted all stats rows. */
+ if (row < numrows - 1)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ return true;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Build local-attnum/remote-attname map and column list.
+ */
+static RemoteAttributeMapping *
+build_remattrmap(Relation relation, List *va_cols,
+ int *p_natts, StringInfo column_list)
+{
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ RemoteAttributeMapping *remattrmap = NULL;
+ int natts = 0;
+
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ initStringInfo(column_list);
+ appendStringInfoChar(column_list, '{');
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+ char *attname = NameStr(attr->attname);
+ AttrNumber attnum = attr->attnum;
+ char *remote_attname;
+ List *fc_options;
+ ListCell *lc;
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ if (!attribute_is_analyzable(relation, attnum, attr, NULL))
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_attname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+ foreach(lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_attname = defGetString(def);
+ break;
+ }
+ }
+
+ if (i > 0)
+ appendStringInfoString(column_list, ", ");
+ appendStringInfoString(column_list, quote_identifier(remote_attname));
+
+ remattrmap[natts].local_attnum = attnum;
+ strncpy(remattrmap[natts].local_attname, attname, NAMEDATALEN);
+ strncpy(remattrmap[natts].remote_attname, remote_attname, NAMEDATALEN);
+ remattrmap[natts].res_index = -1;
+ natts++;
+ }
+ appendStringInfoChar(column_list, '}');
+
+ /* Sort mapping by remote attribute name. */
+ if (natts > 1)
+ qsort(remattrmap, natts, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ *p_natts = natts;
+ return remattrmap;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static bool
+fetch_remote_statistics(PGconn *conn,
+ Relation relation,
+ List *va_cols,
+ ForeignTable *table,
+ const char *schemaname,
+ const char *relname,
+ int server_version_num,
+ int *p_natts,
+ RemoteAttributeMapping **p_remattrmap,
+ RemoteStatsResults *remstats)
+{
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ PGresult *relstats = NULL;
+ PGresult *attstats = NULL;
+ RemoteAttributeMapping *remattrmap = NULL;
+ int natts = 0;
+ char relkind;
+ double reltuples;
+ ListCell *lc;
+
+ /*
+ * Assume the remote schema/relation names are the same as the local name
+ * unless the foreign table's options tell us otherwise.
+ */
+ remote_schemaname = schemaname;
+ remote_relname = relname;
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ }
+
+ relstats = fetch_relstats(conn, relation);
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
+ * can't support a foreign table.
+ */
+ relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
+ switch (relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ case RELKIND_PARTITIONED_TABLE:
+ break;
+ default:
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" is of relkind \"%c\" which cannot have statistics",
+ schemaname, relname,
+ remote_schemaname, remote_relname, relkind));
+ goto fetch_cleanup;
+ }
+
+ /*
+ * If the reltuples value > 0, then then we can expect to find attribute
+ * stats for the table.
+ *
+ * A reltuples value of -1 means the table has never been analyzed (v14+).
+ *
+ * In versions prior to v14, a value of 0 was ambiguous, it could mean
+ * that the table had never been analyzed, or that it was empty at the
+ * time that it was analyzed. Either way, we wouldn't expect to find
+ * attstats for the relation.
+ */
+ reltuples = strtod(PQgetvalue(relstats, 0, RELSTATS_RELTUPLES), NULL);
+ if (((server_version_num < 140000) && (reltuples == 0)) ||
+ ((server_version_num >= 140000) && (reltuples == -1)))
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" has no relation statistics to import",
+ schemaname, relname,
+ remote_schemaname, remote_relname));
+ goto fetch_cleanup;
+ }
+
+ if (reltuples > 0)
+ {
+ StringInfoData column_list;
+
+ remattrmap = build_remattrmap(relation, va_cols, &natts, &column_list);
+
+ if (natts > 0)
+ {
+ attstats = fetch_attstats(conn, server_version_num,
+ remote_schemaname, remote_relname,
+ column_list.data);
+
+ /* Reject the stats if any are missing or in excess. */
+ if (!match_attrmap(attstats, schemaname, relname,
+ remote_schemaname, remote_relname,
+ natts, remattrmap))
+ goto fetch_cleanup;
+ }
+
+ *p_remattrmap = remattrmap;
+ *p_natts = natts;
+ }
+
+ remstats->rel = relstats;
+ remstats->att = attstats;
+ return true;
+
+fetch_cleanup:
+ if (remattrmap)
+ pfree(remattrmap);
+ PQclear(attstats);
+ PQclear(relstats);
+ return false;
+}
+
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static bool
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ UserMapping *user;
+ PGconn *conn;
+ int server_version_num;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ RemoteStatsResults remstats = {.rel = NULL, .att = NULL};
+ RemoteAttributeMapping *remattrmap = NULL;
+ int natts = 0;
+ bool fetch_stats = true;
+ bool ok = false;
+ ListCell *lc;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ /*
+ * Check whether the fetch_stats option is enabled on the foreign table.
+ * If not, silently ignore the foreign table.
+ *
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+ if (!fetch_stats)
+ return false;
+
+ /*
+ * We don't currently support statistics import for foreign tables with
+ * extended statistics objects.
+ */
+ if (HasRelationExtStatistics(relation))
+ {
+ ereport(WARNING,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("cannot import statistics for foreign table \"%s.%s\" --- this foreign table has extended statistics objects",
+ schemaname, relname));
+ return false;
+ }
+
+ /*
+ * OK, let's do it.
+ */
+ ereport(elevel,
+ (errmsg("importing statistics for foreign table \"%s.%s\"",
+ schemaname, relname)));
+
+ /*
+ * Get connection to the foreign server. Connection manager will
+ * establish new connection if necessary.
+ */
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ server_version_num = PQserverVersion(conn);
+
+ ok = fetch_remote_statistics(conn, relation, va_cols,
+ table, schemaname, relname,
+ server_version_num,
+ &natts, &remattrmap, &remstats);
+
+ if (ok)
+ ok = import_fetched_statistics(schemaname, relname, server_version_num,
+ natts, remattrmap, &remstats);
+
+ if (ok)
+ ereport(elevel,
+ (errmsg("finished importing statistics for foreign table \"%s.%s\"",
+ schemaname, relname)));
+
+ if (remattrmap)
+ pfree(remattrmap);
+ PQclear(remstats.rel);
+ PQclear(remstats.att);
+ ReleaseConnection(conn);
+
+ return ok;
+}
+
/*
* postgresGetAnalyzeInfoForForeignTable
* Count tuples in foreign table (just get pg_class.reltuples).
@@ -4975,10 +5879,11 @@ postgresGetAnalyzeInfoForForeignTable(Relation relation, bool *can_tablesample)
if (PQresultStatus(res) != PGRES_TUPLES_OK)
pgfdw_report_error(res, conn, sql.data);
- if (PQntuples(res) != 1 || PQnfields(res) != 2)
+ if (PQntuples(res) != 1 || PQnfields(res) != RELSTATS_NUM_FIELDS)
elog(ERROR, "unexpected result from deparseAnalyzeInfoSql query");
- reltuples = strtod(PQgetvalue(res, 0, 0), NULL);
- relkind = *(PQgetvalue(res, 0, 1));
+ /* We don't use relpages here */
+ reltuples = strtod(PQgetvalue(res, 0, RELSTATS_RELTUPLES), NULL);
+ relkind = *(PQgetvalue(res, 0, RELSTATS_RELKIND));
PQclear(res);
ReleaseConnection(conn);
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 49ed797e8ef..a0f52e57dbc 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -241,6 +241,7 @@ SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again
-- Now we should be able to run ANALYZE.
-- To exercise multiple code paths, we use local stats on ft1
-- and remote-estimate mode on ft2.
+ALTER SERVER loopback OPTIONS (ADD fetch_stats 'false');
ANALYZE ft1;
ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true');
@@ -1293,7 +1294,8 @@ REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok
DROP TABLE reind_fdw_parent;
-- ===================================================================
--- conversion error
+-- conversion error, will generate a WARNING for imported stats and an
+-- error on locally computed stats.
-- ===================================================================
ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int;
SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR
@@ -3917,6 +3919,11 @@ CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3
SERVER loopback2 OPTIONS (table_name 'base_tbl2');
INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will failover to sampling on async_p2 because fetch_stats = true (the default) on
+-- loopback2, and is set to false on loopback
+ANALYZE async_pt;
+-- Turning off fetch_stats at the table level for async_p2 removes the warning.
+ALTER FOREIGN TABLE async_p2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
-- simple queries
@@ -3954,6 +3961,10 @@ CREATE TABLE base_tbl3 (a int, b int, c text);
CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000)
SERVER loopback2 OPTIONS (table_name 'base_tbl3');
INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i;
+-- Will fail because fetch_stats = true (the default) on async_p3/loopback2
+ANALYZE async_pt;
+-- Turn off fetch_stats at the server level.
+ALTER SERVER loopback2 OPTIONS (ADD fetch_stats 'false');
ANALYZE async_pt;
EXPLAIN (VERBOSE, COSTS OFF)
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index de69ddcdebc..d7c0dc8ed14 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,29 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</function> and
+ <function>pg_restore_attribute_stats</function>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views). If the foreign table is a partition
+ of a partitioned table, analyzing the partitioned table will still
+ result in row sampling on the foreign table regardless of this setting,
+ though direct analysis of the foreign table would have attempted to
+ fetch remote statistics first.
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 49a5cdf579c..12714a249db 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -83,6 +83,7 @@ static void compute_index_stats(Relation onerel, double totalrows,
AnlIndexData *indexdata, int nindexes,
HeapTuple *rows, int numrows,
MemoryContext col_context);
+static void validate_va_cols_list(Relation onerel, List *va_cols);
static VacAttrStats *examine_attribute(Relation onerel, int attnum,
Node *index_expr);
static int acquire_sample_rows(Relation onerel, int elevel,
@@ -114,6 +115,7 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ bool stats_imported = false;
/* Select logging level */
if (params->options & VACOPT_VERBOSE)
@@ -182,6 +184,27 @@ analyze_rel(Oid relid, RangeVar *relation,
return;
}
+ /*
+ * Check the given list of columns
+ */
+ if (va_cols != NIL)
+ validate_va_cols_list(onerel, va_cols);
+
+ /*
+ * Initialize progress reporting before setup for regular/foreign tables.
+ * (For the former, the time spent on it would be negligible, but for the
+ * latter, if FDWs support statistics import or analysis, they'd do some
+ * work that needs the remote access, so the time can be non-negligible.)
+ */
+ pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
+ RelationGetRelid(onerel));
+ if (AmAutoVacuumWorkerProcess())
+ pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
+ PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
+ else
+ pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
+ PROGRESS_ANALYZE_STARTED_BY_MANUAL);
+
/*
* Check that it's of an analyzable relkind, and set up appropriately.
*/
@@ -196,26 +219,33 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->ImportStatistics(onerel, va_cols, elevel))
+ stats_imported = true;
+ else
{
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ goto out;
+ }
}
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
@@ -232,26 +262,16 @@ analyze_rel(Oid relid, RangeVar *relation,
(errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
RelationGetRelationName(onerel))));
relation_close(onerel, ShareUpdateExclusiveLock);
- return;
+ goto out;
}
- /*
- * OK, let's do it. First, initialize progress reporting.
- */
- pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
- RelationGetRelid(onerel));
- if (AmAutoVacuumWorkerProcess())
- pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
- PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
- else
- pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
- PROGRESS_ANALYZE_STARTED_BY_MANUAL);
-
/*
* Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * tables, which don't contain any rows, and foreign tables that
+ * successfully imported statistics.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ && !stats_imported)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
@@ -270,6 +290,7 @@ analyze_rel(Oid relid, RangeVar *relation,
*/
relation_close(onerel, NoLock);
+out:
pgstat_progress_end_command();
}
@@ -368,16 +389,10 @@ do_analyze_rel(Relation onerel, const VacuumParams *params,
starttime = GetCurrentTimestamp();
/*
- * Determine which columns to analyze
- *
- * Note that system attributes are never analyzed, so we just reject them
- * at the lookup stage. We also reject duplicate column mentions. (We
- * could alternatively ignore duplicates, but analyzing a column twice
- * won't work; we'd end up making a conflicting update in pg_statistic.)
+ * Determine which columns to analyze.
*/
if (va_cols != NIL)
{
- Bitmapset *unique_cols = NULL;
ListCell *le;
vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
@@ -388,18 +403,7 @@ do_analyze_rel(Relation onerel, const VacuumParams *params,
char *col = strVal(lfirst(le));
i = attnameAttNum(onerel, col, false);
- if (i == InvalidAttrNumber)
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_COLUMN),
- errmsg("column \"%s\" of relation \"%s\" does not exist",
- col, RelationGetRelationName(onerel))));
- if (bms_is_member(i, unique_cols))
- ereport(ERROR,
- (errcode(ERRCODE_DUPLICATE_COLUMN),
- errmsg("column \"%s\" of relation \"%s\" appears more than once",
- col, RelationGetRelationName(onerel))));
- unique_cols = bms_add_member(unique_cols, i);
-
+ Assert(i != InvalidAttrNumber);
vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
if (vacattrstats[tcnt] != NULL)
tcnt++;
@@ -1030,6 +1034,40 @@ compute_index_stats(Relation onerel, double totalrows,
MemoryContextDelete(ind_context);
}
+/*
+ * validate_va_cols_list -- validate the columns list given to analyze_rel
+ *
+ * Note that system attributes are never analyzed, so we just reject them at
+ * the lookup stage. We also reject duplicate column mentions. (We could
+ * alternatively ignore duplicates, but analyzing a column twice won't work;
+ * we'd end up making a conflicting update in pg_statistic.)
+ */
+static void
+validate_va_cols_list(Relation onerel, List *va_cols)
+{
+ Bitmapset *unique_cols = NULL;
+ ListCell *le;
+
+ Assert(va_cols != NIL);
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+ int i = attnameAttNum(onerel, col, false);
+
+ if (i == InvalidAttrNumber)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_COLUMN),
+ errmsg("column \"%s\" of relation \"%s\" does not exist",
+ col, RelationGetRelationName(onerel))));
+ if (bms_is_member(i, unique_cols))
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_COLUMN),
+ errmsg("column \"%s\" of relation \"%s\" appears more than once",
+ col, RelationGetRelationName(onerel))));
+ unique_cols = bms_add_member(unique_cols, i);
+ }
+}
+
/*
* examine_attribute -- pre-analysis of a single column
*
@@ -1044,37 +1082,15 @@ examine_attribute(Relation onerel, int attnum, Node *index_expr)
{
Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
int attstattarget;
- HeapTuple atttuple;
- Datum dat;
- bool isnull;
HeapTuple typtuple;
VacAttrStats *stats;
int i;
bool ok;
- /* Never analyze dropped columns */
- if (attr->attisdropped)
- return NULL;
-
- /* Don't analyze virtual generated columns */
- if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
- return NULL;
-
/*
- * Get attstattarget value. Set to -1 if null. (Analyze functions expect
- * -1 to mean use default_statistics_target; see for example
- * std_typanalyze.)
+ * Check if the column is analyzable.
*/
- atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
- if (!HeapTupleIsValid(atttuple))
- elog(ERROR, "cache lookup failed for attribute %d of relation %u",
- attnum, RelationGetRelid(onerel));
- dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
- attstattarget = isnull ? -1 : DatumGetInt16(dat);
- ReleaseSysCache(atttuple);
-
- /* Don't analyze column if user has specified not to */
- if (attstattarget == 0)
+ if (!attribute_is_analyzable(onerel, attnum, attr, &attstattarget))
return NULL;
/*
@@ -1155,6 +1171,45 @@ examine_attribute(Relation onerel, int attnum, Node *index_expr)
return stats;
}
+bool
+attribute_is_analyzable(Relation onerel, int attnum, Form_pg_attribute attr,
+ int *p_attstattarget)
+{
+ int attstattarget;
+ HeapTuple atttuple;
+ Datum dat;
+ bool isnull;
+
+ /* Never analyze dropped columns */
+ if (attr->attisdropped)
+ return false;
+
+ /* Don't analyze virtual generated columns */
+ if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
+ return false;
+
+ /*
+ * Get attstattarget value. Set to -1 if null. (Analyze functions expect
+ * -1 to mean use default_statistics_target; see for example
+ * std_typanalyze.)
+ */
+ atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, RelationGetRelid(onerel));
+ dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ /* Don't analyze column if user has specified not to */
+ if (attstattarget == 0)
+ return false;
+
+ if (p_attstattarget)
+ *p_attstattarget = attstattarget;
+ return true;
+}
+
/*
* Read stream callback returning the next BlockNumber as chosen by the
* BlockSampling algorithm.
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index 334c6498581..a546f377f44 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -245,6 +245,40 @@ BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows,
table_close(pg_stext, RowExclusiveLock);
}
+/*
+ * Test if the given relation has extended statistics objects.
+ */
+bool
+HasRelationExtStatistics(Relation onerel)
+{
+ Relation pg_statext;
+ SysScanDesc scan;
+ ScanKeyData skey;
+ bool found;
+
+ pg_statext = table_open(StatisticExtRelationId, RowExclusiveLock);
+
+ /*
+ * Prepare to scan pg_statistic_ext for entries having stxrelid = this
+ * rel.
+ */
+ ScanKeyInit(&skey,
+ Anum_pg_statistic_ext_stxrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(onerel)));
+
+ scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
+ NULL, 1, &skey);
+
+ found = HeapTupleIsValid(systable_getnext(scan));
+
+ systable_endscan(scan);
+
+ table_close(pg_statext, RowExclusiveLock);
+
+ return found;
+}
+
/*
* ComputeExtStatisticsRows
* Compute number of rows required by extended statistics on a table.
diff --git a/src/include/commands/vacuum.h b/src/include/commands/vacuum.h
index 5b8023616c0..40a0880acd4 100644
--- a/src/include/commands/vacuum.h
+++ b/src/include/commands/vacuum.h
@@ -428,6 +428,8 @@ extern void parallel_vacuum_main(dsm_segment *seg, shm_toc *toc);
extern void analyze_rel(Oid relid, RangeVar *relation,
const VacuumParams *params, List *va_cols, bool in_outer_xact,
BufferAccessStrategy bstrategy);
+extern bool attribute_is_analyzable(Relation onerel, int attnum, Form_pg_attribute attr,
+ int *p_attstattarget);
extern bool std_typanalyze(VacAttrStats *stats);
/* in utils/misc/sampling.c --- duplicate of declarations in utils/sampling.h */
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..ad0107b2549 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,10 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +259,7 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/include/statistics/statistics.h b/src/include/statistics/statistics.h
index 38a56f6ccb3..8f9b9d237fd 100644
--- a/src/include/statistics/statistics.h
+++ b/src/include/statistics/statistics.h
@@ -101,6 +101,7 @@ extern MCVList *statext_mcv_load(Oid mvoid, bool inh);
extern void BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows,
int numrows, HeapTuple *rows,
int natts, VacAttrStats **vacattrstats);
+extern bool HasRelationExtStatistics(Relation onerel);
extern int ComputeExtStatisticsRows(Relation onerel,
int natts, VacAttrStats **vacattrstats);
extern bool statext_is_kind_built(HeapTuple htup, char type);
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-01 18:53 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-04-01 18:53 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> I think that that would be the user's fault, as it's the user's
> responsibility to ensure that the existing stats for the remote table
> are up-to-date. From another perspective, not all users will be able
> to operate in such a way, so I'm thinking of disabling this feature by
> default.
>
I'd like it to remain on by default, and the handling of this edge case can
be made configurable in the future, so I'm fine with it for now.
> > I see that remote_analyze didn't make it as a part of this patch. Is
> that something you'd repackaged as a follow-on patch, or are you just done
> with it?
>
> As just reviewing/polishing the 0001/0002 patches is a lot of work, I
> didn't have time to look at the remote_analyze patch. We are running
> out of time, so I'm afraid that I won't be able to have time for that.
>
Fair enough.
> I modified the patch further:
>
> * Modified postgresImportStatistics to create RemoteAttributeMapping if
> needed.
>
+1
> * The query executed in fetch_relstats is almost the same as the one
> executed in postgresGetAnalyzeInfoForForeignTable. To avoid code
> duplication, I modified it to use the latter query.
+1. That always bothered me.
> * Modified import_spi_query_ok to get the result of an import query by
> using SPI_getbinval, not SPI_getvalue, for efficiency.
+1.
Everything checks out over here.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-02 11:05 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-04-02 11:05 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Thu, Apr 2, 2026 at 3:54 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>> I think that that would be the user's fault, as it's the user's
>> responsibility to ensure that the existing stats for the remote table
>> are up-to-date. From another perspective, not all users will be able
>> to operate in such a way, so I'm thinking of disabling this feature by
>> default.
>
> I'd like it to remain on by default, and the handling of this edge case can be made configurable in the future, so I'm fine with it for now.
The problem is not limited to this special case. Consider cases when
1) the remote table that has many rows are heavily updated after it
got analyzed, and then 2) postgres_fdw imports its stats before it
gets re-analyzed. The stats postgres_fdw imports would be stale,
causing plan degradation. I don't think we should enable this feature
by default until we guarantee stats freshness in some way.
> Everything checks out over here.
Thanks for reviewing!
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-02 17:14 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 2 replies; 89+ messages in thread
From: Corey Huinker @ 2026-04-02 17:14 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> The problem is not limited to this special case. Consider cases when
> 1) the remote table that has many rows are heavily updated after it
> got analyzed, and then 2) postgres_fdw imports its stats before it
> gets re-analyzed. The stats postgres_fdw imports would be stale,
> causing plan degradation. I don't think we should enable this feature
> by default until we guarantee stats freshness in some way.
So it seems like we have the following configurations desired by at least
somebody:
0. Row Sampling Only
1. Fetch stats and fall back to row sampling.
2. Always analyze remote table (assuming it is a table that can hold
stats), then fetch stats, and fall back if necessary.
3. Fetch stats, and if that turned up 0 attribute stats try an analyze,
then try to refetch and if it still fails go to row sampling.
With the following interpretation of reltuples = 0:
a. The table is definitively empty, stop.
b. The table is missing stats and running an analyze is cheap (assuming
remote analysis is even enabled)
c. if remote version >= 14 then a else b
I'm of the opinion that 3c is the best configuration for most tables, and
you have advocated for 1a without an analyze option and 2a with one. Option
2 seems a bit heavy handed to me, but I could see checking the remote
pg_stat_all_tables and making an analyze/no-analyze judgement call based on
that, perhaps call that analyze_stale_vacuum_interval or something like
that. That could be a neat feature for v20, and so whatever default we
choose for fetch_stats, I ask that we choose values that keep our options
open for all 4x3 configurations enumerated above.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-03 13:55 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-04-03 13:55 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Fri, Apr 3, 2026 at 2:14 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>>
>> The problem is not limited to this special case. Consider cases when
>> 1) the remote table that has many rows are heavily updated after it
>> got analyzed, and then 2) postgres_fdw imports its stats before it
>> gets re-analyzed. The stats postgres_fdw imports would be stale,
>> causing plan degradation. I don't think we should enable this feature
>> by default until we guarantee stats freshness in some way.
>
> So it seems like we have the following configurations desired by at least somebody:
>
> 0. Row Sampling Only
> 1. Fetch stats and fall back to row sampling.
> 2. Always analyze remote table (assuming it is a table that can hold stats), then fetch stats, and fall back if necessary.
> 3. Fetch stats, and if that turned up 0 attribute stats try an analyze, then try to refetch and if it still fails go to row sampling.
>
> With the following interpretation of reltuples = 0:
>
> a. The table is definitively empty, stop.
> b. The table is missing stats and running an analyze is cheap (assuming remote analysis is even enabled)
> c. if remote version >= 14 then a else b
>
> I'm of the opinion that 3c is the best configuration for most tables, and you have advocated for 1a without an analyze option and 2a with one. Option 2 seems a bit heavy handed to me, but I could see checking the remote pg_stat_all_tables and making an analyze/no-analyze judgement call based on that, perhaps call that analyze_stale_vacuum_interval or something like that. That could be a neat feature for v20, and so whatever default we choose for fetch_stats, I ask that we choose values that keep our options open for all 4x3 configurations enumerated above.
Before discussing this, let's wrap up the work for v19. Here is a new
version of the patch. Changes are:
* As above, I think we should disable this feature by default for now,
so I modified the patch as such.
* You are defining a remote query per version at the top of the file
that is used in fetch_attstats, but I think that that reduces
readability, making maintenance hard, so I modified that function to
build the query dynamically in it, as I proposed before. I also
modified that function to use PQsendQuery, not PQsendQueryParams, as
in fetch_relstats, for efficiency.
* I moved the code for opening/closing the connection from
postgresImportStatistics to fetch_remote_statistics, as the connection
is only used in the latter function. I also removed useless cleanup
processing in that function.
* I added regression tests.
* I fixed a minor bug I noticed while adding those tests.
* I did some cleanup and editorialization including re-ordering
functions in logical order.
One thing I'm wondering is: we should rename ImportStatistics to
ImportForeignStatistics, for consistency with ImportForeignSchema?
Also, we should rename fetch_stats to import_stats, for consistency
with eg, import_default?
Anyway I think the patch is now in good shape, except comments/docs,
which I will work on next.
Best regards,
Etsuro Fujita
Attachments:
v19-Add-remote-statistics-fetching-to-postgres_fdw.patch (application/octet-stream, 53.5K) download
diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c
index c159ecd1558..2dcc6c8af1b 100644
--- a/contrib/postgres_fdw/deparse.c
+++ b/contrib/postgres_fdw/deparse.c
@@ -2541,8 +2541,8 @@ deparseAnalyzeSizeSql(StringInfo buf, Relation rel)
}
/*
- * Construct SELECT statement to acquire the number of rows and the relkind of
- * a relation.
+ * Construct SELECT statement to acquire the number of pages, the number of
+ * rows, and the relkind of a relation.
*
* Note: we just return the remote server's reltuples value, which might
* be off a good deal, but it doesn't seem worth working harder. See
@@ -2557,7 +2557,7 @@ deparseAnalyzeInfoSql(StringInfo buf, Relation rel)
initStringInfo(&relname);
deparseRelation(&relname, rel);
- appendStringInfoString(buf, "SELECT reltuples, relkind FROM pg_catalog.pg_class WHERE oid = ");
+ appendStringInfoString(buf, "SELECT relpages, reltuples, relkind FROM pg_catalog.pg_class WHERE oid = ");
deparseStringLiteral(buf, relname.data);
appendStringInfoString(buf, "::pg_catalog.regclass");
}
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index ac34a1acacb..3f5fa8a7dd1 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -12727,6 +12727,64 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test for statistics import
+-- ===================================================================
+CREATE TABLE simport_table (c1 int, c2 text);
+CREATE FOREIGN TABLE simport_ftable (c1 int, c2 text, cx int)
+ SERVER loopback OPTIONS (table_name 'simport_table');
+ALTER FOREIGN TABLE simport_ftable ALTER COLUMN cx OPTIONS (ADD column_name 'c1');
+ALTER FOREIGN TABLE simport_ftable OPTIONS (ADD fetch_stats 'true');
+ANALYZE simport_ftable; -- should fail
+WARNING: could not import statistics for foreign table "public.simport_ftable" --- remote table "public.simport_table" has no relation statistics to import
+ANALYZE simport_table;
+ANALYZE VERBOSE simport_ftable; -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+ALTER TABLE simport_table ALTER COLUMN c1 SET STATISTICS 0;
+ALTER TABLE simport_table ALTER COLUMN c2 SET STATISTICS 0;
+INSERT INTO simport_table VALUES (1, 'foo'), (1, 'foo'), (2, 'bar'), (2, 'bar');
+ANALYZE simport_table;
+ANALYZE simport_ftable; -- should fail
+WARNING: could not import statistics for foreign table "public.simport_ftable" --- remote table "public.simport_table" has no attribute statistics to import
+ALTER TABLE simport_table ALTER COLUMN c1 SET STATISTICS DEFAULT;
+ANALYZE simport_table;
+ANALYZE simport_ftable; -- should fail
+WARNING: could not import statistics for foreign table "public.simport_ftable" --- no attribute statistics found for column "c2" of remote table "public.simport_table"
+ALTER TABLE simport_table ALTER COLUMN c2 SET STATISTICS DEFAULT;
+ANALYZE simport_table;
+ANALYZE VERBOSE simport_ftable; -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+ANALYZE VERBOSE simport_ftable (c1); -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+ANALYZE VERBOSE simport_ftable (c2); -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+ANALYZE VERBOSE simport_ftable (c1, cx); -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+ANALYZE VERBOSE simport_ftable (c2, cx); -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+CREATE STATISTICS stats (dependencies) ON c1, c2 FROM simport_ftable;
+ANALYZE simport_ftable; -- should fail
+WARNING: cannot import statistics for foreign table "public.simport_ftable" --- this foreign table has extended statistics objects
+DROP STATISTICS stats;
+ANALYZE simport_ftable (cid); -- should fail
+ERROR: column "cid" of relation "simport_ftable" does not exist
+CREATE VIEW simport_view AS SELECT * FROM simport_table;
+CREATE FOREIGN TABLE simport_fview (c1 int, c2 text)
+ SERVER loopback OPTIONS (table_name 'simport_view');
+ALTER FOREIGN TABLE simport_fview OPTIONS (ADD fetch_stats 'true');
+ANALYZE simport_fview; -- should fail
+WARNING: could not import statistics for foreign table "public.simport_fview" --- remote table "public.simport_view" is of relkind "v" which cannot have statistics
+-- cleanup
+DROP FOREIGN TABLE simport_ftable;
+DROP FOREIGN TABLE simport_fview;
+DROP VIEW simport_view;
+DROP TABLE simport_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..5b7726800d0 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,6 +120,7 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
+ strcmp(def->defname, "fetch_stats") == 0 ||
strcmp(def->defname, "keep_connections") == 0)
{
/* these accept only boolean values */
@@ -278,6 +279,10 @@ InitPgFdwOptions(void)
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
+ /* fetch_stats is available on both server and table */
+ {"fetch_stats", ForeignServerRelationId, false},
+ {"fetch_stats", ForeignTableRelationId, false},
+
/*
* sslcert and sslkey are in fact libpq options, but we repeat them
* here to allow them to appear in both foreign server context (when
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 41e47cc795b..bcb2ab578aa 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -21,8 +21,10 @@
#include "commands/defrem.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
+#include "commands/vacuum.h"
#include "executor/execAsync.h"
#include "executor/instrument.h"
+#include "executor/spi.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -40,6 +42,7 @@
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "postgres_fdw.h"
+#include "statistics/statistics.h"
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
@@ -318,6 +321,23 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+ int server_version_num;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local attnums */
+typedef struct
+{
+ AttrNumber local_attnum;
+ char local_attname[NAMEDATALEN];
+ char remote_attname[NAMEDATALEN];
+ int res_index;
+} RemoteAttributeMapping;
+
/*
* SQL functions
*/
@@ -403,6 +423,9 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresImportStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -508,6 +531,37 @@ static int postgresAcquireSampleRowsFunc(Relation relation, int elevel,
double *totaldeadrows);
static void analyze_row_processor(PGresult *res, int row,
PgFdwAnalyzeState *astate);
+static bool fetch_remote_statistics(Relation relation,
+ List *va_cols,
+ ForeignTable *table,
+ const char *local_schemaname,
+ const char *local_relname,
+ int *p_attrcnt,
+ RemoteAttributeMapping **p_remattrmap,
+ RemoteStatsResults *remstats);
+static PGresult *fetch_relstats(PGconn *conn, Relation relation);
+static PGresult *fetch_attstats(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list);
+static RemoteAttributeMapping *build_remattrmap(Relation relation, List *va_cols,
+ int *p_attrcnt, StringInfo column_list);
+static bool attname_in_list(const char *attname, List *va_cols);
+static int remattrmap_cmp(const void *v1, const void *v2);
+static bool match_attrmap(PGresult *res,
+ const char *local_schemaname,
+ const char *local_relname,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int attrcnt,
+ RemoteAttributeMapping *remattrmap);
+static bool import_fetched_statistics(const char *schemaname,
+ const char *relname,
+ int natts,
+ const RemoteAttributeMapping *remattrmap,
+ RemoteStatsResults *remstats);
+static void map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls);
+static bool import_spi_query_ok(void);
static void produce_tuple_asynchronously(AsyncRequest *areq, bool fetch);
static void fetch_more_data_begin(AsyncRequest *areq);
static void complete_pending_request(AsyncRequest *areq);
@@ -547,6 +601,156 @@ static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_i);
static int get_batch_size_option(Relation rel);
+/* All static relstats queries have the same column order */
+enum RelStatsColumns
+{
+ RELSTATS_RELPAGES = 0,
+ RELSTATS_RELTUPLES,
+ RELSTATS_RELKIND,
+ RELSTATS_NUM_FIELDS,
+};
+
+/* All static attstats queries have the same column order */
+enum AttStatsColumns
+{
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS,
+};
+
+static const char *relimport_sql =
+ "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', $1,\n"
+ "\t'schemaname', $2,\n"
+ "\t'relname', $3,\n"
+ "\t'relpages', $4::integer,\n"
+ "\t'reltuples', $5::real)";
+
+enum RelImportSqlArgs
+{
+ RELIMPORT_SQL_VERSION = 0,
+ RELIMPORT_SQL_SCHEMANAME,
+ RELIMPORT_SQL_RELNAME,
+ RELIMPORT_SQL_RELPAGES,
+ RELIMPORT_SQL_RELTUPLES,
+ RELIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid relimport_argtypes[RELIMPORT_SQL_NUM_FIELDS] =
+{
+ INT4OID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID,
+};
+
+static const char *attimport_sql =
+ "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', $1,\n"
+ "\t'schemaname', $2,\n"
+ "\t'relname', $3,\n"
+ "\t'attnum', $4,\n"
+ "\t'inherited', false::boolean,\n"
+ "\t'null_frac', $5::real,\n"
+ "\t'avg_width', $6::integer,\n"
+ "\t'n_distinct', $7::real,\n"
+ "\t'most_common_vals', $8,\n"
+ "\t'most_common_freqs', $9::real[],\n"
+ "\t'histogram_bounds', $10,\n"
+ "\t'correlation', $11::real,\n"
+ "\t'most_common_elems', $12,\n"
+ "\t'most_common_elem_freqs', $13::real[],\n"
+ "\t'elem_count_histogram', $14::real[],\n"
+ "\t'range_length_histogram', $15,\n"
+ "\t'range_empty_frac', $16::real,\n"
+ "\t'range_bounds_histogram', $17)";
+
+enum AttImportSqlArgs
+{
+ ATTIMPORT_SQL_VERSION = 0,
+ ATTIMPORT_SQL_SCHEMANAME,
+ ATTIMPORT_SQL_RELNAME,
+ ATTIMPORT_SQL_ATTNUM,
+ ATTIMPORT_SQL_NULL_FRAC,
+ ATTIMPORT_SQL_AVG_WIDTH,
+ ATTIMPORT_SQL_N_DISTINCT,
+ ATTIMPORT_SQL_MOST_COMMON_VALS,
+ ATTIMPORT_SQL_MOST_COMMON_FREQS,
+ ATTIMPORT_SQL_HISTOGRAM_BOUNDS,
+ ATTIMPORT_SQL_CORRELATION,
+ ATTIMPORT_SQL_MOST_COMMON_ELEMS,
+ ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS,
+ ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_EMPTY_FRAC,
+ ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM,
+ ATTIMPORT_SQL_NUM_FIELDS
+};
+
+static const Oid attimport_argtypes[ATTIMPORT_SQL_NUM_FIELDS] =
+{
+ INT4OID, TEXTOID, TEXTOID, INT2OID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID,
+};
+
+/* Pairs AttStatsColumns:AttImportSqlArgs Map */
+typedef struct
+{
+ enum AttStatsColumns res_field;
+ enum AttImportSqlArgs arg_num;
+} AttrResultArgMap;
+
+/*
+ * The mapping of attribute stats query columns to the positional arguments in
+ * the prepared pg_restore_attribute_stats() statement.
+ */
+#define NUM_MAPPED_ATTIMPORT_ARGS 13
+static const AttrResultArgMap attr_result_arg_map[NUM_MAPPED_ATTIMPORT_ARGS] =
+{
+ {ATTSTATS_NULL_FRAC, ATTIMPORT_SQL_NULL_FRAC},
+ {ATTSTATS_AVG_WIDTH, ATTIMPORT_SQL_AVG_WIDTH},
+ {ATTSTATS_N_DISTINCT, ATTIMPORT_SQL_N_DISTINCT},
+ {ATTSTATS_MOST_COMMON_VALS, ATTIMPORT_SQL_MOST_COMMON_VALS},
+ {ATTSTATS_MOST_COMMON_FREQS, ATTIMPORT_SQL_MOST_COMMON_FREQS},
+ {ATTSTATS_HISTOGRAM_BOUNDS, ATTIMPORT_SQL_HISTOGRAM_BOUNDS},
+ {ATTSTATS_CORRELATION, ATTIMPORT_SQL_CORRELATION},
+ {ATTSTATS_MOST_COMMON_ELEMS, ATTIMPORT_SQL_MOST_COMMON_ELEMS},
+ {ATTSTATS_MOST_COMMON_ELEM_FREQS, ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS},
+ {ATTSTATS_ELEM_COUNT_HISTOGRAM, ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM},
+ {ATTSTATS_RANGE_LENGTH_HISTOGRAM, ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM},
+ {ATTSTATS_RANGE_EMPTY_FRAC, ATTIMPORT_SQL_RANGE_EMPTY_FRAC},
+ {ATTSTATS_RANGE_BOUNDS_HISTOGRAM, ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM},
+};
+
+static const char *attclear_sql =
+ "SELECT pg_catalog.pg_clear_attribute_stats($1, $2, $3, false)";
+
+enum AttClearSqlArgs
+{
+ ATTCLEAR_SQL_SCHEMANAME = 0,
+ ATTCLEAR_SQL_RELNAME,
+ ATTCLEAR_SQL_ATTNAME,
+ ATTCLEAR_SQL_NUM_FIELDS
+};
+
+static const Oid attclear_argtypes[ATTCLEAR_SQL_NUM_FIELDS] =
+{
+ TEXTOID, TEXTOID, TEXTOID,
+};
+
/*
* Foreign-data wrapper handler function: return a struct with pointers
@@ -596,6 +800,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->ImportStatistics = postgresImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4975,10 +5180,11 @@ postgresGetAnalyzeInfoForForeignTable(Relation relation, bool *can_tablesample)
if (PQresultStatus(res) != PGRES_TUPLES_OK)
pgfdw_report_error(res, conn, sql.data);
- if (PQntuples(res) != 1 || PQnfields(res) != 2)
+ if (PQntuples(res) != 1 || PQnfields(res) != RELSTATS_NUM_FIELDS)
elog(ERROR, "unexpected result from deparseAnalyzeInfoSql query");
- reltuples = strtod(PQgetvalue(res, 0, 0), NULL);
- relkind = *(PQgetvalue(res, 0, 1));
+ /* We don't use relpages here */
+ reltuples = strtod(PQgetvalue(res, 0, RELSTATS_RELTUPLES), NULL);
+ relkind = *(PQgetvalue(res, 0, RELSTATS_RELKIND));
PQclear(res);
ReleaseConnection(conn);
@@ -5367,6 +5573,713 @@ analyze_row_processor(PGresult *res, int row, PgFdwAnalyzeState *astate)
}
}
+/*
+ * postgresImportStatistics
+ * Attempt to fetch remote statistics and apply those instead of analyzing.
+ */
+static bool
+postgresImportStatistics(Relation relation, List *va_cols, int elevel)
+{
+ ForeignTable *table;
+ ForeignServer *server;
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ RemoteStatsResults remstats = {.rel = NULL, .att = NULL};
+ RemoteAttributeMapping *remattrmap = NULL;
+ int attrcnt = 0;
+ bool fetch_stats = false;
+ bool ok = false;
+ ListCell *lc;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ /*
+ * Check whether the fetch_stats option is enabled on the foreign table.
+ * If not, silently ignore the foreign table.
+ *
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "fetch_stats") == 0)
+ {
+ fetch_stats = defGetBoolean(def);
+ break;
+ }
+ }
+ if (!fetch_stats)
+ return false;
+
+ /*
+ * We don't currently support statistics import for foreign tables with
+ * extended statistics objects.
+ */
+ if (HasRelationExtStatistics(relation))
+ {
+ ereport(WARNING,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("cannot import statistics for foreign table \"%s.%s\" --- this foreign table has extended statistics objects",
+ schemaname, relname));
+ return false;
+ }
+
+ /*
+ * OK, let's do it.
+ */
+ ereport(elevel,
+ (errmsg("importing statistics for foreign table \"%s.%s\"",
+ schemaname, relname)));
+
+ ok = fetch_remote_statistics(relation, va_cols,
+ table, schemaname, relname,
+ &attrcnt, &remattrmap, &remstats);
+
+ if (ok)
+ ok = import_fetched_statistics(schemaname, relname,
+ attrcnt, remattrmap, &remstats);
+
+ if (ok)
+ ereport(elevel,
+ (errmsg("finished importing statistics for foreign table \"%s.%s\"",
+ schemaname, relname)));
+
+ PQclear(remstats.rel);
+ PQclear(remstats.att);
+ if (remattrmap)
+ pfree(remattrmap);
+
+ return ok;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static bool
+fetch_remote_statistics(Relation relation,
+ List *va_cols,
+ ForeignTable *table,
+ const char *local_schemaname,
+ const char *local_relname,
+ int *p_attrcnt,
+ RemoteAttributeMapping **p_remattrmap,
+ RemoteStatsResults *remstats)
+{
+ UserMapping *user;
+ PGconn *conn;
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ PGresult *relstats = NULL;
+ PGresult *attstats = NULL;
+ int server_version_num;
+ RemoteAttributeMapping *remattrmap = NULL;
+ int attrcnt = 0;
+ char relkind;
+ double reltuples;
+ bool ok = false;
+ ListCell *lc;
+
+ /*
+ * Assume the remote schema/relation names are the same as the local name
+ * unless the foreign table's options tell us otherwise.
+ */
+ remote_schemaname = local_schemaname;
+ remote_relname = local_relname;
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ }
+
+ /*
+ * Get connection to the foreign server. Connection manager will
+ * establish new connection if necessary.
+ */
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ remstats->server_version_num = server_version_num = PQserverVersion(conn);
+
+ remstats->rel = relstats = fetch_relstats(conn, relation);
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
+ * can't support a foreign table.
+ */
+ relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
+ switch (relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ case RELKIND_PARTITIONED_TABLE:
+ break;
+ default:
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" is of relkind \"%c\" which cannot have statistics",
+ local_schemaname, local_relname,
+ remote_schemaname, remote_relname, relkind));
+ goto fetch_cleanup;
+ }
+
+ /*
+ * If the reltuples value > 0, then then we can expect to find attribute
+ * stats for the table.
+ *
+ * A reltuples value of -1 means the table has never been analyzed (v14+).
+ *
+ * In versions prior to v14, a value of 0 was ambiguous, it could mean
+ * that the table had never been analyzed, or that it was empty at the
+ * time that it was analyzed. Either way, we wouldn't expect to find
+ * attstats for the relation.
+ */
+ reltuples = strtod(PQgetvalue(relstats, 0, RELSTATS_RELTUPLES), NULL);
+ if (((server_version_num < 140000) && (reltuples == 0)) ||
+ ((server_version_num >= 140000) && (reltuples == -1)))
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" has no relation statistics to import",
+ local_schemaname, local_relname,
+ remote_schemaname, remote_relname));
+ goto fetch_cleanup;
+ }
+
+ if (reltuples > 0)
+ {
+ StringInfoData column_list;
+
+ *p_remattrmap = remattrmap = build_remattrmap(relation, va_cols,
+ &attrcnt, &column_list);
+ *p_attrcnt = attrcnt;
+
+ if (attrcnt > 0)
+ {
+ remstats->att = attstats = fetch_attstats(conn,
+ server_version_num,
+ remote_schemaname,
+ remote_relname,
+ column_list.data);
+
+ /* Reject the stats if any are missing or in excess. */
+ if (!match_attrmap(attstats,
+ local_schemaname, local_relname,
+ remote_schemaname, remote_relname,
+ attrcnt, remattrmap))
+ goto fetch_cleanup;
+ }
+ }
+
+ ok = true;
+
+ fetch_cleanup:
+ ReleaseConnection(conn);
+ return ok;
+}
+
+/*
+ * Attempt to fetch remote relations stats.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn, Relation relation)
+{
+ StringInfoData sql;
+ PGresult *res;
+
+ initStringInfo(&sql);
+ deparseAnalyzeInfoSql(&sql, relation);
+
+ res = pgfdw_exec_query(conn, sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, sql.data);
+
+ if (PQntuples(res) != 1 || PQnfields(res) != RELSTATS_NUM_FIELDS)
+ elog(ERROR, "unexpected result from deparseAnalyzeInfoSql query");
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list)
+{
+ StringInfoData sql;
+ PGresult *res;
+
+ initStringInfo(&sql);
+ appendStringInfoString(&sql,
+ "SELECT DISTINCT ON (attname COLLATE \"C\") attname, "
+ "null_frac, "
+ "avg_width, "
+ "n_distinct, "
+ "most_common_vals, "
+ "most_common_freqs, "
+ "histogram_bounds, "
+ "correlation, ");
+
+ /* Elements stats are supported since Postgres 9.2 */
+ if (server_version_num >= 92000)
+ appendStringInfoString(&sql,
+ "most_common_elems, "
+ "most_common_elem_freqs, "
+ "elem_count_histogram, ");
+ else
+ appendStringInfoString(&sql,
+ "NULL, NULL, NULL, ");
+
+ /* Range stats are supported since Postgres 17 */
+ if (server_version_num >= 170000)
+ appendStringInfoString(&sql,
+ "range_length_histogram, "
+ "range_empty_frac, "
+ "range_bounds_histogram ");
+ else
+ appendStringInfoString(&sql,
+ "NULL, NULL, NULL, ");
+
+ appendStringInfoString(&sql,
+ "FROM pg_catalog.pg_stats "
+ "WHERE schemaname = ");
+ deparseStringLiteral(&sql, remote_schemaname);
+ appendStringInfoString(&sql,
+ " AND tablename = ");
+ deparseStringLiteral(&sql, remote_relname);
+ appendStringInfo(&sql,
+ " AND attname = ANY('%s'::text[]) ",
+ column_list);
+
+ /* inherited is supported since Postgres 9.0 */
+ if (server_version_num >= 90000)
+ appendStringInfoString(&sql,
+ "ORDER BY attname COLLATE \"C\", inherited DESC");
+ else
+ appendStringInfoString(&sql,
+ "ORDER BY attname COLLATE \"C\"");
+
+ res = pgfdw_exec_query(conn, sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, sql.data);
+
+ if (PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ return res;
+}
+
+/*
+ * Build local-attnum/remote-attname map and column list.
+ */
+static RemoteAttributeMapping *
+build_remattrmap(Relation relation, List *va_cols,
+ int *p_attrcnt, StringInfo column_list)
+{
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ RemoteAttributeMapping *remattrmap = NULL;
+ int attrcnt = 0;
+
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ initStringInfo(column_list);
+ appendStringInfoChar(column_list, '{');
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+ char *attname = NameStr(attr->attname);
+ AttrNumber attnum = attr->attnum;
+ char *remote_attname;
+ List *fc_options;
+ ListCell *lc;
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ if (!attribute_is_analyzable(relation, attnum, attr, NULL))
+ continue;
+
+ /* If column_name is not specified, go with attname. */
+ remote_attname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+ foreach(lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_attname = defGetString(def);
+ break;
+ }
+ }
+
+ if (attrcnt > 0)
+ appendStringInfoString(column_list, ", ");
+ appendStringInfoString(column_list, quote_identifier(remote_attname));
+
+ remattrmap[attrcnt].local_attnum = attnum;
+ strncpy(remattrmap[attrcnt].local_attname, attname, NAMEDATALEN);
+ strncpy(remattrmap[attrcnt].remote_attname, remote_attname, NAMEDATALEN);
+ remattrmap[attrcnt].res_index = -1;
+ attrcnt++;
+ }
+ appendStringInfoChar(column_list, '}');
+
+ /* Sort mapping by remote attribute name. */
+ if (attrcnt > 1)
+ qsort(remattrmap, attrcnt, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ *p_attrcnt = attrcnt;
+ return remattrmap;
+}
+
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Match local columns to result set rows.
+ *
+ * As the result set consists of the attribute stats for some/all of distinct
+ * mapped remote columns in the RemoteAttributeMapping, every entry in it
+ * should have at most one match in the result set; which is also ordered by
+ * attname, so we find such pairs by doing a merge join.
+ *
+ * Returns true if every entry in it has a match, and false if not.
+ */
+static bool
+match_attrmap(PGresult *res,
+ const char *local_schemaname,
+ const char *local_relname,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int attrcnt,
+ RemoteAttributeMapping *remattrmap)
+{
+ int numrows = PQntuples(res);
+ int row = -1;
+
+ /* No work if there are no stats rows. */
+ if (numrows == 0)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" has no attribute statistics to import",
+ local_schemaname, local_relname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* Scan all entries in the RemoteAttributeMapping. */
+ for (int i = 0; i < attrcnt; i++)
+ {
+ /*
+ * First, check whether the entry matches the current stats row, if it
+ * is set.
+ */
+ if (row >= 0 &&
+ strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) == 0)
+ {
+ remattrmap[i].res_index = row;
+ continue;
+ }
+
+ /*
+ * If we've exhausted all stats rows, it means the stats for the entry
+ * are missing.
+ */
+ if (row >= numrows - 1)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- no attribute statistics found for column \"%s\" of remote table \"%s.%s\"",
+ local_schemaname, local_relname,
+ remattrmap[i].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* Advance to the next stats row. */
+ row += 1;
+
+ /*
+ * If the attname in the entry is less than that in the next stats row,
+ * it means the stats for the entry are missing.
+ */
+ if (strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) < 0)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- no attribute statistics found for column \"%s\" of remote table \"%s.%s\"",
+ local_schemaname, local_relname,
+ remattrmap[i].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* We should not have got a stats row we didn't expect. */
+ if (strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) > 0)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ /* We found a match. */
+ Assert(strcmp(remattrmap[i].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) == 0);
+ remattrmap[i].res_index = row;
+ }
+
+ /* We should have exhausted all stats rows. */
+ if (row < numrows - 1)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ return true;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static bool
+import_fetched_statistics(const char *schemaname,
+ const char *relname,
+ int natts,
+ const RemoteAttributeMapping *remattrmap,
+ RemoteStatsResults *remstats)
+{
+ SPIPlanPtr attimport_plan = NULL;
+ SPIPlanPtr attclear_plan = NULL;
+ Datum values[ATTIMPORT_SQL_NUM_FIELDS];
+ char nulls[ATTIMPORT_SQL_NUM_FIELDS];
+ int spirc;
+ bool ok = false;
+
+ /* Assign all the invariant parameters */
+ values[ATTIMPORT_SQL_VERSION] = Int32GetDatum(remstats->server_version_num);
+ nulls[ATTIMPORT_SQL_VERSION] = ' ';
+
+ values[ATTIMPORT_SQL_SCHEMANAME] = CStringGetTextDatum(schemaname);
+ nulls[ATTIMPORT_SQL_SCHEMANAME] = ' ';
+
+ values[ATTIMPORT_SQL_RELNAME] = CStringGetTextDatum(relname);
+ nulls[ATTIMPORT_SQL_RELNAME] = ' ';
+
+ SPI_connect();
+
+ /*
+ * We import the attribute statistics first, because those are more prone
+ * to errors. This avoids making a modification of pg_class that will just
+ * get rolled back by a failed attribute import.
+ */
+ if (remstats->att != NULL)
+ {
+ Assert(PQnfields(remstats->att) == ATTSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats->att) >= 1);
+
+ attimport_plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+ if (attimport_plan == NULL)
+ elog(ERROR, "failed to prepare attimport_sql query");
+
+ attclear_plan = SPI_prepare(attclear_sql, ATTCLEAR_SQL_NUM_FIELDS,
+ (Oid *) attclear_argtypes);
+ if (attclear_plan == NULL)
+ elog(ERROR, "failed to prepare attclear_sql query");
+
+ nulls[ATTIMPORT_SQL_ATTNUM] = ' ';
+
+ for (int mapidx = 0; mapidx < natts; mapidx++)
+ {
+ int row = remattrmap[mapidx].res_index;
+ Datum *values2 = values + 1;
+ char *nulls2 = nulls + 1;
+
+ /* All mappings should have been assigned a result set row. */
+ Assert(row >= 0);
+
+ /*
+ * Check for user-requested abort.
+ */
+ CHECK_FOR_INTERRUPTS();
+
+ /*
+ * First, clear existing attribute stats.
+ *
+ * We can re-use the values/nulls because the number of parameters
+ * is less and the first two params are the same as the second and
+ * third ones in attimport_sql.
+ */
+ values2[ATTCLEAR_SQL_ATTNAME] =
+ CStringGetTextDatum(remattrmap[mapidx].local_attname);
+
+ spirc = SPI_execute_plan(attclear_plan, values2, nulls2, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute attclear_sql query for column \"%s\" of foreign table \"%s.%s\"",
+ remattrmap[mapidx].local_attname, schemaname, relname);
+
+ values[ATTIMPORT_SQL_ATTNUM] =
+ Int16GetDatum(remattrmap[mapidx].local_attnum);
+
+ /* Loop through all mappable columns to set remaining arguments */
+ for (int i = 0; i < NUM_MAPPED_ATTIMPORT_ARGS; i++)
+ map_field_to_arg(remstats->att, row,
+ attr_result_arg_map[i].res_field,
+ attr_result_arg_map[i].arg_num,
+ values, nulls);
+
+ spirc = SPI_execute_plan(attimport_plan, values, nulls, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute attimport_sql query for column \"%s\" of foreign table \"%s.%s\"",
+ remattrmap[mapidx].local_attname, schemaname, relname);
+
+ if (!import_spi_query_ok())
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- attribute statistics import failed for column \"%s\" of this foreign table",
+ schemaname, relname,
+ remattrmap[mapidx].local_attname));
+ goto import_cleanup;
+ }
+ }
+ }
+
+ /*
+ * Import relstats.
+ *
+ * Import relation stats. We only perform this once, so there is no point
+ * in preparing the statement.
+ *
+ * We can re-use the values/nulls because the number of parameters is less
+ * and the first three params are the same as attimport_sql.
+ */
+ Assert(remstats->rel != NULL);
+ Assert(PQnfields(remstats->rel) == RELSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats->rel) == 1);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELPAGES,
+ RELIMPORT_SQL_RELPAGES, values, nulls);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELTUPLES,
+ RELIMPORT_SQL_RELTUPLES, values, nulls);
+
+ spirc = SPI_execute_with_args(relimport_sql,
+ RELIMPORT_SQL_NUM_FIELDS,
+ (Oid *) relimport_argtypes,
+ values, nulls, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute relimport_sql query for foreign table \"%s.%s\"",
+ schemaname, relname);
+
+ if (!import_spi_query_ok())
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- relation statistics import failed for this foreign table",
+ schemaname, relname));
+ goto import_cleanup;
+ }
+
+ ok = true;
+
+import_cleanup:
+ if (attimport_plan)
+ SPI_freeplan(attimport_plan);
+ if (attclear_plan)
+ SPI_freeplan(attclear_plan);
+ SPI_finish();
+ return ok;
+}
+
+/*
+ * Move a string value from a result set to a Text value of a Datum array.
+ */
+static void
+map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls)
+{
+ if (PQgetisnull(res, row, field))
+ {
+ values[arg] = (Datum) 0;
+ nulls[arg] = 'n';
+ }
+ else
+ {
+ const char *s = PQgetvalue(res, row, field);
+
+ values[arg] = CStringGetTextDatum(s);
+ nulls[arg] = ' ';
+ }
+}
+
+/*
+ * Check the 1x1 result set of a pg_restore_*_stats() command for success.
+ */
+static bool
+import_spi_query_ok(void)
+{
+ TupleDesc tupdesc;
+ Datum dat;
+ bool isnull;
+
+ Assert(SPI_tuptable != NULL);
+ Assert(SPI_processed == 1);
+
+ tupdesc = SPI_tuptable->tupdesc;
+ Assert(tupdesc->natts == 1);
+ Assert(TupleDescAttr(tupdesc, 0)->atttypid == BOOLOID);
+ dat = SPI_getbinval(SPI_tuptable->vals[0], tupdesc, 1, &isnull);
+ Assert(!isnull);
+
+ return DatumGetBool(dat);
+}
+
/*
* Import a foreign schema
*/
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 0e218b29a29..f7ca9613b22 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -4435,6 +4435,68 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test for statistics import
+-- ===================================================================
+
+CREATE TABLE simport_table (c1 int, c2 text);
+CREATE FOREIGN TABLE simport_ftable (c1 int, c2 text, cx int)
+ SERVER loopback OPTIONS (table_name 'simport_table');
+ALTER FOREIGN TABLE simport_ftable ALTER COLUMN cx OPTIONS (ADD column_name 'c1');
+ALTER FOREIGN TABLE simport_ftable OPTIONS (ADD fetch_stats 'true');
+
+ANALYZE simport_ftable; -- should fail
+
+ANALYZE simport_table;
+
+ANALYZE VERBOSE simport_ftable; -- should work
+
+ALTER TABLE simport_table ALTER COLUMN c1 SET STATISTICS 0;
+ALTER TABLE simport_table ALTER COLUMN c2 SET STATISTICS 0;
+INSERT INTO simport_table VALUES (1, 'foo'), (1, 'foo'), (2, 'bar'), (2, 'bar');
+ANALYZE simport_table;
+
+ANALYZE simport_ftable; -- should fail
+
+ALTER TABLE simport_table ALTER COLUMN c1 SET STATISTICS DEFAULT;
+ANALYZE simport_table;
+
+ANALYZE simport_ftable; -- should fail
+
+ALTER TABLE simport_table ALTER COLUMN c2 SET STATISTICS DEFAULT;
+ANALYZE simport_table;
+
+ANALYZE VERBOSE simport_ftable; -- should work
+
+ANALYZE VERBOSE simport_ftable (c1); -- should work
+
+ANALYZE VERBOSE simport_ftable (c2); -- should work
+
+ANALYZE VERBOSE simport_ftable (c1, cx); -- should work
+
+ANALYZE VERBOSE simport_ftable (c2, cx); -- should work
+
+CREATE STATISTICS stats (dependencies) ON c1, c2 FROM simport_ftable;
+
+ANALYZE simport_ftable; -- should fail
+
+DROP STATISTICS stats;
+
+ANALYZE simport_ftable (cid); -- should fail
+
+CREATE VIEW simport_view AS SELECT * FROM simport_table;
+CREATE FOREIGN TABLE simport_fview (c1 int, c2 text)
+ SERVER loopback OPTIONS (table_name 'simport_view');
+ALTER FOREIGN TABLE simport_fview OPTIONS (ADD fetch_stats 'true');
+
+ANALYZE simport_fview; -- should fail
+
+-- cleanup
+DROP FOREIGN TABLE simport_ftable;
+DROP FOREIGN TABLE simport_fview;
+DROP VIEW simport_view;
+DROP TABLE simport_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index de69ddcdebc..d7c0dc8ed14 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,29 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>fetch_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing relation and attribute
+ statistics from the remote table, and if all of the attributes being
+ analyzed have statistics in the remote table, then it will import
+ those statistics directly using
+ <function>pg_restore_relation_stats</function> and
+ <function>pg_restore_attribute_stats</function>. This option is only
+ useful if the remote relation is one that can have regular statistics
+ (tables and materialized views). If the foreign table is a partition
+ of a partitioned table, analyzing the partitioned table will still
+ result in row sampling on the foreign table regardless of this setting,
+ though direct analysis of the foreign table would have attempted to
+ fetch remote statistics first.
+ The default is <literal>true</literal>.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 49a5cdf579c..0c14735d163 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -83,6 +83,7 @@ static void compute_index_stats(Relation onerel, double totalrows,
AnlIndexData *indexdata, int nindexes,
HeapTuple *rows, int numrows,
MemoryContext col_context);
+static void validate_va_cols_list(Relation onerel, List *va_cols);
static VacAttrStats *examine_attribute(Relation onerel, int attnum,
Node *index_expr);
static int acquire_sample_rows(Relation onerel, int elevel,
@@ -114,6 +115,7 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ bool stats_imported = false;
/* Select logging level */
if (params->options & VACOPT_VERBOSE)
@@ -182,6 +184,27 @@ analyze_rel(Oid relid, RangeVar *relation,
return;
}
+ /*
+ * Check the given list of columns
+ */
+ if (va_cols != NIL)
+ validate_va_cols_list(onerel, va_cols);
+
+ /*
+ * Initialize progress reporting before setup for regular/foreign tables.
+ * (For the former, the time spent on it would be negligible, but for the
+ * latter, if FDWs support statistics import or analysis, they'd do some
+ * work that needs the remote access, so the time might be non-negligible.)
+ */
+ pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
+ RelationGetRelid(onerel));
+ if (AmAutoVacuumWorkerProcess())
+ pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
+ PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
+ else
+ pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
+ PROGRESS_ANALYZE_STARTED_BY_MANUAL);
+
/*
* Check that it's of an analyzable relkind, and set up appropriately.
*/
@@ -196,26 +219,33 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
+ if (fdwroutine->ImportStatistics != NULL &&
+ fdwroutine->ImportStatistics(onerel, va_cols, elevel))
+ stats_imported = true;
+ else
{
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ goto out;
+ }
}
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
@@ -232,26 +262,16 @@ analyze_rel(Oid relid, RangeVar *relation,
(errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
RelationGetRelationName(onerel))));
relation_close(onerel, ShareUpdateExclusiveLock);
- return;
+ goto out;
}
- /*
- * OK, let's do it. First, initialize progress reporting.
- */
- pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
- RelationGetRelid(onerel));
- if (AmAutoVacuumWorkerProcess())
- pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
- PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
- else
- pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
- PROGRESS_ANALYZE_STARTED_BY_MANUAL);
-
/*
* Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * tables, which don't contain any rows, and foreign tables that
+ * successfully imported statistics.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ && !stats_imported)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
@@ -270,6 +290,7 @@ analyze_rel(Oid relid, RangeVar *relation,
*/
relation_close(onerel, NoLock);
+out:
pgstat_progress_end_command();
}
@@ -368,16 +389,10 @@ do_analyze_rel(Relation onerel, const VacuumParams *params,
starttime = GetCurrentTimestamp();
/*
- * Determine which columns to analyze
- *
- * Note that system attributes are never analyzed, so we just reject them
- * at the lookup stage. We also reject duplicate column mentions. (We
- * could alternatively ignore duplicates, but analyzing a column twice
- * won't work; we'd end up making a conflicting update in pg_statistic.)
+ * Determine which columns to analyze.
*/
if (va_cols != NIL)
{
- Bitmapset *unique_cols = NULL;
ListCell *le;
vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
@@ -388,18 +403,7 @@ do_analyze_rel(Relation onerel, const VacuumParams *params,
char *col = strVal(lfirst(le));
i = attnameAttNum(onerel, col, false);
- if (i == InvalidAttrNumber)
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_COLUMN),
- errmsg("column \"%s\" of relation \"%s\" does not exist",
- col, RelationGetRelationName(onerel))));
- if (bms_is_member(i, unique_cols))
- ereport(ERROR,
- (errcode(ERRCODE_DUPLICATE_COLUMN),
- errmsg("column \"%s\" of relation \"%s\" appears more than once",
- col, RelationGetRelationName(onerel))));
- unique_cols = bms_add_member(unique_cols, i);
-
+ Assert(i != InvalidAttrNumber);
vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
if (vacattrstats[tcnt] != NULL)
tcnt++;
@@ -1030,6 +1034,40 @@ compute_index_stats(Relation onerel, double totalrows,
MemoryContextDelete(ind_context);
}
+/*
+ * validate_va_cols_list -- validate the columns list given to analyze_rel
+ *
+ * Note that system attributes are never analyzed, so we just reject them at
+ * the lookup stage. We also reject duplicate column mentions. (We could
+ * alternatively ignore duplicates, but analyzing a column twice won't work;
+ * we'd end up making a conflicting update in pg_statistic.)
+ */
+static void
+validate_va_cols_list(Relation onerel, List *va_cols)
+{
+ Bitmapset *unique_cols = NULL;
+ ListCell *le;
+
+ Assert(va_cols != NIL);
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+ int i = attnameAttNum(onerel, col, false);
+
+ if (i == InvalidAttrNumber)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_COLUMN),
+ errmsg("column \"%s\" of relation \"%s\" does not exist",
+ col, RelationGetRelationName(onerel))));
+ if (bms_is_member(i, unique_cols))
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_COLUMN),
+ errmsg("column \"%s\" of relation \"%s\" appears more than once",
+ col, RelationGetRelationName(onerel))));
+ unique_cols = bms_add_member(unique_cols, i);
+ }
+}
+
/*
* examine_attribute -- pre-analysis of a single column
*
@@ -1044,37 +1082,15 @@ examine_attribute(Relation onerel, int attnum, Node *index_expr)
{
Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
int attstattarget;
- HeapTuple atttuple;
- Datum dat;
- bool isnull;
HeapTuple typtuple;
VacAttrStats *stats;
int i;
bool ok;
- /* Never analyze dropped columns */
- if (attr->attisdropped)
- return NULL;
-
- /* Don't analyze virtual generated columns */
- if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
- return NULL;
-
/*
- * Get attstattarget value. Set to -1 if null. (Analyze functions expect
- * -1 to mean use default_statistics_target; see for example
- * std_typanalyze.)
+ * Check if the column is analyzable.
*/
- atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
- if (!HeapTupleIsValid(atttuple))
- elog(ERROR, "cache lookup failed for attribute %d of relation %u",
- attnum, RelationGetRelid(onerel));
- dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
- attstattarget = isnull ? -1 : DatumGetInt16(dat);
- ReleaseSysCache(atttuple);
-
- /* Don't analyze column if user has specified not to */
- if (attstattarget == 0)
+ if (!attribute_is_analyzable(onerel, attnum, attr, &attstattarget))
return NULL;
/*
@@ -1155,6 +1171,45 @@ examine_attribute(Relation onerel, int attnum, Node *index_expr)
return stats;
}
+bool
+attribute_is_analyzable(Relation onerel, int attnum, Form_pg_attribute attr,
+ int *p_attstattarget)
+{
+ int attstattarget;
+ HeapTuple atttuple;
+ Datum dat;
+ bool isnull;
+
+ /* Never analyze dropped columns */
+ if (attr->attisdropped)
+ return false;
+
+ /* Don't analyze virtual generated columns */
+ if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
+ return false;
+
+ /*
+ * Get attstattarget value. Set to -1 if null. (Analyze functions expect
+ * -1 to mean use default_statistics_target; see for example
+ * std_typanalyze.)
+ */
+ atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, RelationGetRelid(onerel));
+ dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ /* Don't analyze column if user has specified not to */
+ if (attstattarget == 0)
+ return false;
+
+ if (p_attstattarget)
+ *p_attstattarget = attstattarget;
+ return true;
+}
+
/*
* Read stream callback returning the next BlockNumber as chosen by the
* BlockSampling algorithm.
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index cb7898b21ee..2b83355d26e 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -246,6 +246,40 @@ BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows,
table_close(pg_stext, RowExclusiveLock);
}
+/*
+ * Test if the given relation has extended statistics objects.
+ */
+bool
+HasRelationExtStatistics(Relation onerel)
+{
+ Relation pg_statext;
+ SysScanDesc scan;
+ ScanKeyData skey;
+ bool found;
+
+ pg_statext = table_open(StatisticExtRelationId, RowExclusiveLock);
+
+ /*
+ * Prepare to scan pg_statistic_ext for entries having stxrelid = this
+ * rel.
+ */
+ ScanKeyInit(&skey,
+ Anum_pg_statistic_ext_stxrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(onerel)));
+
+ scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
+ NULL, 1, &skey);
+
+ found = HeapTupleIsValid(systable_getnext(scan));
+
+ systable_endscan(scan);
+
+ table_close(pg_statext, RowExclusiveLock);
+
+ return found;
+}
+
/*
* ComputeExtStatisticsRows
* Compute number of rows required by extended statistics on a table.
diff --git a/src/include/commands/vacuum.h b/src/include/commands/vacuum.h
index 5b8023616c0..40a0880acd4 100644
--- a/src/include/commands/vacuum.h
+++ b/src/include/commands/vacuum.h
@@ -428,6 +428,8 @@ extern void parallel_vacuum_main(dsm_segment *seg, shm_toc *toc);
extern void analyze_rel(Oid relid, RangeVar *relation,
const VacuumParams *params, List *va_cols, bool in_outer_xact,
BufferAccessStrategy bstrategy);
+extern bool attribute_is_analyzable(Relation onerel, int attnum, Form_pg_attribute attr,
+ int *p_attstattarget);
extern bool std_typanalyze(VacAttrStats *stats);
/* in utils/misc/sampling.c --- duplicate of declarations in utils/sampling.h */
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..ad0107b2549 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,10 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*ImportStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +259,7 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ ImportStatistics_function ImportStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/include/statistics/statistics.h b/src/include/statistics/statistics.h
index 38a56f6ccb3..8f9b9d237fd 100644
--- a/src/include/statistics/statistics.h
+++ b/src/include/statistics/statistics.h
@@ -101,6 +101,7 @@ extern MCVList *statext_mcv_load(Oid mvoid, bool inh);
extern void BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows,
int numrows, HeapTuple *rows,
int natts, VacAttrStats **vacattrstats);
+extern bool HasRelationExtStatistics(Relation onerel);
extern int ComputeExtStatisticsRows(Relation onerel,
int natts, VacAttrStats **vacattrstats);
extern bool statext_is_kind_built(HeapTuple htup, char type);
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-03 16:01 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-04-03 16:01 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> * As above, I think we should disable this feature by default for now,
> so I modified the patch as such.
>
+1 so long as it doesn't paint us into a corner.
> * You are defining a remote query per version at the top of the file
> that is used in fetch_attstats, but I think that that reduces
> readability, making maintenance hard, so I modified that function to
> build the query dynamically in it, as I proposed before. I also
> modified that function to use PQsendQuery, not PQsendQueryParams, as
> in fetch_relstats, for efficiency.
>
No objections. I find full-formed queries more readable, but I'm clearly in
the minority with that opinion.
I'm curious, is the efficiency of PQsendQuery over PQsendQueryParams that
significant?
> * I moved the code for opening/closing the connection from
> postgresImportStatistics to fetch_remote_statistics, as the connection
> is only used in the latter function. I also removed useless cleanup
> processing in that function.
>
+1
> * I added regression tests.
>
+1
> * I fixed a minor bug I noticed while adding those tests.
>
> * I did some cleanup and editorialization including re-ordering
> functions in logical order.
>
This was momentarily confusing as I apply your patch to a separate branch
and then compare whole branches, but it checks out.
> One thing I'm wondering is: we should rename ImportStatistics to
> ImportForeignStatistics, for consistency with ImportForeignSchema?
>
ImportForeignStatistics makes sense to me.
> Also, we should rename fetch_stats to import_stats, for consistency
> with eg, import_default?
>
restore_stats is probably the better name, given that it is calling the
pg_restore_*() functions.
> Anyway I think the patch is now in good shape, except comments/docs,
> which I will work on next.
+1!
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-05 11:05 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-04-05 11:05 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Sat, Apr 4, 2026 at 1:01 AM Corey Huinker <corey.huinker@gmail.com> wrote:
>>
>> * As above, I think we should disable this feature by default for now,
>> so I modified the patch as such.
> +1 so long as it doesn't paint us into a corner.
Given that we can't guarantee the freshness, I think that that's the
only choice.
>> * You are defining a remote query per version at the top of the file
>> that is used in fetch_attstats, but I think that that reduces
>> readability, making maintenance hard, so I modified that function to
>> build the query dynamically in it, as I proposed before. I also
>> modified that function to use PQsendQuery, not PQsendQueryParams, as
>> in fetch_relstats, for efficiency.
> I'm curious, is the efficiency of PQsendQuery over PQsendQueryParams that significant?
No, it isn't, but note that PQsendQuery uses simple query protocol
while PQsendQueryParams uses extended query protocol, and that the
overhead incurred by the former protocol is smaller than that by the
latter protocol, so it's better to use PQsendQuery here.
>> * I fixed a minor bug I noticed while adding those tests.
>>
>> * I did some cleanup and editorialization including re-ordering
>> functions in logical order.
> This was momentarily confusing as I apply your patch to a separate branch and then compare whole branches, but it checks out.
Sorry, but I believe that that makes the code easy to read.
>> One thing I'm wondering is: we should rename ImportStatistics to
>> ImportForeignStatistics, for consistency with ImportForeignSchema?
> ImportForeignStatistics makes sense to me.
Will rename.
>> Also, we should rename fetch_stats to import_stats, for consistency
>> with eg, import_default?
> restore_stats is probably the better name, given that it is calling the pg_restore_*() functions.
That sounds better, so will rename.
Thanks for reviewing!
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-07 10:09 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-04-07 10:09 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Sun, Apr 5, 2026 at 8:05 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
> On Sat, Apr 4, 2026 at 1:01 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> >> One thing I'm wondering is: we should rename ImportStatistics to
> >> ImportForeignStatistics, for consistency with ImportForeignSchema?
>
> > ImportForeignStatistics makes sense to me.
>
> Will rename.
Done.
> >> Also, we should rename fetch_stats to import_stats, for consistency
> >> with eg, import_default?
>
> > restore_stats is probably the better name, given that it is calling the pg_restore_*() functions.
>
> That sounds better, so will rename.
Done.
Here are other changes:
* I removed the implementation details from the docs in
postgres-fdw.sgml, as I think it is overly technical for
postgres-fdw.sgml, which is intended for end users. Also, I added a
note about resorting to sampling if stats import failed, and another
note about the user's responsibility to ensure that remote stats are
up-to-date.
* I added the docs about the new callback routine to fdwhandler.sgml.
* I added/tweaked comments.
* I Added one more test case.
* I did further cleanup and editorialization.
I think the patch is committable, so I will push it if no objections.
(Maybe we could add/improve some more comments, but I think we could
do that later if needed.)
Best regards,
Etsuro Fujita
Attachments:
v20-Add-remote-statistics-fetching-to-postgres_fdw.patch (application/octet-stream, 56.7K) download
diff --git a/contrib/postgres_fdw/deparse.c b/contrib/postgres_fdw/deparse.c
index c159ecd1558..2dcc6c8af1b 100644
--- a/contrib/postgres_fdw/deparse.c
+++ b/contrib/postgres_fdw/deparse.c
@@ -2541,8 +2541,8 @@ deparseAnalyzeSizeSql(StringInfo buf, Relation rel)
}
/*
- * Construct SELECT statement to acquire the number of rows and the relkind of
- * a relation.
+ * Construct SELECT statement to acquire the number of pages, the number of
+ * rows, and the relkind of a relation.
*
* Note: we just return the remote server's reltuples value, which might
* be off a good deal, but it doesn't seem worth working harder. See
@@ -2557,7 +2557,7 @@ deparseAnalyzeInfoSql(StringInfo buf, Relation rel)
initStringInfo(&relname);
deparseRelation(&relname, rel);
- appendStringInfoString(buf, "SELECT reltuples, relkind FROM pg_catalog.pg_class WHERE oid = ");
+ appendStringInfoString(buf, "SELECT relpages, reltuples, relkind FROM pg_catalog.pg_class WHERE oid = ");
deparseStringLiteral(buf, relname.data);
appendStringInfoString(buf, "::pg_catalog.regclass");
}
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index cd22553236f..10e87acabef 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -12863,6 +12863,66 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
-- ===================================================================
+-- test for statistics import
+-- ===================================================================
+CREATE TABLE simport_table (c1 int, c2 text);
+CREATE FOREIGN TABLE simport_ftable (c1 int, c2 text, cx int)
+ SERVER loopback OPTIONS (table_name 'simport_table');
+ALTER FOREIGN TABLE simport_ftable ALTER COLUMN cx OPTIONS (ADD column_name 'c1');
+ALTER FOREIGN TABLE simport_ftable OPTIONS (ADD restore_stats 'true');
+ANALYZE simport_ftable; -- should fail
+WARNING: could not import statistics for foreign table "public.simport_ftable" --- remote table "public.simport_table" has no relation statistics to import
+ANALYZE simport_table;
+ANALYZE VERBOSE simport_ftable; -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+ALTER TABLE simport_table ALTER COLUMN c1 SET STATISTICS 0;
+ALTER TABLE simport_table ALTER COLUMN c2 SET STATISTICS 0;
+INSERT INTO simport_table VALUES (1, 'foo'), (1, 'foo'), (2, 'bar'), (2, 'bar');
+ANALYZE simport_table;
+ANALYZE simport_ftable; -- should fail
+WARNING: could not import statistics for foreign table "public.simport_ftable" --- remote table "public.simport_table" has no attribute statistics to import
+ALTER TABLE simport_table ALTER COLUMN c1 SET STATISTICS DEFAULT;
+ANALYZE simport_table;
+ANALYZE simport_ftable; -- should fail
+WARNING: could not import statistics for foreign table "public.simport_ftable" --- no attribute statistics found for column "c2" of remote table "public.simport_table"
+ALTER TABLE simport_table ALTER COLUMN c2 SET STATISTICS DEFAULT;
+ANALYZE simport_table;
+ANALYZE VERBOSE simport_ftable; -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+ANALYZE VERBOSE simport_ftable (c1); -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+ANALYZE VERBOSE simport_ftable (c2); -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+ANALYZE VERBOSE simport_ftable (c1, cx); -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+ANALYZE VERBOSE simport_ftable (c2, cx); -- should work
+INFO: importing statistics for foreign table "public.simport_ftable"
+INFO: finished importing statistics for foreign table "public.simport_ftable"
+CREATE STATISTICS stats (dependencies) ON c1, c2 FROM simport_ftable;
+ANALYZE simport_ftable; -- should fail
+WARNING: cannot import statistics for foreign table "public.simport_ftable" --- this foreign table has extended statistics objects
+DROP STATISTICS stats;
+ANALYZE simport_ftable (cid); -- should fail
+ERROR: column "cid" of relation "simport_ftable" does not exist
+ANALYZE simport_ftable (c1, c1); -- should fail
+ERROR: column "c1" of relation "simport_ftable" appears more than once
+CREATE VIEW simport_view AS SELECT * FROM simport_table;
+CREATE FOREIGN TABLE simport_fview (c1 int, c2 text)
+ SERVER loopback OPTIONS (table_name 'simport_view');
+ALTER FOREIGN TABLE simport_fview OPTIONS (ADD restore_stats 'true');
+ANALYZE simport_fview; -- should fail
+WARNING: could not import statistics for foreign table "public.simport_fview" --- remote table "public.simport_view" is of relkind "v" which cannot have statistics
+-- cleanup
+DROP FOREIGN TABLE simport_ftable;
+DROP FOREIGN TABLE simport_fview;
+DROP VIEW simport_view;
+DROP TABLE simport_table;
+-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
-- Disable debug_discard_caches in order to manage remote connections
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index b0bd72d1e58..3944aedbacc 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -120,7 +120,8 @@ postgres_fdw_validator(PG_FUNCTION_ARGS)
strcmp(def->defname, "async_capable") == 0 ||
strcmp(def->defname, "parallel_commit") == 0 ||
strcmp(def->defname, "parallel_abort") == 0 ||
- strcmp(def->defname, "keep_connections") == 0)
+ strcmp(def->defname, "keep_connections") == 0 ||
+ strcmp(def->defname, "restore_stats") == 0)
{
/* these accept only boolean values */
(void) defGetBoolean(def);
@@ -274,6 +275,9 @@ InitPgFdwOptions(void)
/* sampling is available on both server and table */
{"analyze_sampling", ForeignServerRelationId, false},
{"analyze_sampling", ForeignTableRelationId, false},
+ /* restore_stats is available on both server and table */
+ {"restore_stats", ForeignServerRelationId, false},
+ {"restore_stats", ForeignTableRelationId, false},
{"use_scram_passthrough", ForeignServerRelationId, false},
{"use_scram_passthrough", UserMappingRelationId, false},
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index cc8ec24c30e..267cd44fa89 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -21,8 +21,10 @@
#include "commands/defrem.h"
#include "commands/explain_format.h"
#include "commands/explain_state.h"
+#include "commands/vacuum.h"
#include "executor/execAsync.h"
#include "executor/instrument.h"
+#include "executor/spi.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
@@ -40,6 +42,7 @@
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "postgres_fdw.h"
+#include "statistics/statistics.h"
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
@@ -318,6 +321,182 @@ typedef struct
List *already_used; /* expressions already dealt with */
} ec_member_foreign_arg;
+/* Result sets that are returned from a foreign statistics scan */
+typedef struct
+{
+ PGresult *rel;
+ PGresult *att;
+ int server_version_num;
+} RemoteStatsResults;
+
+/* Pairs of remote columns with local columns */
+typedef struct
+{
+ AttrNumber local_attnum;
+ char local_attname[NAMEDATALEN];
+ char remote_attname[NAMEDATALEN];
+ int res_index;
+} RemoteAttributeMapping;
+
+/* Column order in relation stats query */
+enum RelStatsColumns
+{
+ RELSTATS_RELPAGES = 0,
+ RELSTATS_RELTUPLES,
+ RELSTATS_RELKIND,
+ RELSTATS_NUM_FIELDS,
+};
+
+/* Column order in attribute stats query */
+enum AttStatsColumns
+{
+ ATTSTATS_ATTNAME = 0,
+ ATTSTATS_NULL_FRAC,
+ ATTSTATS_AVG_WIDTH,
+ ATTSTATS_N_DISTINCT,
+ ATTSTATS_MOST_COMMON_VALS,
+ ATTSTATS_MOST_COMMON_FREQS,
+ ATTSTATS_HISTOGRAM_BOUNDS,
+ ATTSTATS_CORRELATION,
+ ATTSTATS_MOST_COMMON_ELEMS,
+ ATTSTATS_MOST_COMMON_ELEM_FREQS,
+ ATTSTATS_ELEM_COUNT_HISTOGRAM,
+ ATTSTATS_RANGE_LENGTH_HISTOGRAM,
+ ATTSTATS_RANGE_EMPTY_FRAC,
+ ATTSTATS_RANGE_BOUNDS_HISTOGRAM,
+ ATTSTATS_NUM_FIELDS,
+};
+
+/* Relation stats import query */
+static const char *relimport_sql =
+ "SELECT pg_catalog.pg_restore_relation_stats(\n"
+ "\t'version', $1,\n"
+ "\t'schemaname', $2,\n"
+ "\t'relname', $3,\n"
+ "\t'relpages', $4::integer,\n"
+ "\t'reltuples', $5::real)";
+
+/* Argument order in relation stats import query */
+enum RelImportSqlArgs
+{
+ RELIMPORT_SQL_VERSION = 0,
+ RELIMPORT_SQL_SCHEMANAME,
+ RELIMPORT_SQL_RELNAME,
+ RELIMPORT_SQL_RELPAGES,
+ RELIMPORT_SQL_RELTUPLES,
+ RELIMPORT_SQL_NUM_FIELDS
+};
+
+/* Argument types in relation stats import query */
+static const Oid relimport_argtypes[RELIMPORT_SQL_NUM_FIELDS] =
+{
+ INT4OID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID,
+};
+
+/* Attribute stats import query */
+static const char *attimport_sql =
+ "SELECT pg_catalog.pg_restore_attribute_stats(\n"
+ "\t'version', $1,\n"
+ "\t'schemaname', $2,\n"
+ "\t'relname', $3,\n"
+ "\t'attnum', $4,\n"
+ "\t'inherited', false::boolean,\n"
+ "\t'null_frac', $5::real,\n"
+ "\t'avg_width', $6::integer,\n"
+ "\t'n_distinct', $7::real,\n"
+ "\t'most_common_vals', $8,\n"
+ "\t'most_common_freqs', $9::real[],\n"
+ "\t'histogram_bounds', $10,\n"
+ "\t'correlation', $11::real,\n"
+ "\t'most_common_elems', $12,\n"
+ "\t'most_common_elem_freqs', $13::real[],\n"
+ "\t'elem_count_histogram', $14::real[],\n"
+ "\t'range_length_histogram', $15,\n"
+ "\t'range_empty_frac', $16::real,\n"
+ "\t'range_bounds_histogram', $17)";
+
+/* Argument order in attribute stats import query */
+enum AttImportSqlArgs
+{
+ ATTIMPORT_SQL_VERSION = 0,
+ ATTIMPORT_SQL_SCHEMANAME,
+ ATTIMPORT_SQL_RELNAME,
+ ATTIMPORT_SQL_ATTNUM,
+ ATTIMPORT_SQL_NULL_FRAC,
+ ATTIMPORT_SQL_AVG_WIDTH,
+ ATTIMPORT_SQL_N_DISTINCT,
+ ATTIMPORT_SQL_MOST_COMMON_VALS,
+ ATTIMPORT_SQL_MOST_COMMON_FREQS,
+ ATTIMPORT_SQL_HISTOGRAM_BOUNDS,
+ ATTIMPORT_SQL_CORRELATION,
+ ATTIMPORT_SQL_MOST_COMMON_ELEMS,
+ ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS,
+ ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM,
+ ATTIMPORT_SQL_RANGE_EMPTY_FRAC,
+ ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM,
+ ATTIMPORT_SQL_NUM_FIELDS
+};
+
+/* Argument types in attribute stats import query */
+static const Oid attimport_argtypes[ATTIMPORT_SQL_NUM_FIELDS] =
+{
+ INT4OID, TEXTOID, TEXTOID, INT2OID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID, TEXTOID, TEXTOID, TEXTOID,
+ TEXTOID,
+};
+
+/*
+ * The mapping of attribute stats query columns to the positional arguments in
+ * the prepared pg_restore_attribute_stats() statement.
+ */
+typedef struct
+{
+ enum AttStatsColumns res_field;
+ enum AttImportSqlArgs arg_num;
+} AttrResultArgMap;
+
+#define NUM_MAPPED_ATTIMPORT_ARGS 13
+
+static const AttrResultArgMap attr_result_arg_map[NUM_MAPPED_ATTIMPORT_ARGS] =
+{
+ {ATTSTATS_NULL_FRAC, ATTIMPORT_SQL_NULL_FRAC},
+ {ATTSTATS_AVG_WIDTH, ATTIMPORT_SQL_AVG_WIDTH},
+ {ATTSTATS_N_DISTINCT, ATTIMPORT_SQL_N_DISTINCT},
+ {ATTSTATS_MOST_COMMON_VALS, ATTIMPORT_SQL_MOST_COMMON_VALS},
+ {ATTSTATS_MOST_COMMON_FREQS, ATTIMPORT_SQL_MOST_COMMON_FREQS},
+ {ATTSTATS_HISTOGRAM_BOUNDS, ATTIMPORT_SQL_HISTOGRAM_BOUNDS},
+ {ATTSTATS_CORRELATION, ATTIMPORT_SQL_CORRELATION},
+ {ATTSTATS_MOST_COMMON_ELEMS, ATTIMPORT_SQL_MOST_COMMON_ELEMS},
+ {ATTSTATS_MOST_COMMON_ELEM_FREQS, ATTIMPORT_SQL_MOST_COMMON_ELEM_FREQS},
+ {ATTSTATS_ELEM_COUNT_HISTOGRAM, ATTIMPORT_SQL_ELEM_COUNT_HISTOGRAM},
+ {ATTSTATS_RANGE_LENGTH_HISTOGRAM, ATTIMPORT_SQL_RANGE_LENGTH_HISTOGRAM},
+ {ATTSTATS_RANGE_EMPTY_FRAC, ATTIMPORT_SQL_RANGE_EMPTY_FRAC},
+ {ATTSTATS_RANGE_BOUNDS_HISTOGRAM, ATTIMPORT_SQL_RANGE_BOUNDS_HISTOGRAM},
+};
+
+/* Attribute stats clear query */
+static const char *attclear_sql =
+ "SELECT pg_catalog.pg_clear_attribute_stats($1, $2, $3, false)";
+
+/* Argument order in attribute stats clear query */
+enum AttClearSqlArgs
+{
+ ATTCLEAR_SQL_SCHEMANAME = 0,
+ ATTCLEAR_SQL_RELNAME,
+ ATTCLEAR_SQL_ATTNAME,
+ ATTCLEAR_SQL_NUM_FIELDS
+};
+
+/* Argument types in attribute stats clear query */
+static const Oid attclear_argtypes[ATTCLEAR_SQL_NUM_FIELDS] =
+{
+ TEXTOID, TEXTOID, TEXTOID,
+};
+
/*
* SQL functions
*/
@@ -403,6 +582,9 @@ static void postgresExecForeignTruncate(List *rels,
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+static bool postgresImportForeignStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void postgresGetForeignJoinPaths(PlannerInfo *root,
@@ -508,6 +690,37 @@ static int postgresAcquireSampleRowsFunc(Relation relation, int elevel,
double *totaldeadrows);
static void analyze_row_processor(PGresult *res, int row,
PgFdwAnalyzeState *astate);
+static bool fetch_remote_statistics(Relation relation,
+ List *va_cols,
+ ForeignTable *table,
+ const char *local_schemaname,
+ const char *local_relname,
+ int *p_attrcnt,
+ RemoteAttributeMapping **p_remattrmap,
+ RemoteStatsResults *remstats);
+static PGresult *fetch_relstats(PGconn *conn, Relation relation);
+static PGresult *fetch_attstats(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list);
+static RemoteAttributeMapping *build_remattrmap(Relation relation, List *va_cols,
+ int *p_attrcnt, StringInfo column_list);
+static bool attname_in_list(const char *attname, List *va_cols);
+static int remattrmap_cmp(const void *v1, const void *v2);
+static bool match_attrmap(PGresult *res,
+ const char *local_schemaname,
+ const char *local_relname,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int attrcnt,
+ RemoteAttributeMapping *remattrmap);
+static bool import_fetched_statistics(const char *schemaname,
+ const char *relname,
+ int attrcnt,
+ const RemoteAttributeMapping *remattrmap,
+ RemoteStatsResults *remstats);
+static void map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls);
+static bool import_spi_query_ok(void);
static void produce_tuple_asynchronously(AsyncRequest *areq, bool fetch);
static void fetch_more_data_begin(AsyncRequest *areq);
static void complete_pending_request(AsyncRequest *areq);
@@ -596,6 +809,7 @@ postgres_fdw_handler(PG_FUNCTION_ARGS)
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
+ routine->ImportForeignStatistics = postgresImportForeignStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = postgresImportForeignSchema;
@@ -4975,10 +5189,11 @@ postgresGetAnalyzeInfoForForeignTable(Relation relation, bool *can_tablesample)
if (PQresultStatus(res) != PGRES_TUPLES_OK)
pgfdw_report_error(res, conn, sql.data);
- if (PQntuples(res) != 1 || PQnfields(res) != 2)
+ if (PQntuples(res) != 1 || PQnfields(res) != RELSTATS_NUM_FIELDS)
elog(ERROR, "unexpected result from deparseAnalyzeInfoSql query");
- reltuples = strtod(PQgetvalue(res, 0, 0), NULL);
- relkind = *(PQgetvalue(res, 0, 1));
+ /* We don't use relpages here */
+ reltuples = strtod(PQgetvalue(res, 0, RELSTATS_RELTUPLES), NULL);
+ relkind = *(PQgetvalue(res, 0, RELSTATS_RELKIND));
PQclear(res);
ReleaseConnection(conn);
@@ -5367,6 +5582,719 @@ analyze_row_processor(PGresult *res, int row, PgFdwAnalyzeState *astate)
}
}
+/*
+ * postgresImportForeignStatistics
+ * Attempt to fetch/restore remote statistics instead of sampling.
+ */
+static bool
+postgresImportForeignStatistics(Relation relation, List *va_cols, int elevel)
+{
+ const char *schemaname = NULL;
+ const char *relname = NULL;
+ ForeignTable *table;
+ ForeignServer *server;
+ RemoteStatsResults remstats = {.rel = NULL, .att = NULL};
+ RemoteAttributeMapping *remattrmap = NULL;
+ int attrcnt = 0;
+ bool restore_stats = false;
+ bool ok = false;
+ ListCell *lc;
+
+ table = GetForeignTable(RelationGetRelid(relation));
+ server = GetForeignServer(table->serverid);
+ schemaname = get_namespace_name(RelationGetNamespace(relation));
+ relname = RelationGetRelationName(relation);
+
+ /*
+ * Check whether the restore_stats option is enabled on the foreign table.
+ * If not, silently ignore the foreign table.
+ *
+ * Server-level options can be overridden by table-level options, so check
+ * server-level first.
+ */
+ foreach(lc, server->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "restore_stats") == 0)
+ {
+ restore_stats = defGetBoolean(def);
+ break;
+ }
+ }
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "restore_stats") == 0)
+ {
+ restore_stats = defGetBoolean(def);
+ break;
+ }
+ }
+ if (!restore_stats)
+ return false;
+
+ /*
+ * We don't currently support statistics import for foreign tables with
+ * extended statistics objects.
+ */
+ if (HasRelationExtStatistics(relation))
+ {
+ ereport(WARNING,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("cannot import statistics for foreign table \"%s.%s\" --- this foreign table has extended statistics objects",
+ schemaname, relname));
+ return false;
+ }
+
+ /*
+ * OK, let's do it.
+ */
+ ereport(elevel,
+ (errmsg("importing statistics for foreign table \"%s.%s\"",
+ schemaname, relname)));
+
+ ok = fetch_remote_statistics(relation, va_cols,
+ table, schemaname, relname,
+ &attrcnt, &remattrmap, &remstats);
+
+ if (ok)
+ ok = import_fetched_statistics(schemaname, relname,
+ attrcnt, remattrmap, &remstats);
+
+ if (ok)
+ ereport(elevel,
+ (errmsg("finished importing statistics for foreign table \"%s.%s\"",
+ schemaname, relname)));
+
+ PQclear(remstats.rel);
+ PQclear(remstats.att);
+ if (remattrmap)
+ pfree(remattrmap);
+
+ return ok;
+}
+
+/*
+ * Attempt to fetch statistics from a remote server.
+ */
+static bool
+fetch_remote_statistics(Relation relation,
+ List *va_cols,
+ ForeignTable *table,
+ const char *local_schemaname,
+ const char *local_relname,
+ int *p_attrcnt,
+ RemoteAttributeMapping **p_remattrmap,
+ RemoteStatsResults *remstats)
+{
+ const char *remote_schemaname = NULL;
+ const char *remote_relname = NULL;
+ UserMapping *user;
+ PGconn *conn;
+ PGresult *relstats = NULL;
+ PGresult *attstats = NULL;
+ int server_version_num;
+ RemoteAttributeMapping *remattrmap = NULL;
+ int attrcnt = 0;
+ char relkind;
+ double reltuples;
+ bool ok = false;
+ ListCell *lc;
+
+ /*
+ * Assume the remote schema/relation names are the same as the local name
+ * unless the foreign table's options tell us otherwise.
+ */
+ remote_schemaname = local_schemaname;
+ remote_relname = local_relname;
+ foreach(lc, table->options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "schema_name") == 0)
+ remote_schemaname = defGetString(def);
+ else if (strcmp(def->defname, "table_name") == 0)
+ remote_relname = defGetString(def);
+ }
+
+ /*
+ * Get connection to the foreign server. Connection manager will
+ * establish new connection if necessary.
+ */
+ user = GetUserMapping(GetUserId(), table->serverid);
+ conn = GetConnection(user, false, NULL);
+ remstats->server_version_num = server_version_num = PQserverVersion(conn);
+
+ /* Fetch relation stats. */
+ remstats->rel = relstats = fetch_relstats(conn, relation);
+
+ /*
+ * Verify that the remote table is the sort that can have meaningful stats
+ * in pg_stats.
+ *
+ * Note that while relations of kinds RELKIND_INDEX and
+ * RELKIND_PARTITIONED_INDEX can have rows in pg_stats, they obviously
+ * can't support a foreign table.
+ */
+ relkind = *PQgetvalue(relstats, 0, RELSTATS_RELKIND);
+ switch (relkind)
+ {
+ case RELKIND_RELATION:
+ case RELKIND_FOREIGN_TABLE:
+ case RELKIND_MATVIEW:
+ case RELKIND_PARTITIONED_TABLE:
+ break;
+ default:
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" is of relkind \"%c\" which cannot have statistics",
+ local_schemaname, local_relname,
+ remote_schemaname, remote_relname, relkind));
+ goto fetch_cleanup;
+ }
+
+ /*
+ * If the reltuples value > 0, then then we can expect to find attribute
+ * stats for the remote table.
+ *
+ * In v14 or latter, if a reltuples value is -1, it means the table has
+ * never been analyzed, so we wouldn't expect to find the stats for the
+ * table; fallback to sampling in that case. If the value is 0, it means
+ * it was empty; in which case skip the stats and import relation stats
+ * only.
+ *
+ * In versions prior to v14, a value of 0 was ambiguous; it could mean
+ * that the table had never been analyzed, or that it was empty. Either
+ * way, we wouldn't expect to find the stats for the table, so we fallback
+ * to sampling.
+ */
+ reltuples = strtod(PQgetvalue(relstats, 0, RELSTATS_RELTUPLES), NULL);
+ if (((server_version_num < 140000) && (reltuples == 0)) ||
+ ((server_version_num >= 140000) && (reltuples == -1)))
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" has no relation statistics to import",
+ local_schemaname, local_relname,
+ remote_schemaname, remote_relname));
+ goto fetch_cleanup;
+ }
+
+
+ if (reltuples > 0)
+ {
+ StringInfoData column_list;
+
+ *p_remattrmap = remattrmap = build_remattrmap(relation, va_cols,
+ &attrcnt, &column_list);
+ *p_attrcnt = attrcnt;
+
+ if (attrcnt > 0)
+ {
+ /* Fetch attribute stats. */
+ remstats->att = attstats = fetch_attstats(conn,
+ server_version_num,
+ remote_schemaname,
+ remote_relname,
+ column_list.data);
+
+ /* If any attribute statsare missing, fallback to sampling. */
+ if (!match_attrmap(attstats,
+ local_schemaname, local_relname,
+ remote_schemaname, remote_relname,
+ attrcnt, remattrmap))
+ goto fetch_cleanup;
+ }
+ }
+
+ ok = true;
+
+ fetch_cleanup:
+ ReleaseConnection(conn);
+ return ok;
+}
+
+/*
+ * Attempt to fetch remote relation stats.
+ */
+static PGresult *
+fetch_relstats(PGconn *conn, Relation relation)
+{
+ StringInfoData sql;
+ PGresult *res;
+
+ initStringInfo(&sql);
+ deparseAnalyzeInfoSql(&sql, relation);
+
+ res = pgfdw_exec_query(conn, sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, sql.data);
+
+ if (PQntuples(res) != 1 || PQnfields(res) != RELSTATS_NUM_FIELDS)
+ elog(ERROR, "unexpected result from deparseAnalyzeInfoSql query");
+
+ return res;
+}
+
+/*
+ * Attempt to fetch remote attribute stats.
+ */
+static PGresult *
+fetch_attstats(PGconn *conn, int server_version_num,
+ const char *remote_schemaname, const char *remote_relname,
+ const char *column_list)
+{
+ StringInfoData sql;
+ PGresult *res;
+
+ initStringInfo(&sql);
+ appendStringInfoString(&sql,
+ "SELECT DISTINCT ON (attname COLLATE \"C\") attname,"
+ " null_frac,"
+ " avg_width,"
+ " n_distinct,"
+ " most_common_vals,"
+ " most_common_freqs,"
+ " histogram_bounds,"
+ " correlation,");
+
+ /* Elements stats are supported since Postgres 9.2 */
+ if (server_version_num >= 92000)
+ appendStringInfoString(&sql,
+ " most_common_elems,"
+ " most_common_elem_freqs,"
+ " elem_count_histogram,");
+ else
+ appendStringInfoString(&sql,
+ " NULL, NULL, NULL,");
+
+ /* Range stats are supported since Postgres 17 */
+ if (server_version_num >= 170000)
+ appendStringInfoString(&sql,
+ " range_length_histogram,"
+ " range_empty_frac,"
+ " range_bounds_histogram");
+ else
+ appendStringInfoString(&sql,
+ " NULL, NULL, NULL,");
+
+ appendStringInfoString(&sql,
+ " FROM pg_catalog.pg_stats"
+ " WHERE schemaname = ");
+ deparseStringLiteral(&sql, remote_schemaname);
+ appendStringInfoString(&sql,
+ " AND tablename = ");
+ deparseStringLiteral(&sql, remote_relname);
+ appendStringInfo(&sql,
+ " AND attname = ANY('%s'::text[])",
+ column_list);
+
+ /* inherited is supported since Postgres 9.0 */
+ if (server_version_num >= 90000)
+ appendStringInfoString(&sql,
+ " ORDER BY attname COLLATE \"C\", inherited DESC");
+ else
+ appendStringInfoString(&sql,
+ " ORDER BY attname COLLATE \"C\"");
+
+ res = pgfdw_exec_query(conn, sql.data, NULL);
+ if (PQresultStatus(res) != PGRES_TUPLES_OK)
+ pgfdw_report_error(res, conn, sql.data);
+
+ if (PQnfields(res) != ATTSTATS_NUM_FIELDS)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ return res;
+}
+
+/*
+ * Build the mapping of local columns to remote columns and create a column
+ * list used for constructing the fetch_attstats query.
+ */
+static RemoteAttributeMapping *
+build_remattrmap(Relation relation, List *va_cols,
+ int *p_attrcnt, StringInfo column_list)
+{
+ TupleDesc tupdesc = RelationGetDescr(relation);
+ RemoteAttributeMapping *remattrmap = NULL;
+ int attrcnt = 0;
+
+ remattrmap = palloc_array(RemoteAttributeMapping, tupdesc->natts);
+ initStringInfo(column_list);
+ appendStringInfoChar(column_list, '{');
+ for (int i = 0; i < tupdesc->natts; i++)
+ {
+ Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+ char *attname = NameStr(attr->attname);
+ AttrNumber attnum = attr->attnum;
+ char *remote_attname;
+ List *fc_options;
+ ListCell *lc;
+
+ /* If a list is specified, exclude any attnames not in it. */
+ if (!attname_in_list(attname, va_cols))
+ continue;
+
+ if (!attribute_is_analyzable(relation, attnum, attr, NULL))
+ continue;
+
+ /* If the column_name option is not specified, go with attname. */
+ remote_attname = attname;
+ fc_options = GetForeignColumnOptions(RelationGetRelid(relation), attnum);
+ foreach(lc, fc_options)
+ {
+ DefElem *def = (DefElem *) lfirst(lc);
+
+ if (strcmp(def->defname, "column_name") == 0)
+ {
+ remote_attname = defGetString(def);
+ break;
+ }
+ }
+
+ if (attrcnt > 0)
+ appendStringInfoString(column_list, ", ");
+ appendStringInfoString(column_list, quote_identifier(remote_attname));
+
+ remattrmap[attrcnt].local_attnum = attnum;
+ strncpy(remattrmap[attrcnt].local_attname, attname, NAMEDATALEN);
+ strncpy(remattrmap[attrcnt].remote_attname, remote_attname, NAMEDATALEN);
+ remattrmap[attrcnt].res_index = -1;
+ attrcnt++;
+ }
+ appendStringInfoChar(column_list, '}');
+
+ /* Sort mapping by remote attribute name if needed. */
+ if (attrcnt > 1)
+ qsort(remattrmap, attrcnt, sizeof(RemoteAttributeMapping), remattrmap_cmp);
+
+ *p_attrcnt = attrcnt;
+ return remattrmap;
+}
+
+/*
+ * Test if an attribute name is in the list.
+ *
+ * An empty list means that all attribute names are in the list.
+ */
+static bool
+attname_in_list(const char *attname, List *va_cols)
+{
+ ListCell *le;
+
+ if (va_cols == NIL)
+ return true;
+
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+
+ if (strcmp(attname, col) == 0)
+ return true;
+ }
+ return false;
+}
+
+/*
+ * Compare two RemoteAttributeMappings for sorting.
+ */
+static int
+remattrmap_cmp(const void *v1, const void *v2)
+{
+ const RemoteAttributeMapping *r1 = v1;
+ const RemoteAttributeMapping *r2 = v2;
+
+ return strncmp(r1->remote_attname, r2->remote_attname, NAMEDATALEN);
+}
+
+/*
+ * Match local columns to result set rows.
+ *
+ * As the result set consists of the attribute stats for some/all of distinct
+ * mapped remote columns in the RemoteAttributeMapping, every entry in it
+ * should have at most one match in the result set; which is also ordered by
+ * attname, so we find such pairs by doing a merge join.
+ *
+ * Returns true if every entry in it has a match, and false if not.
+ */
+static bool
+match_attrmap(PGresult *res,
+ const char *local_schemaname,
+ const char *local_relname,
+ const char *remote_schemaname,
+ const char *remote_relname,
+ int attrcnt,
+ RemoteAttributeMapping *remattrmap)
+{
+ int numrows = PQntuples(res);
+ int row = -1;
+
+ /* No work if there are no stats rows. */
+ if (numrows == 0)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- remote table \"%s.%s\" has no attribute statistics to import",
+ local_schemaname, local_relname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* Scan all entries in the RemoteAttributeMapping. */
+ for (int mapidx = 0; mapidx < attrcnt; mapidx++)
+ {
+ /*
+ * First, check whether the entry matches the current stats row, if it
+ * is set.
+ */
+ if (row >= 0 &&
+ strcmp(remattrmap[mapidx].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) == 0)
+ {
+ remattrmap[mapidx].res_index = row;
+ continue;
+ }
+
+ /*
+ * If we've exhausted all stats rows, it means the stats for the entry
+ * are missing.
+ */
+ if (row >= numrows - 1)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- no attribute statistics found for column \"%s\" of remote table \"%s.%s\"",
+ local_schemaname, local_relname,
+ remattrmap[mapidx].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* Advance to the next stats row. */
+ row += 1;
+
+ /*
+ * If the attname in the entry is less than that in the next stats row,
+ * it means the stats for the entry are missing.
+ */
+ if (strcmp(remattrmap[mapidx].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) < 0)
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- no attribute statistics found for column \"%s\" of remote table \"%s.%s\"",
+ local_schemaname, local_relname,
+ remattrmap[mapidx].remote_attname,
+ remote_schemaname, remote_relname));
+ return false;
+ }
+
+ /* We should not have got a stats row we didn't expect. */
+ if (strcmp(remattrmap[mapidx].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) > 0)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ /* We found a match. */
+ Assert(strcmp(remattrmap[mapidx].remote_attname,
+ PQgetvalue(res, row, ATTSTATS_ATTNAME)) == 0);
+ remattrmap[mapidx].res_index = row;
+ }
+
+ /* We should have exhausted all stats rows. */
+ if (row < numrows - 1)
+ elog(ERROR, "unexpected result from fetch_attstats query");
+
+ return true;
+}
+
+/*
+ * Import fetched statistics into the local statistics tables.
+ */
+static bool
+import_fetched_statistics(const char *schemaname,
+ const char *relname,
+ int attrcnt,
+ const RemoteAttributeMapping *remattrmap,
+ RemoteStatsResults *remstats)
+{
+ SPIPlanPtr attimport_plan = NULL;
+ SPIPlanPtr attclear_plan = NULL;
+ Datum values[ATTIMPORT_SQL_NUM_FIELDS];
+ char nulls[ATTIMPORT_SQL_NUM_FIELDS];
+ int spirc;
+ bool ok = false;
+
+ /* Assign all the invariant parameters common to relation/attribute stats */
+ values[ATTIMPORT_SQL_VERSION] = Int32GetDatum(remstats->server_version_num);
+ nulls[ATTIMPORT_SQL_VERSION] = ' ';
+
+ values[ATTIMPORT_SQL_SCHEMANAME] = CStringGetTextDatum(schemaname);
+ nulls[ATTIMPORT_SQL_SCHEMANAME] = ' ';
+
+ values[ATTIMPORT_SQL_RELNAME] = CStringGetTextDatum(relname);
+ nulls[ATTIMPORT_SQL_RELNAME] = ' ';
+
+ SPI_connect();
+
+ /*
+ * We import attribute statistics first, if any, because those are more
+ * prone to errors. This avoids making a modification of pg_class that
+ * will just get rolled back by a failed attribute import.
+ */
+ if (remstats->att != NULL)
+ {
+ Assert(PQnfields(remstats->att) == ATTSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats->att) >= 1);
+
+ attimport_plan = SPI_prepare(attimport_sql, ATTIMPORT_SQL_NUM_FIELDS,
+ (Oid *) attimport_argtypes);
+ if (attimport_plan == NULL)
+ elog(ERROR, "failed to prepare attimport_sql query");
+
+ attclear_plan = SPI_prepare(attclear_sql, ATTCLEAR_SQL_NUM_FIELDS,
+ (Oid *) attclear_argtypes);
+ if (attclear_plan == NULL)
+ elog(ERROR, "failed to prepare attclear_sql query");
+
+ nulls[ATTIMPORT_SQL_ATTNUM] = ' ';
+
+ for (int mapidx = 0; mapidx < attrcnt; mapidx++)
+ {
+ int row = remattrmap[mapidx].res_index;
+ Datum *values2 = values + 1;
+ char *nulls2 = nulls + 1;
+
+ /* All mappings should have been assigned a result set row. */
+ Assert(row >= 0);
+
+ /*
+ * Check for user-requested abort.
+ */
+ CHECK_FOR_INTERRUPTS();
+
+ /*
+ * First, clear existing attribute stats.
+ *
+ * We can re-use the values/nulls because the number of parameters
+ * is less and the first two params are the same as the second and
+ * third ones in attimport_sql.
+ */
+ values2[ATTCLEAR_SQL_ATTNAME] =
+ CStringGetTextDatum(remattrmap[mapidx].local_attname);
+
+ spirc = SPI_execute_plan(attclear_plan, values2, nulls2, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute attclear_sql query for column \"%s\" of foreign table \"%s.%s\"",
+ remattrmap[mapidx].local_attname, schemaname, relname);
+
+ values[ATTIMPORT_SQL_ATTNUM] =
+ Int16GetDatum(remattrmap[mapidx].local_attnum);
+
+ /* Loop through all mappable columns to set remaining arguments */
+ for (int i = 0; i < NUM_MAPPED_ATTIMPORT_ARGS; i++)
+ map_field_to_arg(remstats->att, row,
+ attr_result_arg_map[i].res_field,
+ attr_result_arg_map[i].arg_num,
+ values, nulls);
+
+ spirc = SPI_execute_plan(attimport_plan, values, nulls, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute attimport_sql query for column \"%s\" of foreign table \"%s.%s\"",
+ remattrmap[mapidx].local_attname, schemaname, relname);
+
+ if (!import_spi_query_ok())
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- attribute statistics import failed for column \"%s\" of this foreign table",
+ schemaname, relname,
+ remattrmap[mapidx].local_attname));
+ goto import_cleanup;
+ }
+ }
+ }
+
+ /*
+ * Import relation stats. We only perform this once, so there is no point
+ * in preparing the statement.
+ *
+ * We can re-use the values/nulls because the number of parameters is less
+ * and the first three params are the same as attimport_sql.
+ */
+ Assert(remstats->rel != NULL);
+ Assert(PQnfields(remstats->rel) == RELSTATS_NUM_FIELDS);
+ Assert(PQntuples(remstats->rel) == 1);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELPAGES,
+ RELIMPORT_SQL_RELPAGES, values, nulls);
+ map_field_to_arg(remstats->rel, 0, RELSTATS_RELTUPLES,
+ RELIMPORT_SQL_RELTUPLES, values, nulls);
+
+ spirc = SPI_execute_with_args(relimport_sql,
+ RELIMPORT_SQL_NUM_FIELDS,
+ (Oid *) relimport_argtypes,
+ values, nulls, false, 1);
+ if (spirc != SPI_OK_SELECT)
+ elog(ERROR, "failed to execute relimport_sql query for foreign table \"%s.%s\"",
+ schemaname, relname);
+
+ if (!import_spi_query_ok())
+ {
+ ereport(WARNING,
+ errmsg("could not import statistics for foreign table \"%s.%s\" --- relation statistics import failed for this foreign table",
+ schemaname, relname));
+ goto import_cleanup;
+ }
+
+ ok = true;
+
+import_cleanup:
+ if (attimport_plan)
+ SPI_freeplan(attimport_plan);
+ if (attclear_plan)
+ SPI_freeplan(attclear_plan);
+ SPI_finish();
+ return ok;
+}
+
+/*
+ * Move a string value from a result set to a Text value of a Datum array.
+ */
+static void
+map_field_to_arg(PGresult *res, int row, int field,
+ int arg, Datum *values, char *nulls)
+{
+ if (PQgetisnull(res, row, field))
+ {
+ values[arg] = (Datum) 0;
+ nulls[arg] = 'n';
+ }
+ else
+ {
+ const char *s = PQgetvalue(res, row, field);
+
+ values[arg] = CStringGetTextDatum(s);
+ nulls[arg] = ' ';
+ }
+}
+
+/*
+ * Check the 1x1 result set of a pg_restore_*_stats() command for success.
+ */
+static bool
+import_spi_query_ok(void)
+{
+ TupleDesc tupdesc;
+ Datum dat;
+ bool isnull;
+
+ Assert(SPI_tuptable != NULL);
+ Assert(SPI_processed == 1);
+
+ tupdesc = SPI_tuptable->tupdesc;
+ Assert(tupdesc->natts == 1);
+ Assert(TupleDescAttr(tupdesc, 0)->atttypid == BOOLOID);
+ dat = SPI_getbinval(SPI_tuptable->vals[0], tupdesc, 1, &isnull);
+ Assert(!isnull);
+
+ return DatumGetBool(dat);
+}
+
/*
* Import a foreign schema
*/
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 59963e298b8..79ad5be8bf9 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -4515,6 +4515,70 @@ ANALYZE analyze_ftable;
DROP FOREIGN TABLE analyze_ftable;
DROP TABLE analyze_table;
+-- ===================================================================
+-- test for statistics import
+-- ===================================================================
+
+CREATE TABLE simport_table (c1 int, c2 text);
+CREATE FOREIGN TABLE simport_ftable (c1 int, c2 text, cx int)
+ SERVER loopback OPTIONS (table_name 'simport_table');
+ALTER FOREIGN TABLE simport_ftable ALTER COLUMN cx OPTIONS (ADD column_name 'c1');
+ALTER FOREIGN TABLE simport_ftable OPTIONS (ADD restore_stats 'true');
+
+ANALYZE simport_ftable; -- should fail
+
+ANALYZE simport_table;
+
+ANALYZE VERBOSE simport_ftable; -- should work
+
+ALTER TABLE simport_table ALTER COLUMN c1 SET STATISTICS 0;
+ALTER TABLE simport_table ALTER COLUMN c2 SET STATISTICS 0;
+INSERT INTO simport_table VALUES (1, 'foo'), (1, 'foo'), (2, 'bar'), (2, 'bar');
+ANALYZE simport_table;
+
+ANALYZE simport_ftable; -- should fail
+
+ALTER TABLE simport_table ALTER COLUMN c1 SET STATISTICS DEFAULT;
+ANALYZE simport_table;
+
+ANALYZE simport_ftable; -- should fail
+
+ALTER TABLE simport_table ALTER COLUMN c2 SET STATISTICS DEFAULT;
+ANALYZE simport_table;
+
+ANALYZE VERBOSE simport_ftable; -- should work
+
+ANALYZE VERBOSE simport_ftable (c1); -- should work
+
+ANALYZE VERBOSE simport_ftable (c2); -- should work
+
+ANALYZE VERBOSE simport_ftable (c1, cx); -- should work
+
+ANALYZE VERBOSE simport_ftable (c2, cx); -- should work
+
+CREATE STATISTICS stats (dependencies) ON c1, c2 FROM simport_ftable;
+
+ANALYZE simport_ftable; -- should fail
+
+DROP STATISTICS stats;
+
+ANALYZE simport_ftable (cid); -- should fail
+
+ANALYZE simport_ftable (c1, c1); -- should fail
+
+CREATE VIEW simport_view AS SELECT * FROM simport_table;
+CREATE FOREIGN TABLE simport_fview (c1 int, c2 text)
+ SERVER loopback OPTIONS (table_name 'simport_view');
+ALTER FOREIGN TABLE simport_fview OPTIONS (ADD restore_stats 'true');
+
+ANALYZE simport_fview; -- should fail
+
+-- cleanup
+DROP FOREIGN TABLE simport_ftable;
+DROP FOREIGN TABLE simport_fview;
+DROP VIEW simport_view;
+DROP TABLE simport_table;
+
-- ===================================================================
-- test for postgres_fdw_get_connections function with check_conn = true
-- ===================================================================
diff --git a/doc/src/sgml/fdwhandler.sgml b/doc/src/sgml/fdwhandler.sgml
index f601d22d191..a80067d2ee3 100644
--- a/doc/src/sgml/fdwhandler.sgml
+++ b/doc/src/sgml/fdwhandler.sgml
@@ -1409,6 +1409,45 @@ AcquireSampleRowsFunc(Relation relation,
if the FDW does not have any concept of dead rows.)
</para>
+ <para>
+<programlisting>
+bool
+ImportForeignStatistics(Relation relation,
+ List *va_cols,
+ int elevel);
+</programlisting>
+
+ This function is called before the <function>AnalyzeForeignTable</function>
+ callback function when <xref linkend="sql-analyze"/> is executed on a
+ foreign table, and is used to import remotely-calculated statistics (both
+ table-level and column-level) for the foreign table directly to the local
+ server.
+ <literal>relation</literal> is the <structname>Relation</structname> struct
+ describing the target foreign table. <literal>va_cols</literal>, if not
+ NIL, contains the columns specified in the <command>ANALYZE</command>
+ command. <literal>elevel</literal> contains a flag indicating a logging
+ level to use.
+ If the FDW imports statistics successfully, it should return
+ <literal>true</literal>. Otherwise, return <literal>false</literal>, in
+ which case <function>AnalyzeForeignTable</function> callback function is
+ called to collect statistics locally, if supported.
+ </para>
+
+ <para>
+ For reference, the logic for calculating statistics in
+ <productname>PostgreSQL</productname> are found in
+ <filename>src/backend/command/analyze.c</filename>.
+ It's recommended to import table-level and column-level statistics for the
+ foreign table using <function>pg_restore_relation_stats</function> and
+ <function>pg_restore_attribute_stats</function>, respectively.
+ </para>
+
+ <para>
+ If the FDW does not support importing remote statistics for any tables, the
+ <function>ImportForeignStatistics</function> pointer can be set to
+ <literal>NULL</literal>.
+ </para>
+
</sect2>
<sect2 id="fdw-callbacks-import">
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index 9185c76f932..7ac760c3174 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -332,7 +332,7 @@ OPTIONS (ADD password_required 'false');
</para>
<para>
- The following option controls how such an <command>ANALYZE</command>
+ The following options control how such an <command>ANALYZE</command>
operation behaves:
</para>
@@ -364,6 +364,33 @@ OPTIONS (ADD password_required 'false');
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>restore_stats</literal> (<type>boolean</type>)</term>
+ <listitem>
+ <para>
+ This option, which can be specified for a foreign table or a foreign
+ server, determines if <command>ANALYZE</command> on a foreign table
+ will instead attempt to fetch the existing statistics for the foreign
+ table on the remote server, and restore those statistics directly to
+ the local server. If the attempt failed, statistics are collected by
+ row sampling on the foreign table.
+ This option is only useful if the remote table is one that can have
+ regular statistics (tables and materialized views).
+ When using this option, <emphasis>it is the user's responsibility
+ </emphasis> to ensure that the existing statistics for the foreign
+ table are up-to-date.
+ The default is <literal>false</literal>.
+ </para>
+
+ <para>
+ If the foreign table is a partition of a partitioned table, analyzing
+ the partitioned table will still result in row sampling on the foreign
+ table regardless of this setting, though direct analysis of the foreign
+ table would have attempted to restore remote statistics first.
+ </para>
+ </listitem>
+ </varlistentry>
+
</variablelist>
</sect3>
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 49a5cdf579c..3331833a363 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -83,6 +83,7 @@ static void compute_index_stats(Relation onerel, double totalrows,
AnlIndexData *indexdata, int nindexes,
HeapTuple *rows, int numrows,
MemoryContext col_context);
+static void validate_va_cols_list(Relation onerel, List *va_cols);
static VacAttrStats *examine_attribute(Relation onerel, int attnum,
Node *index_expr);
static int acquire_sample_rows(Relation onerel, int elevel,
@@ -114,6 +115,7 @@ analyze_rel(Oid relid, RangeVar *relation,
int elevel;
AcquireSampleRowsFunc acquirefunc = NULL;
BlockNumber relpages = 0;
+ bool stats_imported = false;
/* Select logging level */
if (params->options & VACOPT_VERBOSE)
@@ -182,6 +184,27 @@ analyze_rel(Oid relid, RangeVar *relation,
return;
}
+ /*
+ * Check the given list of columns
+ */
+ if (va_cols != NIL)
+ validate_va_cols_list(onerel, va_cols);
+
+ /*
+ * Initialize progress reporting before setup for regular/foreign tables.
+ * (For the former, the time spent on it would be negligible, but for the
+ * latter, if FDWs support statistics import or analysis, they'd do some
+ * work that needs the remote access, so the time might be non-negligible.)
+ */
+ pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
+ RelationGetRelid(onerel));
+ if (AmAutoVacuumWorkerProcess())
+ pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
+ PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
+ else
+ pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
+ PROGRESS_ANALYZE_STARTED_BY_MANUAL);
+
/*
* Check that it's of an analyzable relkind, and set up appropriately.
*/
@@ -196,26 +219,33 @@ analyze_rel(Oid relid, RangeVar *relation,
else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
/*
- * For a foreign table, call the FDW's hook function to see whether it
- * supports analysis.
+ * For a foreign table, call the FDW's hook functions to see whether
+ * it supports statistics import or analysis.
*/
FdwRoutine *fdwroutine;
- bool ok = false;
fdwroutine = GetFdwRoutineForRelation(onerel, false);
- if (fdwroutine->AnalyzeForeignTable != NULL)
- ok = fdwroutine->AnalyzeForeignTable(onerel,
- &acquirefunc,
- &relpages);
-
- if (!ok)
+ if (fdwroutine->ImportForeignStatistics != NULL &&
+ fdwroutine->ImportForeignStatistics(onerel, va_cols, elevel))
+ stats_imported = true;
+ else
{
- ereport(WARNING,
- (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
- RelationGetRelationName(onerel))));
- relation_close(onerel, ShareUpdateExclusiveLock);
- return;
+ bool ok = false;
+
+ if (fdwroutine->AnalyzeForeignTable != NULL)
+ ok = fdwroutine->AnalyzeForeignTable(onerel,
+ &acquirefunc,
+ &relpages);
+
+ if (!ok)
+ {
+ ereport(WARNING,
+ errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
+ RelationGetRelationName(onerel)));
+ relation_close(onerel, ShareUpdateExclusiveLock);
+ goto out;
+ }
}
}
else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
@@ -232,26 +262,16 @@ analyze_rel(Oid relid, RangeVar *relation,
(errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
RelationGetRelationName(onerel))));
relation_close(onerel, ShareUpdateExclusiveLock);
- return;
+ goto out;
}
- /*
- * OK, let's do it. First, initialize progress reporting.
- */
- pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
- RelationGetRelid(onerel));
- if (AmAutoVacuumWorkerProcess())
- pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
- PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
- else
- pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
- PROGRESS_ANALYZE_STARTED_BY_MANUAL);
-
/*
* Do the normal non-recursive ANALYZE. We can skip this for partitioned
- * tables, which don't contain any rows.
+ * tables, which don't contain any rows, and foreign tables that
+ * successfully imported statistics.
*/
- if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+ && !stats_imported)
do_analyze_rel(onerel, params, va_cols, acquirefunc,
relpages, false, in_outer_xact, elevel);
@@ -270,6 +290,7 @@ analyze_rel(Oid relid, RangeVar *relation,
*/
relation_close(onerel, NoLock);
+out:
pgstat_progress_end_command();
}
@@ -368,16 +389,10 @@ do_analyze_rel(Relation onerel, const VacuumParams *params,
starttime = GetCurrentTimestamp();
/*
- * Determine which columns to analyze
- *
- * Note that system attributes are never analyzed, so we just reject them
- * at the lookup stage. We also reject duplicate column mentions. (We
- * could alternatively ignore duplicates, but analyzing a column twice
- * won't work; we'd end up making a conflicting update in pg_statistic.)
+ * Determine which columns to analyze.
*/
if (va_cols != NIL)
{
- Bitmapset *unique_cols = NULL;
ListCell *le;
vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
@@ -388,18 +403,7 @@ do_analyze_rel(Relation onerel, const VacuumParams *params,
char *col = strVal(lfirst(le));
i = attnameAttNum(onerel, col, false);
- if (i == InvalidAttrNumber)
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_COLUMN),
- errmsg("column \"%s\" of relation \"%s\" does not exist",
- col, RelationGetRelationName(onerel))));
- if (bms_is_member(i, unique_cols))
- ereport(ERROR,
- (errcode(ERRCODE_DUPLICATE_COLUMN),
- errmsg("column \"%s\" of relation \"%s\" appears more than once",
- col, RelationGetRelationName(onerel))));
- unique_cols = bms_add_member(unique_cols, i);
-
+ Assert(i != InvalidAttrNumber);
vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
if (vacattrstats[tcnt] != NULL)
tcnt++;
@@ -1030,6 +1034,40 @@ compute_index_stats(Relation onerel, double totalrows,
MemoryContextDelete(ind_context);
}
+/*
+ * validate_va_cols_list -- validate the columns list given to analyze_rel
+ *
+ * Note that system attributes are never analyzed, so we just reject them at
+ * the lookup stage. We also reject duplicate column mentions. (We could
+ * alternatively ignore duplicates, but analyzing a column twice won't work;
+ * we'd end up making a conflicting update in pg_statistic.)
+ */
+static void
+validate_va_cols_list(Relation onerel, List *va_cols)
+{
+ Bitmapset *unique_cols = NULL;
+ ListCell *le;
+
+ Assert(va_cols != NIL);
+ foreach(le, va_cols)
+ {
+ char *col = strVal(lfirst(le));
+ int i = attnameAttNum(onerel, col, false);
+
+ if (i == InvalidAttrNumber)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_COLUMN),
+ errmsg("column \"%s\" of relation \"%s\" does not exist",
+ col, RelationGetRelationName(onerel))));
+ if (bms_is_member(i, unique_cols))
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_COLUMN),
+ errmsg("column \"%s\" of relation \"%s\" appears more than once",
+ col, RelationGetRelationName(onerel))));
+ unique_cols = bms_add_member(unique_cols, i);
+ }
+}
+
/*
* examine_attribute -- pre-analysis of a single column
*
@@ -1044,37 +1082,15 @@ examine_attribute(Relation onerel, int attnum, Node *index_expr)
{
Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
int attstattarget;
- HeapTuple atttuple;
- Datum dat;
- bool isnull;
HeapTuple typtuple;
VacAttrStats *stats;
int i;
bool ok;
- /* Never analyze dropped columns */
- if (attr->attisdropped)
- return NULL;
-
- /* Don't analyze virtual generated columns */
- if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
- return NULL;
-
/*
- * Get attstattarget value. Set to -1 if null. (Analyze functions expect
- * -1 to mean use default_statistics_target; see for example
- * std_typanalyze.)
+ * Check if the column is analyzable.
*/
- atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
- if (!HeapTupleIsValid(atttuple))
- elog(ERROR, "cache lookup failed for attribute %d of relation %u",
- attnum, RelationGetRelid(onerel));
- dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
- attstattarget = isnull ? -1 : DatumGetInt16(dat);
- ReleaseSysCache(atttuple);
-
- /* Don't analyze column if user has specified not to */
- if (attstattarget == 0)
+ if (!attribute_is_analyzable(onerel, attnum, attr, &attstattarget))
return NULL;
/*
@@ -1155,6 +1171,45 @@ examine_attribute(Relation onerel, int attnum, Node *index_expr)
return stats;
}
+bool
+attribute_is_analyzable(Relation onerel, int attnum, Form_pg_attribute attr,
+ int *p_attstattarget)
+{
+ int attstattarget;
+ HeapTuple atttuple;
+ Datum dat;
+ bool isnull;
+
+ /* Never analyze dropped columns */
+ if (attr->attisdropped)
+ return false;
+
+ /* Don't analyze virtual generated columns */
+ if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
+ return false;
+
+ /*
+ * Get attstattarget value. Set to -1 if null. (Analyze functions expect
+ * -1 to mean use default_statistics_target; see for example
+ * std_typanalyze.)
+ */
+ atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
+ if (!HeapTupleIsValid(atttuple))
+ elog(ERROR, "cache lookup failed for attribute %d of relation %u",
+ attnum, RelationGetRelid(onerel));
+ dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
+ attstattarget = isnull ? -1 : DatumGetInt16(dat);
+ ReleaseSysCache(atttuple);
+
+ /* Don't analyze column if user has specified not to */
+ if (attstattarget == 0)
+ return false;
+
+ if (p_attstattarget)
+ *p_attstattarget = attstattarget;
+ return true;
+}
+
/*
* Read stream callback returning the next BlockNumber as chosen by the
* BlockSampling algorithm.
diff --git a/src/backend/statistics/extended_stats.c b/src/backend/statistics/extended_stats.c
index cb7898b21ee..2b83355d26e 100644
--- a/src/backend/statistics/extended_stats.c
+++ b/src/backend/statistics/extended_stats.c
@@ -246,6 +246,40 @@ BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows,
table_close(pg_stext, RowExclusiveLock);
}
+/*
+ * Test if the given relation has extended statistics objects.
+ */
+bool
+HasRelationExtStatistics(Relation onerel)
+{
+ Relation pg_statext;
+ SysScanDesc scan;
+ ScanKeyData skey;
+ bool found;
+
+ pg_statext = table_open(StatisticExtRelationId, RowExclusiveLock);
+
+ /*
+ * Prepare to scan pg_statistic_ext for entries having stxrelid = this
+ * rel.
+ */
+ ScanKeyInit(&skey,
+ Anum_pg_statistic_ext_stxrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(onerel)));
+
+ scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
+ NULL, 1, &skey);
+
+ found = HeapTupleIsValid(systable_getnext(scan));
+
+ systable_endscan(scan);
+
+ table_close(pg_statext, RowExclusiveLock);
+
+ return found;
+}
+
/*
* ComputeExtStatisticsRows
* Compute number of rows required by extended statistics on a table.
diff --git a/src/include/commands/vacuum.h b/src/include/commands/vacuum.h
index 69fec07491b..956d9cea36d 100644
--- a/src/include/commands/vacuum.h
+++ b/src/include/commands/vacuum.h
@@ -430,6 +430,8 @@ extern void parallel_vacuum_main(dsm_segment *seg, shm_toc *toc);
extern void analyze_rel(Oid relid, RangeVar *relation,
const VacuumParams *params, List *va_cols, bool in_outer_xact,
BufferAccessStrategy bstrategy);
+extern bool attribute_is_analyzable(Relation onerel, int attnum, Form_pg_attribute attr,
+ int *p_attstattarget);
extern bool std_typanalyze(VacAttrStats *stats);
/* in utils/misc/sampling.c --- duplicate of declarations in utils/sampling.h */
diff --git a/src/include/foreign/fdwapi.h b/src/include/foreign/fdwapi.h
index 96b6f692d2a..abf59a0d8ad 100644
--- a/src/include/foreign/fdwapi.h
+++ b/src/include/foreign/fdwapi.h
@@ -157,6 +157,10 @@ typedef bool (*AnalyzeForeignTable_function) (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
+typedef bool (*ImportForeignStatistics_function) (Relation relation,
+ List *va_cols,
+ int elevel);
+
typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
Oid serverOid);
@@ -255,6 +259,7 @@ typedef struct FdwRoutine
/* Support functions for ANALYZE */
AnalyzeForeignTable_function AnalyzeForeignTable;
+ ImportForeignStatistics_function ImportForeignStatistics;
/* Support functions for IMPORT FOREIGN SCHEMA */
ImportForeignSchema_function ImportForeignSchema;
diff --git a/src/include/statistics/statistics.h b/src/include/statistics/statistics.h
index 38a56f6ccb3..8f9b9d237fd 100644
--- a/src/include/statistics/statistics.h
+++ b/src/include/statistics/statistics.h
@@ -101,6 +101,7 @@ extern MCVList *statext_mcv_load(Oid mvoid, bool inh);
extern void BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows,
int numrows, HeapTuple *rows,
int natts, VacAttrStats **vacattrstats);
+extern bool HasRelationExtStatistics(Relation onerel);
extern int ComputeExtStatisticsRows(Relation onerel,
int natts, VacAttrStats **vacattrstats);
extern bool statext_is_kind_built(HeapTuple htup, char type);
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-08 11:24 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-04-08 11:24 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Tue, Apr 7, 2026 at 7:09 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
> I think the patch is committable, so I will push it if no objections.
Pushed. I closed the CF entry as well.
Corey, if you intend to continue working on the remote_analyze patch,
please start a new thread about it and create a new CF entry with that
thread.
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-08 13:11 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-04-08 13:11 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> Pushed. I closed the CF entry as well.
>
Hooray!
> Corey, if you intend to continue working on the remote_analyze patch,
> please start a new thread about it and create a new CF entry with that
> thread.
>
I will, but I want to incorporate your feedback about how analyze should
work and check in with some people at pgconf.dev first.
Thanks again!
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-12 06:31 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 0 replies; 89+ messages in thread
From: Etsuro Fujita @ 2026-04-12 06:31 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Wed, Apr 8, 2026 at 10:11 PM Corey Huinker <corey.huinker@gmail.com> wrote:
>> Corey, if you intend to continue working on the remote_analyze patch,
>> please start a new thread about it and create a new CF entry with that
>> thread.
>
> I will, but I want to incorporate your feedback about how analyze should work and check in with some people at pgconf.dev first.
Ok, thanks!
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-12 18:15 Tom Lane <tgl@sss.pgh.pa.us>
parent: Corey Huinker <corey.huinker@gmail.com>
2 siblings, 1 reply; 89+ messages in thread
From: Tom Lane @ 2026-04-12 18:15 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Corey Huinker <corey.huinker@gmail.com>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
Etsuro Fujita <etsuro.fujita@gmail.com> writes:
> Pushed. I closed the CF entry as well.
Coverity doesn't like this patch's uses of strncpy():
>>> CID 1691464: (BUFFER_SIZE)
>>> Calling "strncpy" with a maximum size argument of 64 bytes on destination array "remattrmap[attrcnt].local_attname" of size 64 bytes might leave the destination string unterminated.
5960 strncpy(remattrmap[attrcnt].local_attname, attname, NAMEDATALEN);
5961 strncpy(remattrmap[attrcnt].remote_attname, remote_attname, NAMEDATALEN);
I think it's dead right to complain: remote_attname, in particular,
could certainly be longer than NAMEDATALEN.
AFAICS, postgres_fdw's subsequent uses of those strings only need
them to be nul-terminated C strings, so strncpy's property of
zero-filling the whole buffer is not needed here. I recommend
s/strncpy/strlcpy/.
It's probably also appropriate to think about using pg_mbcliplen()
to ensure that this code doesn't result in a broken multibyte
character.
regards, tom lane
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-13 04:53 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-04-13 04:53 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Corey Huinker <corey.huinker@gmail.com>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Sun, Apr 12, 2026 at 11:15 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Coverity doesn't like this patch's uses of strncpy():
>
> >>> CID 1691464: (BUFFER_SIZE)
> >>> Calling "strncpy" with a maximum size argument of 64 bytes on destination array "remattrmap[attrcnt].local_attname" of size 64 bytes might leave the destination string unterminated.
> 5960 strncpy(remattrmap[attrcnt].local_attname, attname, NAMEDATALEN);
> 5961 strncpy(remattrmap[attrcnt].remote_attname, remote_attname, NAMEDATALEN);
>
> I think it's dead right to complain: remote_attname, in particular,
> could certainly be longer than NAMEDATALEN.
>
> AFAICS, postgres_fdw's subsequent uses of those strings only need
> them to be nul-terminated C strings, so strncpy's property of
> zero-filling the whole buffer is not needed here. I recommend
> s/strncpy/strlcpy/.
Seems like a good idea.
> It's probably also appropriate to think about using pg_mbcliplen()
> to ensure that this code doesn't result in a broken multibyte
> character.
Will do.
I am currently overseas and will be attending an event this week, so I
will work on this after returning home. In the meantime, I created an
entry for it in the open items list.
Thanks!
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-04-30 18:04 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-04-30 18:04 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
>
> > AFAICS, postgres_fdw's subsequent uses of those strings only need
> > them to be nul-terminated C strings, so strncpy's property of
> > zero-filling the whole buffer is not needed here. I recommend
> > s/strncpy/strlcpy/.
>
> Seems like a good idea.
>
> > It's probably also appropriate to think about using pg_mbcliplen()
> > to ensure that this code doesn't result in a broken multibyte
> > character.
>
> Will do.
>
> I am currently overseas and will be attending an event this week, so I
> will work on this after returning home. In the meantime, I created an
> entry for it in the open items list.
>
> Thanks!
I've attached 2 different fixes.
The first one swtiches to pg_mbcliplen+memcpy, which is probably overkill
but better safe than sorry.
The second gets rid of the string buffers entirely, and instead frees the
nested object.
I have no preference between the two, though I suspect that the nested-free
solution will be preferred by the community.
Attachments: download all (2 files, .tar.gz)
v1-0001-Replace-strncpy-with-pg_mbcliplen-plus-memcpy.patch (text/x-patch, 1.8K) download
From c1ec2ad6939b85dce3c692a1633e4d45facd292d Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 30 Apr 2026 13:01:15 -0400
Subject: [PATCH v1] Replace strncpy with pg_mbcliplen plus memcpy.
---
contrib/postgres_fdw/postgres_fdw.c | 19 +++++++++++++++++--
1 file changed, 17 insertions(+), 2 deletions(-)
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index c42cb690c7b..ed72e02ced7 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -27,6 +27,7 @@
#include "executor/spi.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
+#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
@@ -5907,6 +5908,20 @@ fetch_attstats(PGconn *conn, int server_version_num,
return res;
}
+/*
+ * Copy a untrusted string into a NameData conforming string buffer.
+ */
+static void
+attname_copy(char *dest, char *src)
+{
+ int len = strlen(src);
+
+ if (len >= NAMEDATALEN)
+ len = pg_mbcliplen(src, len, NAMEDATALEN - 1);
+
+ memcpy(dest, src, len+1);
+}
+
/*
* Build the mapping of local columns to remote columns and create a column
* list used for constructing the fetch_attstats query.
@@ -5957,8 +5972,8 @@ build_remattrmap(Relation relation, List *va_cols,
appendStringInfoString(column_list, quote_identifier(remote_attname));
remattrmap[attrcnt].local_attnum = attnum;
- strncpy(remattrmap[attrcnt].local_attname, attname, NAMEDATALEN);
- strncpy(remattrmap[attrcnt].remote_attname, remote_attname, NAMEDATALEN);
+ attname_copy(remattrmap[attrcnt].local_attname, attname);
+ attname_copy(remattrmap[attrcnt].remote_attname, remote_attname);
remattrmap[attrcnt].res_index = -1;
attrcnt++;
}
base-commit: 5642a0367c2fe69684800c5d5c5929c20d99ef72
--
2.54.0
v1-0001-Replace-name-buffers-from-RemoteAttributeMapping-.patch (text/x-patch, 3.0K) download
From 867d5b7dfbd73caa4d8e917c900e92159b4653ce Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 30 Apr 2026 13:52:27 -0400
Subject: [PATCH v1] Replace name buffers from RemoteAttributeMapping with
pointers
Replace the char buffers in RemoteAttributeMapping with regular
pointers. This creates the need for a function to clean up the nested
data structure, but it elminates the need for some buffer checks that
would have required including pg_wchar.h.
---
contrib/postgres_fdw/postgres_fdw.c | 34 +++++++++++++++++++++++------
1 file changed, 27 insertions(+), 7 deletions(-)
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index c42cb690c7b..8164e9b87f8 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -324,10 +324,10 @@ typedef struct
/* Pairs of remote columns with local columns */
typedef struct
{
- AttrNumber local_attnum;
- char local_attname[NAMEDATALEN];
- char remote_attname[NAMEDATALEN];
+ char *local_attname;
+ char *remote_attname;
int res_index;
+ AttrNumber local_attnum;
} RemoteAttributeMapping;
/* Result sets that are returned from a foreign statistics scan */
@@ -704,6 +704,7 @@ static PGresult *fetch_attstats(PGconn *conn, int server_version_num,
const char *column_list);
static RemoteAttributeMapping *build_remattrmap(Relation relation, List *va_cols,
int *p_attrcnt, StringInfo column_list);
+static void free_remattrmap(RemoteAttributeMapping *map, int len);
static bool attname_in_list(const char *attname, List *va_cols);
static int remattrmap_cmp(const void *v1, const void *v2);
static bool match_attrmap(PGresult *res,
@@ -5670,8 +5671,7 @@ postgresImportForeignStatistics(Relation relation, List *va_cols, int elevel)
PQclear(remstats.rel);
PQclear(remstats.att);
- if (remattrmap)
- pfree(remattrmap);
+ free_remattrmap(remattrmap, attrcnt);
return ok;
}
@@ -5957,8 +5957,8 @@ build_remattrmap(Relation relation, List *va_cols,
appendStringInfoString(column_list, quote_identifier(remote_attname));
remattrmap[attrcnt].local_attnum = attnum;
- strncpy(remattrmap[attrcnt].local_attname, attname, NAMEDATALEN);
- strncpy(remattrmap[attrcnt].remote_attname, remote_attname, NAMEDATALEN);
+ remattrmap[attrcnt].local_attname = pstrdup(attname);
+ remattrmap[attrcnt].remote_attname = pstrdup(remote_attname);
remattrmap[attrcnt].res_index = -1;
attrcnt++;
}
@@ -5972,6 +5972,26 @@ build_remattrmap(Relation relation, List *va_cols,
return remattrmap;
}
+/*
+ * Free the structure created by build_remattrmap().
+ */
+static void
+free_remattrmap(RemoteAttributeMapping *map, int len)
+{
+ if (!map)
+ return;
+
+ for (int i = 0; i < len; i++)
+ {
+ if (map[i].local_attname)
+ pfree(map[i].local_attname);
+ if (map[i].remote_attname)
+ pfree(map[i].remote_attname);
+ }
+
+ pfree(map);
+}
+
/*
* Test if an attribute name is in the list.
*
base-commit: 5642a0367c2fe69684800c5d5c5929c20d99ef72
--
2.54.0
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-05-12 11:36 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-05-12 11:36 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Fri, May 1, 2026 at 3:04 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> I've attached 2 different fixes.
Thanks for the patches!
> The first one swtiches to pg_mbcliplen+memcpy, which is probably overkill but better safe than sorry.
I noticed that RemoteAttributeMapping.remote_attname is used in
match_attrmap(), which assumes that it fully contains a remote
attribute's name, so I think this solution is actually unsafe.
> The second gets rid of the string buffers entirely, and instead frees the nested object.
>
> I have no preference between the two, though I suspect that the nested-free solution will be preferred by the community.
ISTM that the second solution is the right direction to go in.
+static void
+free_remattrmap(RemoteAttributeMapping *map, int len)
+{
+ if (!map)
+ return;
+
+ for (int i = 0; i < len; i++)
+ {
+ if (map[i].local_attname)
+ pfree(map[i].local_attname);
+ if (map[i].remote_attname)
+ pfree(map[i].remote_attname);
+ }
The if tests for local_attname/remote_attname should be assertions?
It took more time than expected to return to this issue. My apologies for that.
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-05-13 11:40 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-05-13 11:40 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Tue, May 12, 2026 at 8:36 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
> On Fri, May 1, 2026 at 3:04 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> > The second gets rid of the string buffers entirely, and instead frees the nested object.
> >
> > I have no preference between the two, though I suspect that the nested-free solution will be preferred by the community.
>
> ISTM that the second solution is the right direction to go in.
>
> +static void
> +free_remattrmap(RemoteAttributeMapping *map, int len)
> +{
> + if (!map)
> + return;
> +
> + for (int i = 0; i < len; i++)
> + {
> + if (map[i].local_attname)
> + pfree(map[i].local_attname);
> + if (map[i].remote_attname)
> + pfree(map[i].remote_attname);
> + }
>
> The if tests for local_attname/remote_attname should be assertions?
I mean that by the definition of build_remattrmap(), the
local_attname/remote_attname cannot be NULL if the given map isn't
NULL, so the if tests are just a waste of cycles. So I modified the
patch as such. Updated patch attached. I also removed an extra
change made to RemoteAttributeMapping, which seemed irrelevant to this
issue to me.
Best regards,
Etsuro Fujita
Attachments:
v1-0001-Replace-name-buffers-from-RemoteAttributeMapping-efujita.patch (application/octet-stream, 2.2K) download
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index cdb555727f8..30eb6668b6c 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -333,8 +333,8 @@ typedef struct
typedef struct
{
AttrNumber local_attnum;
- char local_attname[NAMEDATALEN];
- char remote_attname[NAMEDATALEN];
+ char *local_attname;
+ char *remote_attname;
int res_index;
} RemoteAttributeMapping;
@@ -704,6 +704,7 @@ static PGresult *fetch_attstats(PGconn *conn, int server_version_num,
const char *column_list);
static RemoteAttributeMapping *build_remattrmap(Relation relation, List *va_cols,
int *p_attrcnt, StringInfo column_list);
+static void free_remattrmap(RemoteAttributeMapping *map, int len);
static bool attname_in_list(const char *attname, List *va_cols);
static int remattrmap_cmp(const void *v1, const void *v2);
static bool match_attrmap(PGresult *res,
@@ -5670,8 +5671,7 @@ postgresImportForeignStatistics(Relation relation, List *va_cols, int elevel)
PQclear(remstats.rel);
PQclear(remstats.att);
- if (remattrmap)
- pfree(remattrmap);
+ free_remattrmap(remattrmap, attrcnt);
return ok;
}
@@ -5957,8 +5957,8 @@ build_remattrmap(Relation relation, List *va_cols,
deparseStringLiteral(column_list, remote_attname);
remattrmap[attrcnt].local_attnum = attnum;
- strncpy(remattrmap[attrcnt].local_attname, attname, NAMEDATALEN);
- strncpy(remattrmap[attrcnt].remote_attname, remote_attname, NAMEDATALEN);
+ remattrmap[attrcnt].local_attname = pstrdup(attname);
+ remattrmap[attrcnt].remote_attname = pstrdup(remote_attname);
remattrmap[attrcnt].res_index = -1;
attrcnt++;
}
@@ -5972,6 +5972,26 @@ build_remattrmap(Relation relation, List *va_cols,
return remattrmap;
}
+/*
+ * Free the structure created by build_remattrmap().
+ */
+static void
+free_remattrmap(RemoteAttributeMapping *map, int len)
+{
+ if (!map)
+ return;
+
+ for (int i = 0; i < len; i++)
+ {
+ Assert(map[i].local_attname);
+ pfree(map[i].local_attname);
+ Assert(map[i].remote_attname);
+ pfree(map[i].remote_attname);
+ }
+
+ pfree(map);
+}
+
/*
* Test if an attribute name is in the list.
*
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-05-14 11:35 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-05-14 11:35 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Wed, May 13, 2026 at 8:40 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
> On Tue, May 12, 2026 at 8:36 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
> > On Fri, May 1, 2026 at 3:04 AM Corey Huinker <corey.huinker@gmail.com> wrote:
> > > The second gets rid of the string buffers entirely, and instead frees the nested object.
> > >
> > > I have no preference between the two, though I suspect that the nested-free solution will be preferred by the community.
> >
> > ISTM that the second solution is the right direction to go in.
> >
> > +static void
> > +free_remattrmap(RemoteAttributeMapping *map, int len)
> > +{
> > + if (!map)
> > + return;
> > +
> > + for (int i = 0; i < len; i++)
> > + {
> > + if (map[i].local_attname)
> > + pfree(map[i].local_attname);
> > + if (map[i].remote_attname)
> > + pfree(map[i].remote_attname);
> > + }
> >
> > The if tests for local_attname/remote_attname should be assertions?
>
> I mean that by the definition of build_remattrmap(), the
> local_attname/remote_attname cannot be NULL if the given map isn't
> NULL, so the if tests are just a waste of cycles. So I modified the
> patch as such. Updated patch attached. I also removed an extra
> change made to RemoteAttributeMapping, which seemed irrelevant to this
> issue to me.
I'll push the updated patch if no objections from you (or anyone else).
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-05-16 09:10 Etsuro Fujita <etsuro.fujita@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Etsuro Fujita @ 2026-05-16 09:10 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Thu, May 14, 2026 at 8:35 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
> I'll push the updated patch if no objections from you (or anyone else).
Pushed. I closed the open item as well.
Best regards,
Etsuro Fujita
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-05-26 20:31 Corey Huinker <corey.huinker@gmail.com>
parent: Etsuro Fujita <etsuro.fujita@gmail.com>
0 siblings, 0 replies; 89+ messages in thread
From: Corey Huinker @ 2026-05-26 20:31 UTC (permalink / raw)
To: Etsuro Fujita <etsuro.fujita@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Sat, May 16, 2026 at 5:10 AM Etsuro Fujita <etsuro.fujita@gmail.com>
wrote:
> On Thu, May 14, 2026 at 8:35 PM Etsuro Fujita <etsuro.fujita@gmail.com>
> wrote:
> > I'll push the updated patch if no objections from you (or anyone else).
>
> Pushed. I closed the open item as well.
>
> Best regards,
> Etsuro Fujita
>
My own apologies for a late reply. I agree that the second method was the
better fix, and I agree with your changes (making free_remattrmap tolerant
of null maps, and moving the if-tests to asserts).
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-09-23 16:15 Nurlan Tulemisov <nurlan.tulemisov@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
1 sibling, 1 reply; 89+ messages in thread
From: Nurlan Tulemisov @ 2026-09-23 16:15 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
Hi
I would like to follow up on the earlier discussion about remote statistics
freshness.
Etsuro suggested checking whether remote statistics are sufficiently fresh
before importing them, with a fallback to sampling otherwise [1]. Corey
also discussed consulting remote pg_stat_all_tables when deciding whether
remote ANALYZE is needed [2].
I would like to explore a simple freshness check before importing
statistics, using the same modification threshold used for autoanalyze:
stale = n_mod_since_analyze >
remote_analyze_threshold +
remote_analyze_scale_factor * max(reltuples, 0)
All values would come from the remote server, with the threshold and scale
factor taking the remote table's autovacuum settings into account,
including per-table overrides.
If this condition is true, postgres_fdw would fallback to its existing
sampling instead of importing the remote statistics. This would provide a
practical criterion for rejecting potentially stale statistics, although it
would not guarantee their accuracy when the condition is false.
One limitation to consider is that the statistics counters can be reset.
Does this approach make sense? Are either of you already working on, or
planning, a similar check? I would be happy to coordinate.
[1](
www.postgresql.org/message-id/CAPmGK16AQzGsEe6pD7m42AO1KRCuXQu%3DU_abXaAf3juCS5U%2BmA%40mail.gmail.com
)
[2](
www.postgresql.org/message-id/CADkLM%3DeWt0n8xpJkdNkeor7%3D%3DwUcnzYh%2BrSEaFKpdngJk0ZwJg%40mail.gmail.com
)
On Wed, Sep 23, 2026 at 6:59 PM Corey Huinker <corey.huinker@gmail.com>
wrote:
> The problem is not limited to this special case. Consider cases when
>> 1) the remote table that has many rows are heavily updated after it
>> got analyzed, and then 2) postgres_fdw imports its stats before it
>> gets re-analyzed. The stats postgres_fdw imports would be stale,
>> causing plan degradation. I don't think we should enable this feature
>> by default until we guarantee stats freshness in some way.
>
>
> So it seems like we have the following configurations desired by at least
> somebody:
>
> 0. Row Sampling Only
> 1. Fetch stats and fall back to row sampling.
> 2. Always analyze remote table (assuming it is a table that can hold
> stats), then fetch stats, and fall back if necessary.
> 3. Fetch stats, and if that turned up 0 attribute stats try an analyze,
> then try to refetch and if it still fails go to row sampling.
>
> With the following interpretation of reltuples = 0:
>
> a. The table is definitively empty, stop.
> b. The table is missing stats and running an analyze is cheap (assuming
> remote analysis is even enabled)
> c. if remote version >= 14 then a else b
>
> I'm of the opinion that 3c is the best configuration for most tables, and
> you have advocated for 1a without an analyze option and 2a with one. Option
> 2 seems a bit heavy handed to me, but I could see checking the remote
> pg_stat_all_tables and making an analyze/no-analyze judgement call based on
> that, perhaps call that analyze_stale_vacuum_interval or something like
> that. That could be a neat feature for v20, and so whatever default we
> choose for fetch_stats, I ask that we choose values that keep our options
> open for all 4x3 configurations enumerated above.
>
--
Regards,
Nurlan
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-09-23 18:26 Corey Huinker <corey.huinker@gmail.com>
parent: Nurlan Tulemisov <nurlan.tulemisov@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Corey Huinker @ 2026-09-23 18:26 UTC (permalink / raw)
To: Nurlan Tulemisov <nurlan.tulemisov@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Wed, Sep 23, 2026 at 12:15 PM Nurlan Tulemisov <
nurlan.tulemisov@gmail.com> wrote:
> Hi
>
> I would like to follow up on the earlier discussion about remote
> statistics freshness.
>
> Etsuro suggested checking whether remote statistics are sufficiently fresh
> before importing them, with a fallback to sampling otherwise [1]. Corey
> also discussed consulting remote pg_stat_all_tables when deciding whether
> remote ANALYZE is needed [2].
>
There was also an option for initiating an ANALYZE on the remote system if
the current stats failed in some way, then re-trying the import,and only
then falling back to sampling...though there's likely few scenarios in
which an ANALYZE worked but the table sample does.
Checking the freshness via pg_stat_all_tables is attractive because it is
cheap, but what constitutes "fresh" and how would we configure that? Is it
a time interval beyond which stats are judged too old? Wouldn't such a
thing cause false positives if the remote table is never updated? I think
that there's considerable discussion to be had as to what such a feature
would look like, and the implementation of it will be pretty small by
comparison. Obviously those discussions have been on pause with all of the
v19 issues.
>
> I would like to explore a simple freshness check before importing
> statistics, using the same modification threshold used for autoanalyze:
>
> stale = n_mod_since_analyze >
> remote_analyze_threshold +
> remote_analyze_scale_factor * max(reltuples, 0)
>
> All values would come from the remote server, with the threshold and scale
> factor taking the remote table's autovacuum settings into account,
> including per-table overrides.
>
So, basically you're proposing that we use the criteria of "the remote
server knows it should analyze this table, but hasn't yet for some reason"?
That's simple enough, but I wonder if that information wouldn't better be
used to defer the current local autoanalyze, using the thinking that we're
likely to get better stats after the remote catches up.
> If this condition is true, postgres_fdw would fallback to its existing
> sampling instead of importing the remote statistics. This would provide a
> practical criterion for rejecting potentially stale statistics, although it
> would not guarantee their accuracy when the condition is false.
> One limitation to consider is that the statistics counters can be reset.
>
> Does this approach make sense? Are either of you already working on, or
> planning, a similar check? I would be happy to coordinate.
>
I'm happy to resume efforts on this for v20+, but I want to be very sure
that we have consensus about what the right course of action is. This
feature has had several loops where progress was made toward a design and
implementation, but failed to get the attention of other parties who then
had objections to the chosen design or implementation. Additionally, I
think that it makes sense to see how this feature is used in the wild, and
let that guide additional feature direction.
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-09-24 12:50 Nurlan Tulemisov <nurlan.tulemisov@gmail.com>
parent: Corey Huinker <corey.huinker@gmail.com>
0 siblings, 1 reply; 89+ messages in thread
From: Nurlan Tulemisov @ 2026-09-24 12:50 UTC (permalink / raw)
To: Corey Huinker <corey.huinker@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
Hi Corey,
Thanks for the explanation.
> So, basically you're proposing that we use the criteria of "the remote
> server knows it should analyze this table, but hasn't yet for some reason"?
Yes, the intention is to reuse the modification threshold PostgreSQL
already uses for autoanalyze.
That's simple enough, but I wonder if that information wouldn't better be
> used to defer the current local autoanalyze, using the thinking that we're
> likely to get better stats after the remote catches up.
My concern with deferring the local refresh is that exceeding this
threshold does not guarantee that the remote ANALYZE will happen soon.
Autovacuum could be disabled for the remote table, or its workers could be
busy.
As a smaller first step, would it make sense to emit a WARNING when
importing statistics from a remote table whose modification count exceeds
this threshold, while keeping the current import behavior?
On Wed, Sep 23, 2026 at 9:26 PM Corey Huinker <corey.huinker@gmail.com>
wrote:
> On Wed, Sep 23, 2026 at 12:15 PM Nurlan Tulemisov <
> nurlan.tulemisov@gmail.com> wrote:
>
>> Hi
>>
>> I would like to follow up on the earlier discussion about remote
>> statistics freshness.
>>
>> Etsuro suggested checking whether remote statistics are sufficiently
>> fresh before importing them, with a fallback to sampling otherwise [1].
>> Corey also discussed consulting remote pg_stat_all_tables when deciding
>> whether remote ANALYZE is needed [2].
>>
>
> There was also an option for initiating an ANALYZE on the remote system if
> the current stats failed in some way, then re-trying the import,and only
> then falling back to sampling...though there's likely few scenarios in
> which an ANALYZE worked but the table sample does.
>
> Checking the freshness via pg_stat_all_tables is attractive because it is
> cheap, but what constitutes "fresh" and how would we configure that? Is it
> a time interval beyond which stats are judged too old? Wouldn't such a
> thing cause false positives if the remote table is never updated? I think
> that there's considerable discussion to be had as to what such a feature
> would look like, and the implementation of it will be pretty small by
> comparison. Obviously those discussions have been on pause with all of the
> v19 issues.
>
>
>>
>> I would like to explore a simple freshness check before importing
>> statistics, using the same modification threshold used for autoanalyze:
>>
>> stale = n_mod_since_analyze >
>> remote_analyze_threshold +
>> remote_analyze_scale_factor * max(reltuples, 0)
>>
>> All values would come from the remote server, with the threshold and
>> scale factor taking the remote table's autovacuum settings into account,
>> including per-table overrides.
>>
>
> So, basically you're proposing that we use the criteria of "the remote
> server knows it should analyze this table, but hasn't yet for some reason"?
> That's simple enough, but I wonder if that information wouldn't better be
> used to defer the current local autoanalyze, using the thinking that we're
> likely to get better stats after the remote catches up.
>
>
>
>> If this condition is true, postgres_fdw would fallback to its existing
>> sampling instead of importing the remote statistics. This would provide a
>> practical criterion for rejecting potentially stale statistics, although it
>> would not guarantee their accuracy when the condition is false.
>> One limitation to consider is that the statistics counters can be reset.
>>
>> Does this approach make sense? Are either of you already working on, or
>> planning, a similar check? I would be happy to coordinate.
>>
>
> I'm happy to resume efforts on this for v20+, but I want to be very sure
> that we have consensus about what the right course of action is. This
> feature has had several loops where progress was made toward a design and
> implementation, but failed to get the attention of other parties who then
> had objections to the chosen design or implementation. Additionally, I
> think that it makes sense to see how this feature is used in the wild, and
> let that guide additional feature direction.
>
--
Regards,
Nurlan
^ permalink raw reply [nested|flat] 89+ messages in thread
* Re: Import Statistics in postgres_fdw before resorting to sampling.
@ 2026-09-25 19:59 Corey Huinker <corey.huinker@gmail.com>
parent: Nurlan Tulemisov <nurlan.tulemisov@gmail.com>
0 siblings, 0 replies; 89+ messages in thread
From: Corey Huinker @ 2026-09-25 19:59 UTC (permalink / raw)
To: Nurlan Tulemisov <nurlan.tulemisov@gmail.com>; +Cc: Etsuro Fujita <etsuro.fujita@gmail.com>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers; jkatz@postgresql.org; nathandbossart@gmail.com
On Thu, Sep 24, 2026 at 8:50 AM Nurlan Tulemisov <nurlan.tulemisov@gmail.com>
wrote:
> Hi Corey,
> Thanks for the explanation.
>
>
>> So, basically you're proposing that we use the criteria of "the remote
>> server knows it should analyze this table, but hasn't yet for some reason"?
>
>
> Yes, the intention is to reuse the modification threshold PostgreSQL
> already uses for autoanalyze.
>
We could use the same reasoning to instead directly ANALYZE the remote
table before then attempting to read those remote stats. This might be
preferable because the imported stats are take less network bandwidth than
a table sample, and that allows for a much larger sample to be used on the
remote side (subject to their configuration, obviously).
>
> That's simple enough, but I wonder if that information wouldn't better be
>> used to defer the current local autoanalyze, using the thinking that we're
>> likely to get better stats after the remote catches up.
>
>
> My concern with deferring the local refresh is that exceeding this
> threshold does not guarantee that the remote ANALYZE will happen soon.
> Autovacuum could be disabled for the remote table, or its workers could be
> busy.
>
Or we could initiate it ourselves...I can revive that patch.
> As a smaller first step, would it make sense to emit a WARNING when
> importing statistics from a remote table whose modification count exceeds
> this threshold, while keeping the current import behavior?
>
That might have some merit too.
Keep the ideas coming.
^ permalink raw reply [nested|flat] 89+ messages in thread
end of thread, other threads:[~2026-09-25 19:59 UTC | newest]
Thread overview: 89+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2025-08-12 17:02 Import Statistics in postgres_fdw before resorting to sampling. Corey Huinker <corey.huinker@gmail.com>
2025-08-14 07:37 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2025-08-14 18:34 ` Corey Huinker <corey.huinker@gmail.com>
2025-09-12 05:17 ` Corey Huinker <corey.huinker@gmail.com>
2025-10-19 00:32 ` Corey Huinker <corey.huinker@gmail.com>
2025-10-20 06:45 ` Michael Paquier <michael@paquier.xyz>
2025-10-20 08:07 ` Michael Paquier <michael@paquier.xyz>
2025-11-03 05:26 ` Corey Huinker <corey.huinker@gmail.com>
2025-11-21 18:35 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2025-11-21 21:31 ` Corey Huinker <corey.huinker@gmail.com>
2025-11-23 07:27 ` Corey Huinker <corey.huinker@gmail.com>
2025-11-24 09:25 ` Chao Li <li.evan.chao@gmail.com>
2025-11-27 12:48 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2025-12-11 21:59 ` Corey Huinker <corey.huinker@gmail.com>
2025-12-12 06:11 ` Chao Li <li.evan.chao@gmail.com>
2025-12-12 19:03 ` Corey Huinker <corey.huinker@gmail.com>
2025-12-12 14:04 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2025-12-12 19:45 ` Corey Huinker <corey.huinker@gmail.com>
2025-12-13 19:12 ` Corey Huinker <corey.huinker@gmail.com>
2025-12-14 18:40 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2025-12-14 20:01 ` Corey Huinker <corey.huinker@gmail.com>
2025-12-15 10:01 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-01-03 10:06 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-01-04 02:56 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-06 11:58 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-01-06 14:12 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-06 21:38 ` Matheus Alcantara <matheusssilv97@gmail.com>
2026-01-07 02:18 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-01-07 06:04 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-07 15:17 ` Matheus Alcantara <matheusssilv97@gmail.com>
2026-01-07 19:17 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-07 19:27 ` Matheus Alcantara <matheusssilv97@gmail.com>
2026-01-08 19:42 ` Matheus Alcantara <matheusssilv97@gmail.com>
2026-01-09 09:35 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-01-09 16:21 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-14 19:41 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-15 13:47 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-01-15 17:57 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-16 07:10 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-01-16 16:49 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-18 02:53 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-21 20:51 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-22 10:15 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-01-22 11:29 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-01-22 22:20 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-23 15:43 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-01-23 17:15 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-27 05:47 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-01-27 08:04 ` Corey Huinker <corey.huinker@gmail.com>
2026-01-29 11:03 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-01-29 19:20 ` Corey Huinker <corey.huinker@gmail.com>
2026-02-12 14:29 ` Corey Huinker <corey.huinker@gmail.com>
2026-03-12 11:02 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-03-12 19:41 ` Corey Huinker <corey.huinker@gmail.com>
2026-03-13 12:16 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-03-13 15:36 ` Corey Huinker <corey.huinker@gmail.com>
2026-03-14 11:40 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-03-14 19:51 ` Corey Huinker <corey.huinker@gmail.com>
2026-03-14 20:05 ` Corey Huinker <corey.huinker@gmail.com>
2026-03-18 01:56 ` Corey Huinker <corey.huinker@gmail.com>
2026-03-30 09:32 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-03-30 20:04 ` Corey Huinker <corey.huinker@gmail.com>
2026-04-01 11:39 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-04-01 18:53 ` Corey Huinker <corey.huinker@gmail.com>
2026-04-02 11:05 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-04-02 17:14 ` Corey Huinker <corey.huinker@gmail.com>
2026-04-03 13:55 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-04-03 16:01 ` Corey Huinker <corey.huinker@gmail.com>
2026-04-05 11:05 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-04-07 10:09 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-04-08 11:24 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-04-08 13:11 ` Corey Huinker <corey.huinker@gmail.com>
2026-04-12 06:31 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-09-23 16:15 ` Nurlan Tulemisov <nurlan.tulemisov@gmail.com>
2026-09-23 18:26 ` Corey Huinker <corey.huinker@gmail.com>
2026-09-24 12:50 ` Nurlan Tulemisov <nurlan.tulemisov@gmail.com>
2026-09-25 19:59 ` Corey Huinker <corey.huinker@gmail.com>
2026-03-30 09:42 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-03-30 20:05 ` Corey Huinker <corey.huinker@gmail.com>
2026-04-12 18:15 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-04-13 04:53 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-04-30 18:04 ` Corey Huinker <corey.huinker@gmail.com>
2026-05-12 11:36 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-05-13 11:40 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-05-14 11:35 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-05-16 09:10 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2026-05-26 20:31 ` Corey Huinker <corey.huinker@gmail.com>
2025-11-27 12:46 ` Etsuro Fujita <etsuro.fujita@gmail.com>
2025-12-12 13:45 ` Etsuro Fujita <etsuro.fujita@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