From 036ac44c0f79167669ab83e1f88fd2b3521f886c Mon Sep 17 00:00:00 2001
From: Baji Shaik <baji.pgdev@gmail.com>
Date: Fri, 20 Nov 2026 09:26:53 -0600
Subject: [PATCH] postgres_fdw: Fall back to sampling when remote encoding
 differs

Statistics import matches attribute stats rows to local columns by
comparing attnames.  Those names arrive over the wire already
converted to the local server encoding, and that conversion is not
guaranteed to be one-to-one: some encodings map distinct remote code
points onto the same local one, so two differently-named remote
columns can arrive here as identical bytes.  Matching by name is not
safe in that case -- unless every name involved is plain ASCII, since
every server encoding we support is an ASCII-compatible superset and
can't exhibit this collision for ASCII-only names.

When any remote column name has a non-ASCII byte, detect a
remote/local server_encoding mismatch and fall back to the existing
sampling path with a warning, the same way other unsupported cases
(inherited tables, un-analyzed remote tables, etc.) already do.
PQparameterStatus(conn, "server_encoding") costs no extra round trip;
libpq already has it from the connection's startup parameters.

Author: Baji Shaik
---
 contrib/postgres_fdw/meson.build              |   1 +
 contrib/postgres_fdw/postgres_fdw.c           |  39 ++++++
 .../postgres_fdw/t/011_encoding_mismatch.pl   | 116 ++++++++++++++++++
 3 files changed, 156 insertions(+)
 create mode 100644 contrib/postgres_fdw/t/011_encoding_mismatch.pl

diff --git a/contrib/postgres_fdw/meson.build b/contrib/postgres_fdw/meson.build
index 3e2ed06b766..ec7d12a95ce 100644
--- a/contrib/postgres_fdw/meson.build
+++ b/contrib/postgres_fdw/meson.build
@@ -52,6 +52,7 @@ tests += {
     'tests': [
       't/001_auth_scram.pl',
       't/010_subscription.pl',
+      't/011_encoding_mismatch.pl',
     ],
   },
 }
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index ccc97d53286..dd1f3f1acca 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -26,6 +26,7 @@
 #include "executor/instrument.h"
 #include "foreign/fdwapi.h"
 #include "funcapi.h"
+#include "mb/pg_wchar.h"
 #include "miscadmin.h"
 #include "nodes/makefuncs.h"
 #include "nodes/nodeFuncs.h"
