From 53ca69bd8072ffdc2793f0ab8f3413474a122138 Mon Sep 17 00:00:00 2001 From: Shlok Kyal Date: Fri, 20 Nov 2026 16:22:41 +0530 Subject: [PATCH v3 2/2] Reject initially immediate deferrable subscription target constraints Reject DEFERRABLE INITIALLY IMMEDIATE primary key, unique, and exclusion constraints on logical replication targets, including their partitions. Validate targets during subscription creation, publication refresh, and apply, and reject adding such constraints to registered target tables. Logical replication preserves transaction boundaries but not publisher statement boundaries. Initially immediate rechecks during apply could therefore reject transient conflicts within an otherwise valid multi-row change. --- doc/src/sgml/logical-replication.sgml | 4 +- src/backend/catalog/index.c | 13 +++++ src/backend/catalog/pg_subscription.c | 30 ++++++++++++ src/backend/commands/tablecmds.c | 12 +++++ src/backend/executor/execReplication.c | 56 ++++++++++++++++++++++ src/include/catalog/pg_subscription_rel.h | 2 + src/include/executor/executor.h | 1 + src/test/subscription/t/003_constraints.pl | 53 ++++++++++++++++++++ src/test/subscription/t/035_conflicts.pl | 2 +- 9 files changed, 171 insertions(+), 2 deletions(-) diff --git a/doc/src/sgml/logical-replication.sgml b/doc/src/sgml/logical-replication.sgml index 0225901a666..d23630f0dca 100644 --- a/doc/src/sgml/logical-replication.sgml +++ b/doc/src/sgml/logical-replication.sgml @@ -2778,7 +2778,9 @@ CONTEXT: processing remote data for replication origin "pg_16395" during "INSER Constraints declared as DEFERRABLE use recheck triggers - that fired by default during logical replication. + that fire by default during logical replication. Subscriber tables, + including their partitions, cannot have unique, primary key, or exclusion + constraints declared DEFERRABLE INITIALLY IMMEDIATE. diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 99413556572..89dbcd35eb7 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -41,6 +41,7 @@ #include "catalog/index.h" #include "catalog/objectaccess.h" #include "catalog/partition.h" +#include "catalog/pg_subscription_rel.h" #include "catalog/pg_am.h" #include "catalog/pg_collation.h" #include "catalog/pg_constraint.h" @@ -1945,6 +1946,18 @@ index_constraint_create(Relation heapRelation, /* constraint creation support doesn't work while bootstrapping */ Assert(!IsBootstrapProcessingMode()); + /* + * Reject DEFERRABLE INITIALLY IMMEDIATE constraints on replication + * targets: apply worker does not preserve publisher statement boundaries, + * so statement-end rechecks could reject valid transient conflicts. + */ + if (deferrable && !initdeferred && RelationOrAncestorIsSubscribed(heapRelation)) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot create constraint \"%s\" on logical replication target relation \"%s\"", + constraintName, RelationGetRelationName(heapRelation)), + errdetail("Deferrable initially immediate unique, primary key, and exclusion constraints are not supported."))); + /* enforce system-table restriction */ if (!allow_system_table_mods && IsSystemRelation(heapRelation) && diff --git a/src/backend/catalog/pg_subscription.c b/src/backend/catalog/pg_subscription.c index 8dd24cabe89..1ab6d4270b7 100644 --- a/src/backend/catalog/pg_subscription.c +++ b/src/backend/catalog/pg_subscription.c @@ -19,6 +19,7 @@ #include "access/htup_details.h" #include "access/tableam.h" #include "catalog/indexing.h" +#include "catalog/partition.h" #include "catalog/pg_foreign_server.h" #include "catalog/pg_subscription.h" #include "catalog/pg_subscription_rel.h" @@ -30,6 +31,7 @@ #include "utils/acl.h" #include "utils/array.h" #include "utils/builtins.h" +#include "utils/catcache.h" #include "utils/fmgroids.h" #include "utils/lsyscache.h" #include "utils/memutils.h" @@ -776,3 +778,31 @@ UpdateDeadTupleRetentionStatus(Oid subid, bool active) table_close(rel, NoLock); } + +/* + * Check if the given relation or any of its ancestor is subscribed. + */ +bool +RelationOrAncestorIsSubscribed(Relation rel) +{ + List *relids = NIL; + bool found = false; + + if (rel->rd_rel->relispartition) + relids = get_partition_ancestors(RelationGetRelid(rel)); + relids = lcons_oid(RelationGetRelid(rel), relids); + + foreach_oid(relid, relids) + { + CatCList *subscriptions = SearchSysCacheList1(SUBSCRIPTIONRELMAP, + ObjectIdGetDatum(relid)); + + found = subscriptions->n_members > 0; + ReleaseSysCacheList(subscriptions); + if (found) + break; + } + + list_free(relids); + return found; +} diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 9e363a44c20..5162b7da41f 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -35,6 +35,7 @@ #include "catalog/namespace.h" #include "catalog/objectaccess.h" #include "catalog/partition.h" +#include "catalog/pg_subscription_rel.h" #include "catalog/pg_am.h" #include "catalog/pg_attrdef.h" #include "catalog/pg_cast.h" @@ -21843,6 +21844,17 @@ ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd, check_new_partition_bound(RelationGetRelationName(attachrel), rel, cmd->bound, pstate); + if (RelationOrAncestorIsSubscribed(rel)) + { + foreach_oid(childoid, attachrel_children) + { + Relation child = table_open(childoid, NoLock); + + CheckSubscriptionTargetConstraints(child); + table_close(child, NoLock); + } + } + /* OK to create inheritance. Rest of the checks performed there */ CreateInheritance(attachrel, rel, true); diff --git a/src/backend/executor/execReplication.c b/src/backend/executor/execReplication.c index 5b278a9c93f..b19ffacb3a9 100644 --- a/src/backend/executor/execReplication.c +++ b/src/backend/executor/execReplication.c @@ -19,12 +19,14 @@ #include "access/genam.h" #include "access/gist.h" #include "access/relscan.h" +#include "access/table.h" #include "access/tableam.h" #include "access/transam.h" #include "access/xact.h" #include "access/heapam.h" #include "catalog/catalog.h" #include "catalog/pg_am_d.h" +#include "catalog/pg_inherits.h" #include "commands/trigger.h" #include "executor/executor.h" #include "executor/nodeModifyTable.h" @@ -32,6 +34,7 @@ #include "replication/logicalrelation.h" #include "storage/lmgr.h" #include "utils/builtins.h" +#include "utils/fmgroids.h" #include "utils/lsyscache.h" #include "utils/rel.h" #include "utils/snapmgr.h" @@ -1300,4 +1303,57 @@ CheckSubscriptionTargetRel(Oid relid, char remoterelkind, nspname, relname, remoterelkind == RELKIND_SEQUENCE ? "sequence" : "table", localrelkind == RELKIND_SEQUENCE ? "sequence" : "table")); + + /* + * Reject tables with DEFERRABLE INITIALLY IMMEDIATE constraints on the + * relation. + */ + if (localrelkind != RELKIND_SEQUENCE) + { + List *relids; + + LockRelationOid(relid, AccessShareLock); + if (localrelkind == RELKIND_PARTITIONED_TABLE) + relids = find_all_inheritors(relid, AccessShareLock, NULL); + else + relids = list_make1_oid(relid); + + foreach_oid(targetrelid, relids) + { + Relation rel = table_open(targetrelid, NoLock); + + CheckSubscriptionTargetConstraints(rel); + table_close(rel, AccessShareLock); + } + + list_free(relids); + } +} + +/* + * Checks if the given relation has any deferrable initially immediate + * unique, primary key, or exclusion constraints, which are not supported + * for logical replication targets. + */ +void +CheckSubscriptionTargetConstraints(Relation rel) +{ + TriggerDesc *trigdesc = rel->trigdesc; + + if (trigdesc == NULL) + return; + + for (int index = 0; index < trigdesc->numtriggers; index++) + { + Trigger *trigger = &trigdesc->triggers[index]; + + if (trigger->tgisinternal && trigger->tgfoid == F_UNIQUE_KEY_RECHECK && + trigger->tgdeferrable && !trigger->tginitdeferred) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot use relation \"%s.%s\" as logical replication target", + get_namespace_name(RelationGetNamespace(rel)), + RelationGetRelationName(rel)), + errdetail("Deferrable initially immediate unique, primary key, and exclusion constraints are not supported."))); + } } diff --git a/src/include/catalog/pg_subscription_rel.h b/src/include/catalog/pg_subscription_rel.h index 502640d3018..28de21ee559 100644 --- a/src/include/catalog/pg_subscription_rel.h +++ b/src/include/catalog/pg_subscription_rel.h @@ -22,6 +22,7 @@ #include "catalog/genbki.h" #include "catalog/pg_subscription_rel_d.h" /* IWYU pragma: export */ #include "nodes/pg_list.h" +#include "utils/relcache.h" /* ---------------- * pg_subscription_rel definition. cpp turns this into @@ -117,6 +118,7 @@ extern char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn); extern void RemoveSubscriptionRel(Oid subid, Oid relid); extern bool HasSubscriptionTables(Oid subid); +extern bool RelationOrAncestorIsSubscribed(Relation rel); extern List *GetSubscriptionRelations(Oid subid, bool tables, bool sequences, bool not_ready); diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h index 95498600aba..95e405cccfb 100644 --- a/src/include/executor/executor.h +++ b/src/include/executor/executor.h @@ -806,6 +806,7 @@ extern void ExecSimpleRelationDelete(ResultRelInfo *resultRelInfo, TupleTableSlot *searchslot); extern void CheckCmdReplicaIdentity(Relation rel, CmdType cmd); +extern void CheckSubscriptionTargetConstraints(Relation rel); extern void CheckSubscriptionTargetRel(Oid relid, char remoterelkind, const char *nspname, const char *relname); diff --git a/src/test/subscription/t/003_constraints.pl b/src/test/subscription/t/003_constraints.pl index 6742593d5bc..0a748756d8f 100644 --- a/src/test/subscription/t/003_constraints.pl +++ b/src/test/subscription/t/003_constraints.pl @@ -209,12 +209,65 @@ $node_subscriber->safe_psql( )); $node_publisher->wait_for_catchup('tap_sub'); +# Adding an initially immediate constraint to a subscribed table must fail. +my ($ret, $stdout, $stderr) = $node_subscriber->psql('postgres', + "ALTER TABLE tab_deferred ADD CONSTRAINT immediate_unique UNIQUE (val) DEFERRABLE INITIALLY IMMEDIATE" +); +like( + $stderr, + qr/cannot create constraint "immediate_unique" on logical replication target relation "tab_deferred"/, + 'constraint DDL reports subscription target restriction'); + # Cleanup $node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub; DROP TABLE tab_deferred'); $node_publisher->safe_psql('postgres', 'DROP TABLE tab_deferred; DROP PUBLICATION tap_pub'); +# Create one initially immediate constraint per table on both nodes. +for my $node ($node_publisher, $node_subscriber) +{ + $node->safe_psql( + 'postgres', qq( +CREATE TABLE immediate_primary (val int PRIMARY KEY DEFERRABLE INITIALLY IMMEDIATE); +CREATE TABLE immediate_unique (val int UNIQUE DEFERRABLE INITIALLY IMMEDIATE); +CREATE TABLE immediate_exclusion (val int4range, EXCLUDE USING gist (val WITH &&) DEFERRABLE INITIALLY IMMEDIATE); +)); +} + +# Publish only one table at a time, and reject each subscription attempt. +$node_publisher->safe_psql('postgres', + 'CREATE PUBLICATION tap_pub FOR TABLE immediate_primary'); +($ret, $stdout, $stderr) = $node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION rejected_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub" +); +like( + $stderr, + qr/Deferrable initially immediate unique, primary key, and exclusion constraints are not supported/, + 'primary key reports unsupported timing during subscription creation'); + +$node_publisher->safe_psql('postgres', + 'ALTER PUBLICATION tap_pub SET TABLE immediate_unique'); +($ret, $stdout, $stderr) = $node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION rejected_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub" +); +like( + $stderr, + qr/Deferrable initially immediate unique, primary key, and exclusion constraints are not supported/, + 'unique constraint reports unsupported timing during subscription creation' +); + +$node_publisher->safe_psql('postgres', + 'ALTER PUBLICATION tap_pub SET TABLE immediate_exclusion'); +($ret, $stdout, $stderr) = $node_subscriber->psql('postgres', + "CREATE SUBSCRIPTION rejected_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub" +); +like( + $stderr, + qr/Deferrable initially immediate unique, primary key, and exclusion constraints are not supported/, + 'exclusion constraint reports unsupported timing during subscription creation' +); + $node_subscriber->stop('fast'); $node_publisher->stop('fast'); diff --git a/src/test/subscription/t/035_conflicts.pl b/src/test/subscription/t/035_conflicts.pl index 8abd7eb6d94..82a8a75834b 100644 --- a/src/test/subscription/t/035_conflicts.pl +++ b/src/test/subscription/t/035_conflicts.pl @@ -595,7 +595,7 @@ $node_A->poll_query_until('postgres', # Then delete a local row that has the same key but a different value. $node_A->safe_psql( 'postgres', " - ALTER TABLE tab_defer ADD PRIMARY KEY (a) DEFERRABLE; + ALTER TABLE tab_defer ADD PRIMARY KEY (a) DEFERRABLE INITIALLY DEFERRED; INSERT INTO tab_defer VALUES (1, 10); DELETE FROM tab_defer WHERE a = 1;"); -- 2.34.1