@@ -609,6 +610,8 @@ 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 bool remattrmap_has_non_ascii_name(const RemoteAttributeMapping *remattrmap,
+										  int attrcnt);
 static int	remattrmap_cmp(const void *v1, const void *v2);
 static bool match_attrmap(PGresult *res,
 						  const char *local_schemaname,
@@ -5915,6 +5918,24 @@ fetch_remote_statistics(Relation relation,
 		/* Try to get attribute stats if needed. */
 		if (attrcnt > 0)
 		{
+			/* Non-ASCII names can collide across encodings; fall back */
+			if (remattrmap_has_non_ascii_name(remattrmap, attrcnt))
+			{
+				const char *remote_encoding = PQparameterStatus(conn, "server_encoding");
+				const char *local_encoding = GetDatabaseEncodingName();
+
+				if (remote_encoding == NULL || strcmp(remote_encoding, local_encoding) != 0)
+				{
+					ereport(WARNING,
+							errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+							errmsg("could not import statistics for foreign table \"%s.%s\" --- remote server encoding \"%s\" differs from local encoding \"%s\"",
+								   local_schemaname, local_relname,
+								   remote_encoding ? remote_encoding : "unknown",
+								   local_encoding));
+					goto fetch_cleanup;
+				}
+			}
+
 			/*
 			 * The fetch_attstats query sends COLLATE "C" to the remote
 			 * server; if it hasn't got it, fallback to sampling.
@@ -6195,6 +6216,24 @@ attname_in_list(const char *attname, List *va_cols)
 	return false;
 }
 
+/*
+ * Does any remote_attname in the mapping have a non-ASCII byte?
+ */
+static bool
+remattrmap_has_non_ascii_name(const RemoteAttributeMapping *remattrmap, int attrcnt)
+{
+	for (int i = 0; i < attrcnt; i++)
+	{
+		for (const unsigned char *p = (const unsigned char *) remattrmap[i].remote_attname;
+			 *p; p++)
+		{
+			if (*p > 0x7F)
+				return true;
+		}
+	}
+	return false;
+}
+
 /*
  * Compare two RemoteAttributeMappings for sorting.
  */
diff --git a/contrib/postgres_fdw/t/011_encoding_mismatch.pl b/contrib/postgres_fdw/t/011_encoding_mismatch.pl
new file mode 100644
index 00000000000..b50c2030771
--- /dev/null
+++ b/contrib/postgres_fdw/t/011_encoding_mismatch.pl
@@ -0,0 +1,116 @@
+# Copyright (c) 2024-2026, PostgreSQL Global Development Group
+
+# Test that statistics import falls back to sampling, with a warning,
+# when the remote server's encoding differs from the local one, instead
+# of risking a name-matching mismatch caused by a lossy encoding
+# conversion of column names.
+
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Utils;
+use PostgreSQL::Test::Cluster;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('node');
+$node->init;
+$node->start;
+
+$node->safe_psql('postgres', "CREATE EXTENSION postgres_fdw");
+
+# Remote database with a different encoding, using non-ASCII column
+# names so that a naive byte-order merge could plausibly go wrong.
+$node->safe_psql(
+	'postgres',
+	"CREATE DATABASE remote_eucjp ENCODING 'EUC_JP' LC_COLLATE 'C' "
+	  . "LC_CTYPE 'C' TEMPLATE template0");
+$node->safe_psql(
+	'remote_eucjp',
+	"SET client_encoding = 'UTF8'; "
+	  . "CREATE TABLE \"\x{6CE8}\x{6587}\" ("
+	  . "\"\x{756A}\x{53F7}\" int, \"\x{9867}\x{5BA2}\" int, "
+	  . "\"\x{91D1}\x{984D}\" int, \"\x{65E5}\x{4ED8}\" int); "
+	  . "INSERT INTO \"\x{6CE8}\x{6587}\" "
+	  . "SELECT g, g, g, g FROM generate_series(1, 1000) g; "
+	  . "ANALYZE \"\x{6CE8}\x{6587}\"");
+
+my $port = $node->port;
+my $host = $node->host;
+$node->safe_psql(
+	'postgres', <<EOM);
+SET client_encoding = 'UTF8';
+CREATE SERVER eucjpsrv FOREIGN DATA WRAPPER postgres_fdw
+  OPTIONS (host '$host', port '$port', dbname 'remote_eucjp');
+CREATE USER MAPPING FOR CURRENT_USER SERVER eucjpsrv;
+ALTER SERVER eucjpsrv OPTIONS (ADD import_stats 'true');
+CREATE FOREIGN TABLE "\x{6CE8}\x{6587}" (
+  "\x{756A}\x{53F7}" int, "\x{9867}\x{5BA2}" int,
+  "\x{91D1}\x{984D}" int, "\x{65E5}\x{4ED8}" int)
+  SERVER eucjpsrv;
+EOM
+
+my ($ret, $stdout, $stderr) = $node->psql(
+	'postgres',
+	"SET client_encoding = 'UTF8'; ANALYZE \"\x{6CE8}\x{6587}\"");
+like(
+	$stderr,
+	qr/remote server encoding "EUC_JP" differs from local encoding "UTF8"/,
+	"ANALYZE falls back to sampling with a warning on encoding mismatch");
+
+# Sanity check: a same-encoding loopback must still import normally,
+# with no such warning.
+$node->safe_psql(
+	'postgres',
+	"CREATE TABLE plain (a int, b text); "
+	  . "INSERT INTO plain SELECT g, 'x' || g FROM generate_series(1, 1000) g; "
+	  . "ANALYZE plain");
+$node->safe_psql(
+	'postgres', <<EOM);
+CREATE SERVER sameenc FOREIGN DATA WRAPPER postgres_fdw
+  OPTIONS (host '$host', port '$port', dbname 'postgres');
+CREATE USER MAPPING FOR CURRENT_USER SERVER sameenc;
+ALTER SERVER sameenc OPTIONS (ADD import_stats 'true');
+CREATE FOREIGN TABLE plain_fgn (a int, b text)
+  SERVER sameenc OPTIONS (table_name 'plain');
+EOM
+
+($ret, $stdout, $stderr) = $node->psql(
+	'postgres', "SET client_min_messages = debug2; ANALYZE plain_fgn");
+is($ret, 0, "ANALYZE of same-encoding loopback succeeds");
+like(
+	$stderr,
+	qr/finished importing statistics for foreign table "public\.plain_fgn"/,
+	"same-encoding loopback still imports statistics normally");
+
+
+# A remote/local encoding mismatch with plain ASCII column names is safe
+# (every server encoding we support is an ASCII-compatible superset), so
+# it must still import normally, not fall back.
+$node->safe_psql(
+	'postgres',
+	"CREATE DATABASE remote_latin1 ENCODING 'LATIN1' LC_COLLATE 'C' "
+	  . "LC_CTYPE 'C' TEMPLATE template0");
+$node->safe_psql(
+	'remote_latin1',
+	"CREATE TABLE ascii_names (id int, name text); "
+	  . "INSERT INTO ascii_names SELECT g, 'x' || g FROM generate_series(1, 1000) g; "
+	  . "ANALYZE ascii_names");
+$node->safe_psql(
+	'postgres', <<EOM);
+CREATE SERVER latin1srv FOREIGN DATA WRAPPER postgres_fdw
+  OPTIONS (host '$host', port '$port', dbname 'remote_latin1');
+CREATE USER MAPPING FOR CURRENT_USER SERVER latin1srv;
+ALTER SERVER latin1srv OPTIONS (ADD import_stats 'true');
+CREATE FOREIGN TABLE ascii_names (id int, name text)
+  SERVER latin1srv;
+EOM
+
+($ret, $stdout, $stderr) = $node->psql(
+	'postgres', "SET client_min_messages = debug2; ANALYZE ascii_names");
+is($ret, 0, "ANALYZE of ASCII-named table on mismatched-encoding loopback succeeds");
+like(
+	$stderr,
+	qr/finished importing statistics for foreign table "public\.ascii_names"/,
+	"encoding mismatch with ASCII-only names still imports statistics, not just falls back");
+
+$node->stop;
+done_testing();
-- 
2.54.0 (Apple Git-157)

